mediamtx/internal/rtmp/chunk/chunk0.go

62 lines
1.6 KiB
Go
Raw Normal View History

2022-06-04 23:06:40 +00:00
package chunk
2022-05-13 17:04:47 +00:00
import (
"io"
)
// Chunk0 is a type 0 chunk.
// This type MUST be used at
// the start of a chunk stream, and whenever the stream timestamp goes
// backward (e.g., because of a backward seek).
type Chunk0 struct {
2022-05-13 18:53:52 +00:00
ChunkStreamID byte
Timestamp uint32
Type MessageType
2022-05-13 18:53:52 +00:00
MessageStreamID uint32
BodyLen uint32
Body []byte
2022-05-13 17:04:47 +00:00
}
// Read reads the chunk.
2022-06-08 18:47:36 +00:00
func (c *Chunk0) Read(r io.Reader, chunkMaxBodyLen uint32) error {
2022-05-13 17:04:47 +00:00
header := make([]byte, 12)
_, err := io.ReadFull(r, header)
2022-05-13 17:04:47 +00:00
if err != nil {
return err
}
2022-05-13 18:53:52 +00:00
c.ChunkStreamID = header[0] & 0x3F
2022-06-04 23:06:40 +00:00
c.Timestamp = uint32(header[1])<<16 | uint32(header[2])<<8 | uint32(header[3])
2022-05-13 18:53:52 +00:00
c.BodyLen = uint32(header[4])<<16 | uint32(header[5])<<8 | uint32(header[6])
c.Type = MessageType(header[7])
2022-05-13 18:53:52 +00:00
c.MessageStreamID = uint32(header[8])<<24 | uint32(header[9])<<16 | uint32(header[10])<<8 | uint32(header[11])
2022-05-13 17:04:47 +00:00
2022-06-08 18:47:36 +00:00
chunkBodyLen := c.BodyLen
2022-05-13 17:04:47 +00:00
if chunkBodyLen > chunkMaxBodyLen {
chunkBodyLen = chunkMaxBodyLen
}
2022-05-13 18:53:52 +00:00
c.Body = make([]byte, chunkBodyLen)
_, err = io.ReadFull(r, c.Body)
2022-05-13 17:04:47 +00:00
return err
}
2022-06-27 15:51:54 +00:00
// Marshal writes the chunk.
func (c Chunk0) Marshal() ([]byte, error) {
2022-06-08 12:07:30 +00:00
buf := make([]byte, 12+len(c.Body))
buf[0] = c.ChunkStreamID
buf[1] = byte(c.Timestamp >> 16)
buf[2] = byte(c.Timestamp >> 8)
buf[3] = byte(c.Timestamp)
buf[4] = byte(c.BodyLen >> 16)
buf[5] = byte(c.BodyLen >> 8)
buf[6] = byte(c.BodyLen)
buf[7] = byte(c.Type)
buf[8] = byte(c.MessageStreamID >> 24)
buf[9] = byte(c.MessageStreamID >> 16)
buf[10] = byte(c.MessageStreamID >> 8)
buf[11] = byte(c.MessageStreamID)
copy(buf[12:], c.Body)
return buf, nil
2022-05-13 17:04:47 +00:00
}