-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathmp4track.cpp
1930 lines (1561 loc) · 60.4 KB
/
mp4track.cpp
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
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is MPEG4IP.
*
* The Initial Developer of the Original Code is Cisco Systems Inc.
* Portions created by Cisco Systems Inc. are
* Copyright (C) Cisco Systems Inc. 2001 - 2004. All Rights Reserved.
*
* 3GPP features implementation is based on 3GPP's TS26.234-v5.60,
* and was contributed by Ximpo Group Ltd.
*
* Portions created by Ximpo Group Ltd. are
* Copyright (C) Ximpo Group Ltd. 2003, 2004. All Rights Reserved.
*
* Contributor(s):
* Dave Mackie [email protected]
* Alix Marchandise-Franquet [email protected]
* Ximpo Group Ltd. [email protected]
*/
#include "src/impl.h"
namespace mp4v2 { namespace impl {
///////////////////////////////////////////////////////////////////////////////
#define AMR_UNINITIALIZED -1
#define AMR_TRUE 0
#define AMR_FALSE 1
MP4Track::MP4Track(MP4File& file, MP4Atom& trakAtom)
: m_File(file)
, m_trakAtom(trakAtom)
{
m_lastStsdIndex = 0;
m_lastSampleFile = NULL;
m_cachedReadSampleId = MP4_INVALID_SAMPLE_ID;
m_pCachedReadSample = NULL;
m_cachedReadSampleSize = 0;
m_writeSampleId = 1;
m_fixedSampleDuration = 0;
m_pChunkBuffer = NULL;
m_chunkBufferSize = 0;
m_sizeOfDataInChunkBuffer = 0;
m_chunkSamples = 0;
m_chunkDuration = 0;
// m_bytesPerSample should be set to 1, except for the
// quicktime audio constant bit rate samples, which have non-1 values
m_bytesPerSample = 1;
m_samplesPerChunk = 0;
m_durationPerChunk = 0;
m_isAmr = AMR_UNINITIALIZED;
m_curMode = 0;
m_cachedSttsSid = MP4_INVALID_SAMPLE_ID;
m_cachedCttsSid = MP4_INVALID_SAMPLE_ID;
bool success = true;
MP4Integer32Property* pTrackIdProperty;
success &= m_trakAtom.FindProperty(
"trak.tkhd.trackId",
(MP4Property**)&pTrackIdProperty);
if (success) {
m_trackId = pTrackIdProperty->GetValue();
}
success &= m_trakAtom.FindProperty(
"trak.mdia.mdhd.timeScale",
(MP4Property**)&m_pTimeScaleProperty);
if (success) {
// default chunking is 1 second of samples
m_durationPerChunk = m_pTimeScaleProperty->GetValue();
}
success &= m_trakAtom.FindProperty(
"trak.tkhd.duration",
(MP4Property**)&m_pTrackDurationProperty);
success &= m_trakAtom.FindProperty(
"trak.mdia.mdhd.duration",
(MP4Property**)&m_pMediaDurationProperty);
success &= m_trakAtom.FindProperty(
"trak.tkhd.modificationTime",
(MP4Property**)&m_pTrackModificationProperty);
success &= m_trakAtom.FindProperty(
"trak.mdia.mdhd.modificationTime",
(MP4Property**)&m_pMediaModificationProperty);
success &= m_trakAtom.FindProperty(
"trak.mdia.hdlr.handlerType",
(MP4Property**)&m_pTypeProperty);
// get handles on sample size information
m_pStszFixedSampleSizeProperty = NULL;
bool have_stsz =
m_trakAtom.FindProperty("trak.mdia.minf.stbl.stsz.sampleSize",
(MP4Property**)&m_pStszFixedSampleSizeProperty);
if (have_stsz) {
success &= m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.stsz.sampleCount",
(MP4Property**)&m_pStszSampleCountProperty);
success &= m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.stsz.entries.entrySize",
(MP4Property**)&m_pStszSampleSizeProperty);
m_stsz_sample_bits = 32;
} else {
success &= m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.stz2.sampleCount",
(MP4Property**)&m_pStszSampleCountProperty);
success &= m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.stz2.entries.entrySize",
(MP4Property**)&m_pStszSampleSizeProperty);
MP4Integer8Property *stz2_field_size;
if (m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.stz2.fieldSize",
(MP4Property **)&stz2_field_size)) {
m_stsz_sample_bits = stz2_field_size->GetValue();
m_have_stz2_4bit_sample = false;
} else success = false;
}
// get handles on information needed to map sample id's to file offsets
success &= m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.stsc.entryCount",
(MP4Property**)&m_pStscCountProperty);
success &= m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.stsc.entries.firstChunk",
(MP4Property**)&m_pStscFirstChunkProperty);
success &= m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.stsc.entries.samplesPerChunk",
(MP4Property**)&m_pStscSamplesPerChunkProperty);
success &= m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.stsc.entries.sampleDescriptionIndex",
(MP4Property**)&m_pStscSampleDescrIndexProperty);
success &= m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.stsc.entries.firstSample",
(MP4Property**)&m_pStscFirstSampleProperty);
bool haveStco = m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.stco.entryCount",
(MP4Property**)&m_pChunkCountProperty);
if (haveStco) {
success &= m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.stco.entries.chunkOffset",
(MP4Property**)&m_pChunkOffsetProperty);
} else {
success &= m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.co64.entryCount",
(MP4Property**)&m_pChunkCountProperty);
success &= m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.co64.entries.chunkOffset",
(MP4Property**)&m_pChunkOffsetProperty);
}
// get handles on sample timing info
success &= m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.stts.entryCount",
(MP4Property**)&m_pSttsCountProperty);
success &= m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.stts.entries.sampleCount",
(MP4Property**)&m_pSttsSampleCountProperty);
success &= m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.stts.entries.sampleDelta",
(MP4Property**)&m_pSttsSampleDeltaProperty);
// get handles on rendering offset info if it exists
m_pCttsCountProperty = NULL;
m_pCttsSampleCountProperty = NULL;
m_pCttsSampleOffsetProperty = NULL;
bool haveCtts = m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.ctts.entryCount",
(MP4Property**)&m_pCttsCountProperty);
if (haveCtts) {
success &= m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.ctts.entries.sampleCount",
(MP4Property**)&m_pCttsSampleCountProperty);
success &= m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.ctts.entries.sampleOffset",
(MP4Property**)&m_pCttsSampleOffsetProperty);
}
// get handles on sync sample info if it exists
m_pStssCountProperty = NULL;
m_pStssSampleProperty = NULL;
bool haveStss = m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.stss.entryCount",
(MP4Property**)&m_pStssCountProperty);
if (haveStss) {
success &= m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.stss.entries.sampleNumber",
(MP4Property**)&m_pStssSampleProperty);
}
// edit list
(void)InitEditListProperties();
// was everything found?
if (!success) {
throw new Exception("invalid track", __FILE__, __LINE__, __FUNCTION__ );
}
CalculateBytesPerSample();
// update sdtp log from sdtp atom
MP4Atom* atom = m_trakAtom.FindAtom( "trak.mdia.minf.stbl.sdtp" );
MP4SdtpAtom* sdtp = dynamic_cast<MP4SdtpAtom *>( atom );
if ( sdtp != nullptr )
{
uint8_t* buffer;
uint32_t bufsize;
sdtp->data.GetValue( &buffer, &bufsize );
m_sdtpLog.assign( (char*)buffer, bufsize );
free( buffer );
}
}
MP4Track::~MP4Track()
{
MP4Free(m_pCachedReadSample);
m_pCachedReadSample = NULL;
MP4Free(m_pChunkBuffer);
m_pChunkBuffer = NULL;
}
const char* MP4Track::GetType()
{
return m_pTypeProperty->GetValue();
}
void MP4Track::SetType(const char* type)
{
m_pTypeProperty->SetValue(MP4NormalizeTrackType(type));
}
void MP4Track::ReadSample(
MP4SampleId sampleId,
uint8_t** ppBytes,
uint32_t* pNumBytes,
MP4Timestamp* pStartTime,
MP4Duration* pDuration,
MP4Duration* pRenderingOffset,
bool* pIsSyncSample,
bool* hasDependencyFlags,
uint32_t* dependencyFlags )
{
if( sampleId == MP4_INVALID_SAMPLE_ID )
throw new Exception( "sample id can't be zero", __FILE__, __LINE__, __FUNCTION__ );
if( hasDependencyFlags )
*hasDependencyFlags = !m_sdtpLog.empty();
if( dependencyFlags ) {
if( m_sdtpLog.empty() ) {
*dependencyFlags = 0;
}
else {
if( sampleId > m_sdtpLog.size() )
throw new Exception( "sample id > sdtp logsize", __FILE__, __LINE__, __FUNCTION__ );
*dependencyFlags = m_sdtpLog[sampleId-1]; // sampleId is 1-based
}
}
// handle unusual case of wanting to read a sample
// that is still sitting in the write chunk buffer
if (m_pChunkBuffer && sampleId >= m_writeSampleId - m_chunkSamples) {
WriteChunkBuffer();
}
File* fin = GetSampleFile( sampleId );
if( fin == (File*)-1 )
throw new Exception( "sample is located in an inaccessible file", __FILE__, __LINE__, __FUNCTION__ );
uint64_t fileOffset = GetSampleFileOffset(sampleId);
uint32_t sampleSize = GetSampleSize(sampleId);
if (*ppBytes != NULL && *pNumBytes < sampleSize) {
throw new Exception("sample buffer is too small",
__FILE__, __LINE__, __FUNCTION__ );
}
*pNumBytes = sampleSize;
log.verbose3f("\"%s\": ReadSample: track %u id %u offset 0x%" PRIx64 " size %u (0x%x)",
GetFile().GetFilename().c_str(), m_trackId, sampleId, fileOffset, *pNumBytes, *pNumBytes);
bool bufferMalloc = false;
if (*ppBytes == NULL) {
*ppBytes = (uint8_t*)MP4Malloc(*pNumBytes);
bufferMalloc = true;
}
uint64_t oldPos = m_File.GetPosition( fin ); // only used in mode == 'w'
try {
m_File.SetPosition( fileOffset, fin );
m_File.ReadBytes( *ppBytes, *pNumBytes, fin );
if (pStartTime || pDuration) {
GetSampleTimes(sampleId, pStartTime, pDuration);
log.verbose3f("\"%s\": ReadSample: start %" PRIu64 " duration %" PRId64,
GetFile().GetFilename().c_str(), (pStartTime ? *pStartTime : 0),
(pDuration ? *pDuration : 0));
}
if (pRenderingOffset) {
*pRenderingOffset = GetSampleRenderingOffset(sampleId);
log.verbose3f("\"%s\": ReadSample: renderingOffset %" PRId64,
GetFile().GetFilename().c_str(), *pRenderingOffset);
}
if (pIsSyncSample) {
*pIsSyncSample = IsSyncSample(sampleId);
log.verbose3f("\"%s\": ReadSample: isSyncSample %u",
GetFile().GetFilename().c_str(), *pIsSyncSample);
}
}
catch (Exception* x) {
if( bufferMalloc ) {
MP4Free( *ppBytes );
*ppBytes = NULL;
}
if( m_File.IsWriteMode() )
m_File.SetPosition( oldPos, fin );
throw x;
}
if( m_File.IsWriteMode() )
m_File.SetPosition( oldPos, fin );
}
void MP4Track::ReadSampleFragment(
MP4SampleId sampleId,
uint32_t sampleOffset,
uint16_t sampleLength,
uint8_t* pDest)
{
if (sampleId == MP4_INVALID_SAMPLE_ID) {
throw new Exception("invalid sample id",
__FILE__, __LINE__, __FUNCTION__ );
}
if (sampleId != m_cachedReadSampleId) {
MP4Free(m_pCachedReadSample);
m_pCachedReadSample = NULL;
m_cachedReadSampleSize = 0;
m_cachedReadSampleId = MP4_INVALID_SAMPLE_ID;
ReadSample(
sampleId,
&m_pCachedReadSample,
&m_cachedReadSampleSize);
m_cachedReadSampleId = sampleId;
}
if (sampleOffset + sampleLength > m_cachedReadSampleSize) {
throw new Exception("offset and/or length are too large",
__FILE__, __LINE__, __FUNCTION__ );
}
memcpy(pDest, &m_pCachedReadSample[sampleOffset], sampleLength);
}
void MP4Track::WriteSample(
const uint8_t* pBytes,
uint32_t numBytes,
MP4Duration duration,
MP4Duration renderingOffset,
bool isSyncSample )
{
uint8_t curMode = 0;
log.verbose3f("\"%s\": WriteSample: track %u id %u size %u (0x%x) ",
GetFile().GetFilename().c_str(),
m_trackId, m_writeSampleId, numBytes, numBytes);
if (pBytes == NULL && numBytes > 0) {
throw new Exception("no sample data", __FILE__, __LINE__, __FUNCTION__ );
}
if (m_isAmr == AMR_UNINITIALIZED ) {
// figure out if this is an AMR audio track
if (m_trakAtom.FindAtom("trak.mdia.minf.stbl.stsd.samr") ||
m_trakAtom.FindAtom("trak.mdia.minf.stbl.stsd.sawb")) {
m_isAmr = AMR_TRUE;
m_curMode = (pBytes[0] >> 3) & 0x000F;
} else {
m_isAmr = AMR_FALSE;
}
}
if (m_isAmr == AMR_TRUE) {
curMode = (pBytes[0] >> 3) &0x000F; // The mode is in the first byte
}
if (duration == MP4_INVALID_DURATION) {
duration = GetFixedSampleDuration();
}
log.verbose3f("\"%s\": duration %" PRIu64, GetFile().GetFilename().c_str(),
duration);
if ((m_isAmr == AMR_TRUE) &&
(m_curMode != curMode)) {
WriteChunkBuffer();
m_curMode = curMode;
}
// append sample bytes to chunk buffer
if( m_sizeOfDataInChunkBuffer + numBytes > m_chunkBufferSize ) {
m_pChunkBuffer = (uint8_t*)MP4Realloc(m_pChunkBuffer, m_chunkBufferSize + numBytes);
if (m_pChunkBuffer == NULL)
return;
m_chunkBufferSize += numBytes;
}
memcpy(&m_pChunkBuffer[m_sizeOfDataInChunkBuffer], pBytes, numBytes);
m_sizeOfDataInChunkBuffer += numBytes;
m_chunkSamples++;
m_chunkDuration += duration;
UpdateSampleSizes(m_writeSampleId, numBytes);
UpdateSampleTimes(duration);
UpdateRenderingOffsets(m_writeSampleId, renderingOffset);
UpdateSyncSamples(m_writeSampleId, isSyncSample);
if (IsChunkFull(m_writeSampleId)) {
WriteChunkBuffer();
m_curMode = curMode;
}
UpdateDurations(duration);
UpdateModificationTimes();
m_writeSampleId++;
}
void MP4Track::WriteSampleDependency(
const uint8_t* pBytes,
uint32_t numBytes,
MP4Duration duration,
MP4Duration renderingOffset,
bool isSyncSample,
uint32_t dependencyFlags )
{
m_sdtpLog.push_back( dependencyFlags ); // record dependency flags for processing at finish
WriteSample( pBytes, numBytes, duration, renderingOffset, isSyncSample );
}
void MP4Track::WriteChunkBuffer()
{
if (m_sizeOfDataInChunkBuffer == 0) {
return;
}
uint64_t chunkOffset = m_File.GetPosition();
// write chunk buffer
m_File.WriteBytes(m_pChunkBuffer, m_sizeOfDataInChunkBuffer);
log.verbose3f("\"%s\": WriteChunk: track %u offset 0x%" PRIx64 " size %u (0x%x) numSamples %u",
GetFile().GetFilename().c_str(),
m_trackId, chunkOffset, m_sizeOfDataInChunkBuffer,
m_sizeOfDataInChunkBuffer, m_chunkSamples);
UpdateSampleToChunk(m_writeSampleId,
m_pChunkCountProperty->GetValue() + 1,
m_chunkSamples);
UpdateChunkOffsets(chunkOffset);
// note: we do not free our chunk buffer; we reuse it, expanding as needed.
// It gets zapped when this class goes out of scope
m_sizeOfDataInChunkBuffer = 0;
m_chunkSamples = 0;
m_chunkDuration = 0;
}
void MP4Track::FinishWrite(uint32_t options)
{
FinishSdtp();
// write out any remaining samples in chunk buffer
WriteChunkBuffer();
if (m_pStszFixedSampleSizeProperty == NULL &&
m_stsz_sample_bits == 4) {
if (m_have_stz2_4bit_sample) {
((MP4Integer8Property *)m_pStszSampleSizeProperty)->AddValue(m_stz2_4bit_sample_value);
m_pStszSampleSizeProperty->IncrementValue();
}
}
// record buffer size and bitrates
MP4BitfieldProperty* pBufferSizeProperty;
if (m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.stsd.*.esds.decConfigDescr.bufferSizeDB",
(MP4Property**)&pBufferSizeProperty)) {
pBufferSizeProperty->SetValue(GetMaxSampleSize());
}
// don't overwrite bitrate if it was requested in the Close call
if( !(options & MP4_CLOSE_DO_NOT_COMPUTE_BITRATE)) {
MP4Integer32Property* pBitrateProperty;
if (m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.stsd.*.esds.decConfigDescr.maxBitrate",
(MP4Property**)&pBitrateProperty)) {
pBitrateProperty->SetValue(GetMaxBitrate());
}
if (m_trakAtom.FindProperty(
"trak.mdia.minf.stbl.stsd.*.esds.decConfigDescr.avgBitrate",
(MP4Property**)&pBitrateProperty)) {
pBitrateProperty->SetValue(GetAvgBitrate());
}
}
// cleaup trak.udta
MP4BytesProperty* nameProperty = NULL;
m_trakAtom.FindProperty("trak.udta.name.value", (MP4Property**) &nameProperty);
if( nameProperty != NULL && nameProperty->GetValueSize() == 0 ){
// Zero length name value--delete name, and then udta if no child atoms
MP4Atom* name = m_trakAtom.FindChildAtom("udta.name");
if( name ) {
MP4Atom* udta = name->GetParentAtom();
udta->DeleteChildAtom( name );
delete name;
if( udta->GetNumberOfChildAtoms() == 0 ) {
udta->GetParentAtom()->DeleteChildAtom( udta );
delete udta;
}
}
}
}
// Process sdtp log and add sdtp atom.
//
// Testing (subjective) showed a marked improvement with QuickTime
// player on Mac OS X when scrubbing. Best results were obtained
// from encodings using low number of bframes. It's expected sdtp may help
// other QT-based players.
//
void MP4Track::FinishSdtp()
{
// bail if log is empty -- indicates dependency information was not written
if( m_sdtpLog.empty() )
return;
MP4SdtpAtom* sdtp = (MP4SdtpAtom*)m_trakAtom.FindAtom( "trak.mdia.minf.stbl.sdtp" );
if( !sdtp )
sdtp = (MP4SdtpAtom*)AddAtom( "trak.mdia.minf.stbl", "sdtp" );
sdtp->data.SetValue( (const uint8_t*)m_sdtpLog.data(), (uint32_t)m_sdtpLog.size() );
// add avc1 compatibility indicator if not present
MP4FtypAtom* ftyp = (MP4FtypAtom*)m_File.FindAtom( "ftyp" );
if( ftyp ) {
bool found = false;
const uint32_t max = ftyp->compatibleBrands.GetCount();
for( uint32_t i = 0; i < max; i++ ) {
if( !strcmp( ftyp->compatibleBrands.GetValue( i ), "avc1" )) {
found = true;
break;
}
}
if( !found )
ftyp->compatibleBrands.AddValue( "avc1" );
}
}
bool MP4Track::IsChunkFull(MP4SampleId sampleId)
{
if (m_samplesPerChunk) {
return m_chunkSamples >= m_samplesPerChunk;
}
ASSERT(m_durationPerChunk);
return m_chunkDuration >= m_durationPerChunk;
}
uint32_t MP4Track::GetNumberOfSamples()
{
return m_pStszSampleCountProperty->GetValue();
}
uint32_t MP4Track::GetSampleSize(MP4SampleId sampleId)
{
if (m_pStszFixedSampleSizeProperty != NULL) {
uint32_t fixedSampleSize =
m_pStszFixedSampleSizeProperty->GetValue();
if (fixedSampleSize != 0) {
return fixedSampleSize * m_bytesPerSample;
}
}
// will have to check for 4 bit sample size here
if (m_stsz_sample_bits == 4) {
uint8_t value = m_pStszSampleSizeProperty->GetValue((sampleId - 1) / 2);
if ((sampleId - 1) / 2 == 0) {
value >>= 4;
} else value &= 0xf;
return m_bytesPerSample * value;
}
return m_bytesPerSample *
m_pStszSampleSizeProperty->GetValue(sampleId - 1);
}
uint32_t MP4Track::GetMaxSampleSize()
{
if (m_pStszFixedSampleSizeProperty != NULL) {
uint32_t fixedSampleSize =
m_pStszFixedSampleSizeProperty->GetValue();
if (fixedSampleSize != 0) {
return fixedSampleSize * m_bytesPerSample;
}
}
uint32_t maxSampleSize = 0;
uint32_t numSamples = m_pStszSampleSizeProperty->GetCount();
for (MP4SampleId sid = 1; sid <= numSamples; sid++) {
uint32_t sampleSize =
m_pStszSampleSizeProperty->GetValue(sid - 1);
if (sampleSize > maxSampleSize) {
maxSampleSize = sampleSize;
}
}
return maxSampleSize * m_bytesPerSample;
}
uint64_t MP4Track::GetTotalOfSampleSizes()
{
uint64_t retval;
if (m_pStszFixedSampleSizeProperty != NULL) {
uint32_t fixedSampleSize =
m_pStszFixedSampleSizeProperty->GetValue();
// if fixed sample size, just need to multiply by number of samples
if (fixedSampleSize != 0) {
retval = m_bytesPerSample;
retval *= fixedSampleSize;
retval *= GetNumberOfSamples();
return retval;
}
}
// else non-fixed sample size, sum them
uint64_t totalSampleSizes = 0;
uint32_t numSamples = m_pStszSampleSizeProperty->GetCount();
for (MP4SampleId sid = 1; sid <= numSamples; sid++) {
uint32_t sampleSize =
m_pStszSampleSizeProperty->GetValue(sid - 1);
totalSampleSizes += sampleSize;
}
return totalSampleSizes * m_bytesPerSample;
}
void MP4Track::SampleSizePropertyAddValue (uint32_t size)
{
// this has to deal with different sample size values
switch (m_pStszSampleSizeProperty->GetType()) {
case Integer32Property:
((MP4Integer32Property *)m_pStszSampleSizeProperty)->AddValue(size);
break;
case Integer16Property:
((MP4Integer16Property *)m_pStszSampleSizeProperty)->AddValue(size);
break;
case Integer8Property:
if (m_stsz_sample_bits == 4) {
if (m_have_stz2_4bit_sample == false) {
m_have_stz2_4bit_sample = true;
m_stz2_4bit_sample_value = size << 4;
return;
} else {
m_have_stz2_4bit_sample = false;
size &= 0xf;
size |= m_stz2_4bit_sample_value;
}
}
((MP4Integer8Property *)m_pStszSampleSizeProperty)->AddValue(size);
break;
default:
break;
}
// m_pStszSampleSizeProperty->IncrementValue();
}
void MP4Track::UpdateSampleSizes(MP4SampleId sampleId, uint32_t numBytes)
{
if (m_bytesPerSample > 1) {
if ((numBytes % m_bytesPerSample) != 0) {
// error
log.errorf("%s: \"%s\": numBytes %u not divisible by bytesPerSample %u sampleId %u",
__FUNCTION__, GetFile().GetFilename().c_str(),
numBytes, m_bytesPerSample, sampleId);
}
numBytes /= m_bytesPerSample;
}
// for first sample
// wmay - if we are adding, we want to make sure that
// we don't inadvertently set up the fixed size again.
// so, we check the number of samples
if (sampleId == 1 && GetNumberOfSamples() == 0) {
if (m_pStszFixedSampleSizeProperty == NULL ||
numBytes == 0) {
// special case of first sample is zero bytes in length
// leave m_pStszFixedSampleSizeProperty at 0
// start recording variable sample sizes
if (m_pStszFixedSampleSizeProperty != NULL)
m_pStszFixedSampleSizeProperty->SetValue(0);
SampleSizePropertyAddValue(0);
} else {
// presume sample size is fixed
m_pStszFixedSampleSizeProperty->SetValue(numBytes);
}
} else { // sampleId > 1
uint32_t fixedSampleSize = 0;
if (m_pStszFixedSampleSizeProperty != NULL) {
fixedSampleSize = m_pStszFixedSampleSizeProperty->GetValue();
}
// if we don't have a fixed size, or the current sample size
// doesn't match our sample size, we need to write the current
// sample size into the table
if (fixedSampleSize == 0 || numBytes != fixedSampleSize) {
if (fixedSampleSize != 0) {
// fixed size was set; we need to clear fixed sample size
m_pStszFixedSampleSizeProperty->SetValue(0);
// and create sizes for all previous samples
// use GetNumberOfSamples due to needing the total number
// not just the appended part of the file
uint32_t samples = GetNumberOfSamples();
for (MP4SampleId sid = 1; sid <= samples; sid++) {
SampleSizePropertyAddValue(fixedSampleSize);
}
}
// add size value for this sample
SampleSizePropertyAddValue(numBytes);
}
}
// either way, we increment the number of samples.
m_pStszSampleCountProperty->IncrementValue();
}
uint32_t MP4Track::GetAvgBitrate()
{
if (GetDuration() == 0) {
return 0;
}
double calc = double(GetTotalOfSampleSizes());
// this is a bit better - we use the whole duration
calc *= 8.0;
calc *= GetTimeScale();
calc /= double(GetDuration());
// we might want to think about rounding to the next 100 or 1000
return (uint32_t) ceil(calc);
}
uint32_t MP4Track::GetMaxBitrate()
{
uint32_t timeScale = GetTimeScale();
MP4SampleId numSamples = GetNumberOfSamples();
uint32_t maxBytesPerSec = 0;
uint32_t bytesThisSec = 0;
MP4Timestamp thisSecStart = 0;
MP4Timestamp lastSampleTime = 0;
uint32_t lastSampleSize = 0;
MP4SampleId thisSecStartSid = 1;
for (MP4SampleId sid = 1; sid <= numSamples; sid++) {
uint32_t sampleSize;
MP4Timestamp sampleTime;
sampleSize = GetSampleSize(sid);
GetSampleTimes(sid, &sampleTime, NULL);
if (sampleTime < thisSecStart + timeScale) {
bytesThisSec += sampleSize;
lastSampleSize = sampleSize;
lastSampleTime = sampleTime;
} else {
// we've already written the last sample and sampleSize.
// this means that we've probably overflowed the last second
// calculate the time we've overflowed
MP4Duration overflow_dur =
(thisSecStart + timeScale) - lastSampleTime;
// calculate the duration of the last sample
MP4Duration lastSampleDur = sampleTime - lastSampleTime;
// now, calculate the number of bytes we overflowed. Round up.
if( lastSampleDur > 0 ) {
uint32_t overflow_bytes = 0;
overflow_bytes = ((lastSampleSize * overflow_dur) + (lastSampleDur - 1)) / lastSampleDur;
if (bytesThisSec - overflow_bytes > maxBytesPerSec) {
maxBytesPerSec = bytesThisSec - overflow_bytes;
}
}
// now adjust the values for this sample. Remove the bytes
// from the first sample in this time frame
lastSampleTime = sampleTime;
lastSampleSize = sampleSize;
bytesThisSec += sampleSize;
bytesThisSec -= GetSampleSize(thisSecStartSid);
thisSecStartSid++;
GetSampleTimes(thisSecStartSid, &thisSecStart, NULL);
}
}
return maxBytesPerSec * 8;
}
uint32_t MP4Track::GetSampleStscIndex(MP4SampleId sampleId)
{
uint32_t stscIndex;
uint32_t numStscs = m_pStscCountProperty->GetValue();
if (numStscs == 0) {
throw new Exception("No data chunks exist", __FILE__, __LINE__, __FUNCTION__ );
}
for (stscIndex = 0; stscIndex < numStscs; stscIndex++) {
if (sampleId < m_pStscFirstSampleProperty->GetValue(stscIndex)) {
ASSERT(stscIndex != 0);
stscIndex -= 1;
break;
}
}
if (stscIndex == numStscs) {
ASSERT(stscIndex != 0);
stscIndex -= 1;
}
return stscIndex;
}
File* MP4Track::GetSampleFile( MP4SampleId sampleId )
{
uint32_t stscIndex = GetSampleStscIndex( sampleId );
uint32_t stsdIndex = m_pStscSampleDescrIndexProperty->GetValue( stscIndex );
// check if the answer will be the same as last time
if( m_lastStsdIndex && stsdIndex == m_lastStsdIndex )
return m_lastSampleFile;
MP4Atom* pStsdAtom = m_trakAtom.FindAtom( "trak.mdia.minf.stbl.stsd" );
ASSERT( pStsdAtom );
MP4Atom* pStsdEntryAtom = pStsdAtom->GetChildAtom( stsdIndex - 1 );
ASSERT( pStsdEntryAtom );
MP4Integer16Property* pDrefIndexProperty = NULL;
if( !pStsdEntryAtom->FindProperty( "*.dataReferenceIndex", (MP4Property**)&pDrefIndexProperty ) ||
pDrefIndexProperty == NULL )
{
// mp4v2 does not know about Apple-specific atoms in MOV files so may fail to find
// the DataReferenceIndex. In that case, we'll handle it the same as the "media data
// in local file" case... for our purposes, we don't care about cases where the
// media data is outside of the local file.
MP4FtypAtom *pFtypAtom = reinterpret_cast<MP4FtypAtom *>( m_File.FindAtom( "ftyp" ) );
// MOV spec does not require "ftyp" atom...
if ( pFtypAtom == nullptr )
{
return nullptr;
}
else
{
// ... but most often it is present with a "qt " value
const char *majorBrand = pFtypAtom->majorBrand.GetValue();
if ( ::strcmp( pFtypAtom->majorBrand.GetValue(), "qt " ) == 0 )
return nullptr;
}
throw new Exception( "invalid stsd entry", __FILE__, __LINE__, __FUNCTION__ );
}
uint32_t drefIndex = pDrefIndexProperty->GetValue();
MP4Atom* pDrefAtom = m_trakAtom.FindAtom( "trak.mdia.minf.dinf.dref" );
ASSERT(pDrefAtom);
MP4Atom* pUrlAtom = pDrefAtom->GetChildAtom( drefIndex - 1 );
ASSERT( pUrlAtom );
File* file;
// make sure this is actually a url atom (somtimes it's "cios", like in iTunes videos)
if( strcmp(pUrlAtom->GetType(), "url ") ||
pUrlAtom->GetFlags() & 1 ) {
file = NULL; // self-contained
}
else {
MP4StringProperty* pLocationProperty = NULL;
ASSERT( pUrlAtom->FindProperty( "*.location", (MP4Property**)&pLocationProperty) );
ASSERT( pLocationProperty );
const char* url = pLocationProperty->GetValue();
log.verbose3f("\"%s\": dref url = %s", GetFile().GetFilename().c_str(),
url);
file = (File*)-1;
// attempt to open url if it's a file url
// currently this is the only thing we understand
if( !strncmp( url, "file:", 5 )) {
const char* fileName = url + 5;
if( !strncmp(fileName, "//", 2 ))
fileName = strchr( fileName + 2, '/' );
if( fileName ) {
file = new File( fileName, File::MODE_READ );
if( !file->open() ) {
delete file;
file = (File*)-1;
}
}
}
}
if( m_lastSampleFile )
m_lastSampleFile->close();
// cache the answer
m_lastStsdIndex = stsdIndex;
m_lastSampleFile = file;
return file;
}
uint64_t MP4Track::GetSampleFileOffset(MP4SampleId sampleId)
{
uint32_t stscIndex =
GetSampleStscIndex(sampleId);
// firstChunk is the chunk index of the first chunk with
// samplesPerChunk samples in the chunk. There may be multiples -
// ie: several chunks with the same number of samples per chunk.
uint32_t firstChunk =
m_pStscFirstChunkProperty->GetValue(stscIndex);
MP4SampleId firstSample =
m_pStscFirstSampleProperty->GetValue(stscIndex);
uint32_t samplesPerChunk =
m_pStscSamplesPerChunkProperty->GetValue(stscIndex);
// chunkId tells which is the absolute chunk number that this sample
// is stored in.