aboutsummaryrefslogtreecommitdiff
path: root/track/track.go
blob: 9471cae68ab52ca71ace602139bafb5d1a4ea189 (plain) (blame)
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
package track

import (
	"encoding/binary"
	"errors"
	"fmt"

	"git.onurgunduz.com/mp4"
)

// TrackKind classifies a track as video, audio, or unknown.
type TrackKind int

const (
	TrackUnknown TrackKind = iota
	TrackVideo
	TrackAudio
)

// trackRaw holds internal parsing state and raw box data.
type trackRaw struct {
	// Raw sub-slices of moov buffer.
	stsd []byte
	tkhd []byte // tkhd data (after version+flags header)
	mdhd []byte // mdhd data (after version+flags header)
	hdlr []byte // entire hdlr raw box
	dinf []byte // entire dinf raw box

	tkhdVersion uint8
	tkhdFlags   uint32
	mdhdVersion uint8
	hasVmhd     bool
	hasDinf     bool

	elstMediaTime int64 // edit list media time (media timescale)
	hasElst       bool

	// Raw sample table data.
	stszData    []byte
	sttsData    []byte
	stscData    []byte
	cttsData    []byte
	cttsVersion uint8
	stssData    []byte
	stcoData    []byte
	co64Data    []byte
	hasCo64     bool
	sampleCount uint32

	// Codec string builder buffer.
	codecBuf [24]byte
	codecLen uint8
}

// Track holds metadata for one track parsed from a moov box.
type Track struct {
	ID        uint32
	Kind      TrackKind
	TimeScale uint32
	Duration  uint64

	Width         uint16
	Height        uint16
	DisplayWidth  uint16
	DisplayHeight uint16
	ChannelCount  uint16
	SampleRate    uint32
	SampleSize    uint16

	PixelAspectHorizontal uint32
	PixelAspectVertical   uint32
	ColorPrimaries        uint16
	ColorTransfer         uint16
	ColorMatrix           uint16
	FullColorRange        bool
	HasColor              bool
	RotationDegrees       uint16

	Samples       []Sample
	SampleDescIdx uint32

	raw trackRaw
}

// Codec returns the MIME codec string (e.g. "avc1.64001e", "mp4a.40.2").
func (t *Track) Codec() string { return string(t.raw.codecBuf[:t.raw.codecLen]) }

// StsdRaw returns the raw stsd box data (entire box including header).
func (t *Track) StsdRaw() []byte { return t.raw.stsd }

// TkhdRaw returns the tkhd box data (after version+flags header).
func (t *Track) TkhdRaw() []byte { return t.raw.tkhd }

// MdhdRaw returns the mdhd box data (after version+flags header).
func (t *Track) MdhdRaw() []byte { return t.raw.mdhd }

// HdlrRaw returns the entire hdlr raw box.
func (t *Track) HdlrRaw() []byte { return t.raw.hdlr }

// DinfRaw returns the entire dinf raw box.
func (t *Track) DinfRaw() []byte { return t.raw.dinf }

// TkhdVersion returns the version field of the tkhd box.
func (t *Track) TkhdVersion() uint8 { return t.raw.tkhdVersion }

// TkhdFlags returns the flags field of the tkhd box.
func (t *Track) TkhdFlags() uint32 { return t.raw.tkhdFlags }

// MdhdVersion returns the version field of the mdhd box.
func (t *Track) MdhdVersion() uint8 { return t.raw.mdhdVersion }

// HasVmhd returns true if the track has a vmhd box (video media header).
func (t *Track) HasVmhd() bool { return t.raw.hasVmhd }

// HasDinf returns true if the track has a dinf box (data information).
func (t *Track) HasDinf() bool { return t.raw.hasDinf }

// EditMediaTime returns the media time of the track's edit list and whether the
// track has one. It reproduces the initial composition offset, so the first
// frame is presented at time zero.
func (t *Track) EditMediaTime() (int64, bool) {
	return t.raw.elstMediaTime, t.raw.hasElst
}

// FindTrack returns the track with the given ID, or nil.
func FindTrack(tracks []*Track, id uint32) *Track {
	for _, t := range tracks {
		if t.ID == id {
			return t
		}
	}
	return nil
}

func (t *Track) setCodec(s string) {
	n := copy(t.raw.codecBuf[:], s)
	t.raw.codecLen = uint8(n)
}

