forked from godeep/mp4
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmp4.go
126 lines (114 loc) · 2.26 KB
/
mp4.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package mp4
import (
"io"
"math"
"strconv"
"time"
)
// A MPEG-4 media
//
// A MPEG-4 media contains three main boxes :
//
// ftyp : the file type box
// moov : the movie box (meta-data)
// mdat : the media data (chunks and samples)
//
// Other boxes can also be present (pdin, moof, mfra, free, ...), but are not decoded.
type MP4 struct {
Ftyp *FtypBox
Moov *MoovBox
Mdat *MdatBox
boxes []Box
}
// Decode decodes a media from a Reader
func Decode(r io.Reader) (*MP4, error) {
v := &MP4{
boxes: []Box{},
}
LoopBoxes:
for {
h, err := DecodeHeader(r)
if err != nil {
return nil, err
}
box, err := DecodeBox(h, r)
if err != nil {
return nil, err
}
switch h.Type {
case "ftyp":
v.Ftyp = box.(*FtypBox)
case "moov":
v.Moov = box.(*MoovBox)
case "mdat":
v.Mdat = box.(*MdatBox)
v.Mdat.ContentSize = h.Size - BoxHeaderSize
break LoopBoxes
default:
v.boxes = append(v.boxes, box)
}
}
return v, nil
}
// Dump displays some information about a media
func (m *MP4) Dump() {
m.Ftyp.Dump()
m.Moov.Dump()
}
// Boxes lists the top-level boxes from a media
func (m *MP4) Boxes() []Box {
return m.boxes
}
// Encode encodes a media to a Writer
func (m *MP4) Encode(w io.Writer) error {
err := m.Ftyp.Encode(w)
if err != nil {
return err
}
err = m.Moov.Encode(w)
if err != nil {
return err
}
for _, b := range m.boxes {
err = b.Encode(w)
if err != nil {
return err
}
}
err = m.Mdat.Encode(w)
if err != nil {
return err
}
return nil
}
func (m *MP4) Size() (size int) {
size += m.Ftyp.Size()
size += m.Moov.Size()
size += m.Mdat.Size()
for _, b := range m.Boxes() {
size += b.Size()
}
return
}
func (m *MP4) Duration() time.Duration {
return time.Second * time.Duration(m.Moov.Mvhd.Duration) / time.Duration(m.Moov.Mvhd.Timescale)
}
func (m *MP4) VideoDimensions() (int, int) {
for _, trak := range m.Moov.Trak {
h, _ := strconv.ParseFloat(trak.Tkhd.Height.String(), 64)
w, _ := strconv.ParseFloat(trak.Tkhd.Width.String(), 64)
if h > 0 && w > 0 {
return int(math.Floor(w)), int(math.Floor(h))
}
}
return 0, 0
}
func (m *MP4) AudioVolume() float64 {
for _, trak := range m.Moov.Trak {
vol, _ := strconv.ParseFloat(trak.Tkhd.Volume.String(), 64)
if vol > 0 {
return vol
}
}
return 0.0
}