-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathencoder.go
95 lines (77 loc) · 1.77 KB
/
encoder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//
// Copyright (c) 2018- yutopp ([email protected])
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
//
package flv
import (
"bytes"
"encoding/binary"
"io"
"github.com/yutopp/go-flv/tag"
)
type Encoder struct {
w io.Writer
header *Header
encodedOnce bool
cacheBuffer bytes.Buffer
}
func NewEncoder(w io.Writer, flags Flags) (*Encoder, error) {
header := &Header{
Version: 1, // only supports 1 currently
Flags: flags,
DataOffset: HeaderLength,
}
if err := EncodeFlvHeader(w, header); err != nil {
return nil, err
}
return &Encoder{
w: w,
header: header,
}, nil
}
func (enc *Encoder) Header() *Header {
return enc.header
}
func (enc *Encoder) Encode(flvTag *tag.FlvTag) error {
var previousTagSize uint32
if !enc.encodedOnce {
goto tagSize
}
body:
enc.cacheBuffer.Reset()
if err := tag.EncodeFlvTag(&enc.cacheBuffer, flvTag); err != nil {
return err
}
previousTagSize = uint32(enc.cacheBuffer.Len())
if _, err := io.CopyN(enc.w, &enc.cacheBuffer, int64(previousTagSize)); err != nil {
return err
}
tagSize:
buf := make([]byte, 4)
binary.BigEndian.PutUint32(buf, previousTagSize)
if _, err := enc.w.Write(buf); err != nil {
return err
}
if !enc.encodedOnce {
enc.encodedOnce = true
goto body
}
return nil
}
func EncodeFlvHeader(w io.Writer, header *Header) error {
buf := make([]byte, HeaderLength)
copy(buf, HeaderSignature)
buf[3] = header.Version
buf[4] = 0
if (header.Flags & FlagsAudio) != 0 {
buf[4] |= 0x04 // 0b00000100
}
if (header.Flags & FlagsVideo) != 0 {
buf[4] |= 0x01 // 0b00000001
}
binary.BigEndian.PutUint32(buf[5:9], HeaderLength)
_, err := w.Write(buf)
return err
}