func (t *Track) appendCodec(s string) {
	n := copy(t.raw.codecBuf[t.raw.codecLen:], s)
	t.raw.codecLen += uint8(n)
}

// appendAvcCProfile appends "XXYYZZ" hex profile to the codec buffer.
func (t *Track) appendAvcCProfile(profile, compat, level byte) {
	i := t.raw.codecLen
	t.raw.codecBuf[i+0] = hexChars[profile>>4]
	t.raw.codecBuf[i+1] = hexChars[profile&0x0f]
	t.raw.codecBuf[i+2] = hexChars[compat>>4]
	t.raw.codecBuf[i+3] = hexChars[compat&0x0f]
	t.raw.codecBuf[i+4] = hexChars[level>>4]
	t.raw.codecBuf[i+5] = hexChars[level&0x0f]
	t.raw.codecLen += 6
}

// appendAv1CProfile appends ".P.LLT.DD" to the codec buffer from av1C record
// data: seq_profile, 2-digit seq_level_idx, tier (M or H), and bit depth.
func (t *Track) appendAv1CProfile(d []byte) {
	seqProfile := d[1] >> 5
	seqLevelIdx := d[1] & 0x1f
	seqTier := d[2] >> 7
	highBitdepth := (d[2] >> 6) & 0x01
	twelveBit := (d[2] >> 5) & 0x01

	bitDepth := byte(8)
	if highBitdepth == 1 {
		if seqProfile == 2 && twelveBit == 1 {
			bitDepth = 12
		} else {
			bitDepth = 10
		}
	}
	tier := byte('M')
	if seqTier == 1 {
		tier = 'H'
	}

	i := t.raw.codecLen
	b := t.raw.codecBuf[:]
	b[i+0] = '.'
	b[i+1] = '0' + seqProfile
	b[i+2] = '.'
	b[i+3] = '0' + seqLevelIdx/10
	b[i+4] = '0' + seqLevelIdx%10
	b[i+5] = tier
	b[i+6] = '.'
	b[i+7] = '0' + bitDepth/10
	b[i+8] = '0' + bitDepth%10
	t.raw.codecLen += 9
}

// appendEsdsCodec appends ".OTI.audioConfig" to the codec buffer from esds data.
func (t *Track) appendEsdsCodec(data []byte) {
	oti, audioConfig := parseEsds(data)
	if oti == 0 {
		return
	}
	t.appendCodec(".")
	if oti >= 16 {
		t.raw.codecBuf[t.raw.codecLen] = hexChars[oti>>4]
		t.raw.codecLen++
	}
	t.raw.codecBuf[t.raw.codecLen] = hexChars[oti&0x0f]
	t.raw.codecLen++
	if audioConfig > 0 {
		t.appendCodec(".")
		if audioConfig >= 10 {
			t.raw.codecBuf[t.raw.codecLen] = '0' + audioConfig/10
			t.raw.codecLen++
		}
		t.raw.codecBuf[t.raw.codecLen] = '0' + audioConfig%10
		t.raw.codecLen++
	}
}

// parseEsds extracts OTI and audio object type from esds box data.
func parseEsds(data []byte) (oti, audioConfig byte) {
	if len(data) < 2 {
		return 0, 0
	}
	ptr, end := 0, len(data)
	if data[ptr] != 0x03 {
		return 0, 0
	}
	ptr++
	ptr = skipDescLen(data, ptr, end)
	if ptr < 0 || ptr+3 > end {
		return 0, 0
	}
	flags := data[ptr+2]
	ptr += 3
	if flags&0x80 != 0 {
		ptr += 2
	}
	if flags&0x40 != 0 {
		if ptr >= end {
			return 0, 0
		}
		ptr += 1 + int(data[ptr])
	}
	if flags&0x20 != 0 {
		ptr += 2
	}
	if ptr >= end || data[ptr] != 0x04 {
		return 0, 0
	}
	ptr++
	ptr = skipDescLen(data, ptr, end)
	if ptr < 0 || ptr+13 > end {
		return 0, 0
	}
	oti = data[ptr]
	if oti == 0 {
		return 0, 0
	}
	ptr += 13
	if ptr >= end || data[ptr] != 0x05 {
		return oti, 0
	}
	ptr++
	ptr = skipDescLen(data, ptr, end)
	if ptr < 0 || ptr >= end {
		return oti, 0
	}
	audioConfig = (data[ptr] & 0xf8) >> 3
	return oti, audioConfig
}

func skipDescLen(data []byte, ptr, end int) int {
	for ptr < end {
		b := data[ptr]
		ptr++
		if b&0x80 == 0 {
			return ptr
		}
	}
	return -1
}

// Sample represents a single media sample. The sync-sample flag is stored in
// the high bit of the size field, which keeps the struct at 32 bytes. Read the
// size and the flag through the Size and IsSync methods.
type Sample struct {
	Offset             int64
	DTS                int64
	TrackID            uint32
	size               uint32
	Duration           uint32
	PresentationOffset int32
}

// syncBit marks a sync sample in the high bit of Sample.size.
const syncBit uint32 = 1 << 31

// Size returns the sample size in bytes.
func (s Sample) Size() uint32 { return s.size &^ syncBit }

// IsSync reports whether the sample is a sync sample (keyframe).
func (s Sample) IsSync() bool { return s.size&syncBit != 0 }

// SetSize sets the sample's byte size and sync flag, which share one packed
// field. It is how code that produces samples, rather than parsing them, fills
// a Sample. The size must stay below the sync bit, 2 GiB.
func (s *Sample) SetSize(size uint32, sync bool) {
	s.size = size &^ syncBit
	if sync {
		s.size |= syncBit
	}
}

// PTS returns the presentation timestamp.
func (s Sample) PTS() int64 {
	return s.DTS + int64(s.PresentationOffset)
}

// TrackSampleStats holds aggregated stats for samples belonging to one track.
type TrackSampleStats struct {
	TrackID     uint32
	TimeScale   uint32
	Duration    uint64
	EarliestPTS int64
	SampleCount int
}

// CollectTrackSampleStats aggregates sample count, duration, and earliest PTS
// per track. The returned slice contains only tracks that have at least one sample.
func CollectTrackSampleStats(dst []TrackSampleStats, tracks []*Track, samples []Sample) []TrackSampleStats {
	if cap(dst) < len(tracks) {
		dst = make([]TrackSampleStats, len(tracks))
	} else {
		dst = dst[:len(tracks)]
	}

	for i, t := range tracks {
		dst[i] = TrackSampleStats{
			TrackID:     t.ID,
			TimeScale:   t.TimeScale,
			EarliestPTS: -1,
		}
	}

	for i := range samples {
		s := &samples[i]
		for j := range dst {
			if dst[j].TrackID != s.TrackID {
				continue
			}
			st := &dst[j]
			st.SampleCount++
			st.Duration += uint64(s.Duration)
			pts := s.PTS()
			if st.EarliestPTS < 0 || pts < st.EarliestPTS {
				st.EarliestPTS = pts
			}
			break
		}
	}

	out := dst[:0]
	for i := range dst {
		if dst[i].SampleCount > 0 {
			out = append(out, dst[i])
		}
	}
	return out
}

var (
	htVide = [4]byte{'v', 'i', 'd', 'e'}
	htSoun = [4]byte{'s', 'o', 'u', 'n'}
)

var (
	ErrMoovNotFound = errors.New("moov box not found in buffer")
	ErrInvalidTrack = errors.New("invalid track data")
	ErrCorruptData  = errors.New("corrupt data")
)

// ParseTracks parses a moov box buffer and returns the tracks found with
// their samples fully populated. The moov buffer must include the box header
// (the full top-level moov box). The movie timescale and duration (from mvhd)
// are also returned.
//
// Returns an error if the moov box is not found, if no playable tracks are
// found, or if sample tables cannot be parsed for any track.
func ParseTracks(moovBuf []byte) ([]*Track, uint32, uint64, error) {
	return ParseTracksInto(nil, moovBuf)
}

// ParseTracksInto behaves like ParseTracks but reuses the Track structs in dst
// and their sample slices, which avoids most allocations when the new file has
// the same shape as the previous one. Pass the slice returned by an earlier
// call as dst. The tracks in dst must not be used after this call.
func ParseTracksInto(dst []*Track, moovBuf []byte) ([]*Track, uint32, uint64, error) {
	mr := mp4.NewReader(moovBuf)
	if !mr.Next() || mr.Type() != mp4.TypeMoov {
		return nil, 0, 0, ErrMoovNotFound
	}

	var tracks []*Track
	var timescale uint32
	var duration uint64
	reused := 0

	mr.Enter()
	for mr.Next() {
		switch mr.Type() {
		case mp4.TypeMvhd:
			ts, dur, _ := mr.ReadMvhd()
			timescale = ts
			duration = dur
		case mp4.TypeTrak:
			var t *Track
			if reused < len(dst) {
				t = dst[reused]
				resetTrack(t)
			} else {
				t = &Track{}
			}
			reused++
			if parseTrakInto(&mr, t) {
				tracks = append(tracks, t)
			}
		}
	}
	mr.Exit()

	// Parse samples for each track, dropping any that fail. The result reuses
	// dst's backing array when it fits, so repeated same-shape parses don't
	// allocate; overwriting in place is safe as kept tracks only move earlier.
	var valid []*Track
	if cap(dst) >= len(tracks) {
		valid = dst[:0]
	} else {
		valid = make([]*Track, 0, len(tracks))
	}
	for _, t := range tracks {
		if err := t.parseSamples(); err != nil {
			continue
		}
		valid = append(valid, t)
	}

	return valid, timescale, duration, nil
}

// resetTrack clears t for reuse while keeping the backing array of its sample
// slice, so a later parse can refill it without allocating.
func resetTrack(t *Track) {
	samples := t.Samples[:0]
	*t = Track{}
	t.Samples = samples
}

// parseTrakInto fills track from a trak box and reports whether it is a valid,
// playable track.
func parseTrakInto(mr *mp4.Reader, track *Track) bool {
	mr.Enter()
	defer mr.Exit()

	for mr.Next() {
		switch mr.Type() {
		case mp4.TypeTkhd:
			track.raw.tkhdVersion = mr.Version()
			track.raw.tkhdFlags = mr.Flags()
			track.raw.tkhd = mr.Data()
			trackId, _, w, h := mr.ReadTkhd()
			track.ID = trackId
			track.DisplayWidth = uint16(w >> 16)
			track.DisplayHeight = uint16(h >> 16)
			track.RotationDegrees = tkhdRotation(track.raw.tkhd, track.raw.tkhdVersion)
		case mp4.TypeEdts:
			parseEdts(mr, track)
		case mp4.TypeMdia:
			parseMdia(mr, track)
		}
	}

	return track.ID != 0 && track.raw.codecLen != 0
}

// parseEdts reads the first edit list entry's media time, used to reproduce the
// initial composition offset in the output's init segment.
func parseEdts(mr *mp4.Reader, track *Track) {
	mr.Enter()
	defer mr.Exit()
	for mr.Next() {
		if mr.Type() == mp4.TypeElst {
			if mt, ok := mr.ReadElst(); ok {
				track.raw.elstMediaTime = mt
				track.raw.hasElst = true
			}
			return
		}
	}
}

func parseMdia(mr *mp4.Reader, track *Track) {
	mr.Enter()
	defer mr.Exit()

	var handlerType [4]byte

	for mr.Next() {
		switch mr.Type() {
		case mp4.TypeMdhd:
			track.raw.mdhdVersion = mr.Version()
			track.raw.mdhd = mr.Data()
			ts, dur, _ := mr.ReadMdhd()
			track.TimeScale = ts
			track.Duration = dur
		case mp4.TypeHdlr:
			track.raw.hdlr = mr.RawBox()
			handlerType = mr.ReadHdlr()
		case mp4.TypeMinf:
			parseMinf(mr, track, handlerType)
		}
	}
}

func parseMinf(mr *mp4.Reader, track *Track, handlerType [4]byte) {
	mr.Enter()
	defer mr.Exit()

	for mr.Next() {
		switch mr.Type() {
		case mp4.TypeVmhd:
			track.raw.hasVmhd = true
		case mp4.TypeSmhd:
			track.raw.hasVmhd = false
		case mp4.TypeDinf:
			track.raw.hasDinf = true
			track.raw.dinf = mr.RawBox()
		case mp4.TypeStbl:
			parseStbl(mr, track, handlerType)
		}
	}
}

func parseStbl(mr *mp4.Reader, track *Track, handlerType [4]byte) {
	mr.Enter()
	defer mr.Exit()

	for mr.Next() {
		switch mr.Type() {
		case mp4.TypeStsd:
			track.raw.stsd = mr.RawBox()
			parseStsd(mr, track, handlerType)
		case mp4.TypeStsz:
			track.raw.stszData = mr.Data()
		case mp4.TypeStts:
			track.raw.sttsData = mr.Data()
		case mp4.TypeStsc:
			track.raw.stscData = mr.Data()
		case mp4.TypeCtts:
			track.raw.cttsData = mr.Data()
			track.raw.cttsVersion = mr.Version()
		case mp4.TypeStss:
			track.raw.stssData = mr.Data()
		case mp4.TypeStco:
			track.raw.stcoData = mr.Data()
		case mp4.TypeCo64:
			track.raw.co64Data = mr.Data()
			track.raw.hasCo64 = true
		}
	}

	if track.raw.stszData != nil {
		stszIt := mp4.NewStszIter(track.raw.stszData)
		track.raw.sampleCount = stszIt.Count()
	}

	// The sample description index is 1-based; zero is invalid. A fragmented
	// input has an empty stsc, so default to the first description rather
	// than letting the index stay zero, which would poison a rebuilt trex.
	track.SampleDescIdx = 1
	if track.raw.stscData != nil {
		stscIt := mp4.NewStscIter(track.raw.stscData)
		if entry, ok := stscIt.Next(); ok {
			track.SampleDescIdx = entry.SampleDescriptionId
		}
	}
}

func parseStsd(mr *mp4.Reader, track *Track, handlerType [4]byte) {
	data := mr.Data()
	if len(data) < 4 {
		return
	}

	mr.Enter()
	defer mr.Exit()
	mr.Skip(4)

	if !mr.Next() {
		return
	}

	entryType := mr.Type()
	entryData := mr.Data()

	switch handlerType {
	case htVide:
		track.Kind = TrackVideo
		if len(entryData) < 78 {
			track.setCodec(entryType.String())
			return
		}
		v := mp4.ReadVisualSampleEntry(entryData)
		children := visualChildren(mr, v.ChildOffset)
		track.Width = v.Width
		track.Height = v.Height
		if d := children.pasp; len(d) >= 8 {
			track.PixelAspectHorizontal = binary.BigEndian.Uint32(d[0:4])
			track.PixelAspectVertical = binary.BigEndian.Uint32(d[4:8])
		}
		if d := children.colr; len(d) >= 10 && (string(d[:4]) == "nclx" || string(d[:4]) == "nclc") {
			track.ColorPrimaries = binary.BigEndian.Uint16(d[4:6])
			track.ColorTransfer = binary.BigEndian.Uint16(d[6:8])
			track.ColorMatrix = binary.BigEndian.Uint16(d[8:10])
			track.HasColor = true
			if len(d) >= 11 && string(d[:4]) == "nclx" {
				track.FullColorRange = d[10]&0x80 != 0
			}
		}
		switch entryType {
		case mp4.TypeAvc1:
			track.setCodec("avc1")
			if d := children.avcC; len(d) >= 4 {
				track.appendCodec(".")
				track.appendAvcCProfile(d[1], d[2], d[3])
			}
		case mp4.TypeAv01:
			track.setCodec("av01")
			if d := children.av1C; len(d) >= 3 {
				track.appendAv1CProfile(d)
			}
		default:
			track.setCodec(entryType.String())
		}
	case htSoun:
		track.Kind = TrackAudio
		switch entryType {
		case mp4.TypeMp4a:
			track.setCodec("mp4a")
			if len(entryData) >= 28 {
				a := mp4.ReadAudioSampleEntry(entryData)
				track.ChannelCount = a.ChannelCount
				track.SampleRate = a.SampleRate >> 16
				track.SampleSize = a.SampleSize
				if d := childBox(mr, a.ChildOffset, mp4.TypeEsds); d != nil {
					track.appendEsdsCodec(d)
				}
			}
		case mp4.TypeAlac:
			track.setCodec("alac")
			if len(entryData) >= 28 {
				a := mp4.ReadAudioSampleEntry(entryData)
				track.ChannelCount = a.ChannelCount
				track.SampleRate = a.SampleRate >> 16
				track.SampleSize = a.SampleSize
			}
		default:
			track.setCodec(entryType.String())
		}
	default:
		track.Kind = TrackUnknown
		track.setCodec(entryType.String())
	}
}

type visualSampleChildren struct {
	avcC []byte
	av1C []byte
	pasp []byte
	colr []byte
}

func visualChildren(mr *mp4.Reader, childOffset int) visualSampleChildren {
	var children visualSampleChildren
	mr.Enter()
	defer mr.Exit()
	mr.Skip(childOffset)
	for mr.Next() {
		switch mr.Type() {
		case mp4.TypeAvcC:
			children.avcC = mr.Data()
		case mp4.TypeAv1C:
			children.av1C = mr.Data()
		case mp4.TypePasp:
			children.pasp = mr.Data()
		case mp4.TypeColr:
			children.colr = mr.Data()
		}
	}
	return children
}

func tkhdRotation(data []byte, version uint8) uint16 {
	offset := 36
	if version == 1 {
		offset = 48
	}
	if offset+20 > len(data) {
		return 0
	}
	a := int32(binary.BigEndian.Uint32(data[offset:]))
	b := int32(binary.BigEndian.Uint32(data[offset+4:]))
	c := int32(binary.BigEndian.Uint32(data[offset+12:]))
	d := int32(binary.BigEndian.Uint32(data[offset+16:]))
	const one = int32(1 << 16)
	switch {
	case a == 0 && b == one && c == -one && d == 0:
		return 90
	case a == -one && b == 0 && c == 0 && d == -one:
		return 180
	case a == 0 && b == -one && c == one && d == 0:
		return 270
	default:
		return 0
	}
}

// childBox enters the current sample entry, skips its fixed header of
// childOffset bytes, and returns the data of the first child box of boxType, or
// nil if none is found.
func childBox(mr *mp4.Reader, childOffset int, boxType mp4.BoxType) []byte {
	mr.Enter()
	defer mr.Exit()
	mr.Skip(childOffset)
	for mr.Next() {
		if mr.Type() == boxType {
			return mr.Data()
		}
	}
	return nil
}

// parseSamples parses sample table data and populates track.Samples.
// Returns an error if required sample table data is missing or corrupt.
// maxSamples caps the sample count of a constant-size stsz, which carries no
// per-sample data to bound it; a per-sample table is bounded by its own entries
// instead. The cap keeps a malformed constant-size box from forcing a large
// allocation while staying well above any real constant-size track.
const maxSamples = 1 << 20

func (t *Track) parseSamples() error {
	if t.raw.stszData == nil || t.raw.sttsData == nil || t.raw.stscData == nil {
		return fmt.Errorf("track %d: %w: missing required sample table data (stsz/stts/stsc)", t.ID, ErrInvalidTrack)
	}
	if t.raw.stcoData == nil && t.raw.co64Data == nil {
		return fmt.Errorf("track %d: %w: missing chunk offset data (stco/co64)", t.ID, ErrInvalidTrack)
	}

	stszIt := mp4.NewStszIter(t.raw.stszData)
	numSamples := int(stszIt.Count())
	if numSamples == 0 {
		t.Samples = t.Samples[:0]
		return nil
	}

	// A malformed stsz can declare far more samples than the file describes,
	// which would otherwise size the allocation below from an untrusted count. A
	// per-sample size table cannot describe more samples than it stores; the
	// constant-size form carries no per-sample data, so bound it at maxSamples.
	if stszIt.ConstantSize() {
		if numSamples > maxSamples {
			return fmt.Errorf("track %d: %w: constant-size stsz declares %d samples", t.ID, ErrCorruptData, numSamples)
		}
	} else if numSamples > stszIt.SizeTableLen() {
		return fmt.Errorf("track %d: %w: stsz declares %d samples but stores %d", t.ID, ErrCorruptData, numSamples, stszIt.SizeTableLen())
	}

	var samples []Sample
	if cap(t.Samples) >= numSamples {
		samples = t.Samples[:numSamples]
	} else {
		samples = make([]Sample, numSamples)
	}

	stscIt := mp4.NewStscIter(t.raw.stscData)
	sttsIt := mp4.NewSttsIter(t.raw.sttsData)

	var cttsIt mp4.CttsIter
	hasCtts := t.raw.cttsData != nil
	if hasCtts {
		cttsIt = mp4.NewCttsIter(t.raw.cttsData, t.raw.cttsVersion)
	}

	hasSync := t.raw.stssData != nil
	var syncIt mp4.Uint32Iter
	if hasSync {
		syncIt = mp4.NewUint32Iter(t.raw.stssData)
	}

	curStsc, ok := stscIt.Next()
	if !ok {
		return fmt.Errorf("track %d: %w: empty stsc table", t.ID, ErrInvalidTrack)
	}
	var nextStsc mp4.StscEntry
	haveNextStsc := false
	if e, ok := stscIt.Next(); ok {
		nextStsc = e
		haveNextStsc = true
	}

	curStts, ok := sttsIt.Next()
	if !ok {
		return fmt.Errorf("track %d: %w: empty stts table", t.ID, ErrInvalidTrack)
	}
	sttsRemaining := int(curStts.Count)

	var curCtts mp4.CttsEntry
	cttsRemaining := 0
	if hasCtts {
		if e, ok := cttsIt.Next(); ok {
			curCtts = e
			cttsRemaining = int(e.Count)
		}
	}

	var nextSync uint32
	haveSync := false
	if hasSync {
		if v, ok := syncIt.Next(); ok {
			nextSync = v
			haveSync = true
		}
	}

	var chunkOffset int64
	var chunkIdx uint32

	var stcoIt mp4.Uint32Iter
	var co64It mp4.Co64Iter
	if t.raw.hasCo64 {
		co64It = mp4.NewCo64Iter(t.raw.co64Data)
		if v, ok := co64It.Next(); ok {
			chunkOffset = int64(v)
		}
	} else {
		stcoIt = mp4.NewUint32Iter(t.raw.stcoData)
		if v, ok := stcoIt.Next(); ok {
			chunkOffset = int64(v)
		}
	}
	chunkIdx = 1

	sampleInChunk := uint32(0)
	var offsetInChunk int64
	var dts int64

	for i := range numSamples {
		size, ok := stszIt.Next()
		if !ok {
			return fmt.Errorf("track %d: %w: stsz iterator exhausted at sample %d/%d", t.ID, ErrCorruptData, i, numSamples)
		}

		var presOff int32
		if hasCtts && cttsRemaining > 0 {
			presOff = curCtts.Offset
		}

		isSync := true
		if hasSync {
			isSync = haveSync && nextSync == uint32(i+1)
		}

		packedSize := size
		if isSync {
			packedSize |= syncBit
		}
		samples[i] = Sample{
			Offset:             offsetInChunk + chunkOffset,
			DTS:                dts,
			TrackID:            t.ID,
			size:               packedSize,
			Duration:           curStts.Duration,
			PresentationOffset: presOff,
		}

		if i+1 >= numSamples {
			break
		}

		sampleInChunk++
		offsetInChunk += int64(size)
		if sampleInChunk >= curStsc.SamplesPerChunk {
			sampleInChunk = 0
			offsetInChunk = 0
			chunkIdx++
			if t.raw.hasCo64 {
				if v, ok := co64It.Next(); ok {
					chunkOffset = int64(v)
				}
			} else {
				if v, ok := stcoIt.Next(); ok {
					chunkOffset = int64(v)
				}
			}
			if haveNextStsc && chunkIdx >= nextStsc.FirstChunk {
				curStsc = nextStsc
				if e, ok := stscIt.Next(); ok {
					nextStsc = e
				} else {
					haveNextStsc = false
				}
			}
		}

		dts += int64(curStts.Duration)
		sttsRemaining--
		if sttsRemaining <= 0 {
			if e, ok := sttsIt.Next(); ok {
				curStts = e
				sttsRemaining = int(e.Count)
			}
		}

		if hasCtts {
			cttsRemaining--
			if cttsRemaining <= 0 {
				if e, ok := cttsIt.Next(); ok {
					curCtts = e
					cttsRemaining = int(e.Count)
				}
			}
		}

		if isSync && hasSync {
			if v, ok := syncIt.Next(); ok {
				nextSync = v
			} else {
				haveSync = false
			}
		}
	}

	t.Samples = samples
	t.SampleDescIdx = curStsc.SampleDescriptionId
	return nil
}

const hexChars = "0123456789abcdef"