-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathmp4file.cpp
4413 lines (3608 loc) · 136 KB
/
mp4file.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 - 2005. 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]
* Bill May [email protected]
*/
#include "src/impl.h"
namespace mp4v2 { namespace impl {
///////////////////////////////////////////////////////////////////////////////
MP4File::MP4File( ) :
m_file ( NULL )
, m_fileOriginalSize ( 0 )
, m_createFlags ( 0 )
{
this->Init();
}
/**
* Initialize member variables (shared among constructors)
*/
void MP4File::Init()
{
m_pRootAtom = NULL;
m_odTrackId = MP4_INVALID_TRACK_ID;
m_useIsma = false;
m_pModificationProperty = NULL;
m_pTimeScaleProperty = NULL;
m_pDurationProperty = NULL;
m_memoryBuffer = NULL;
m_memoryBufferSize = 0;
m_memoryBufferPosition = 0;
m_numReadBits = 0;
m_bufReadBits = 0;
m_numWriteBits = 0;
m_bufWriteBits = 0;
m_editName = NULL;
m_trakName[0] = '\0';
m_shouldParseAtomCallback = nullptr;
}
MP4File::~MP4File()
{
delete m_pRootAtom;
for( uint32_t i = 0; i < m_pTracks.Size(); i++ )
delete m_pTracks[i];
MP4Free( m_memoryBuffer ); // just in case
CHECK_AND_FREE( m_editName );
delete m_file;
}
const std::string &
MP4File::GetFilename() const
{
// No one should call this unless Read, etc. has
// succeeded and m_file exists since this method really
// only exists for the public API. This helps us
// guarantee that MP4GetFilename always returns a valid
// string given a valid MP4FileHandle
ASSERT(m_file);
return m_file->name;
}
void MP4File::Read( const char* name, const MP4FileProvider* provider )
{
Open( name, File::MODE_READ, provider );
ReadFromFile();
CacheProperties();
}
void MP4File::Create( const char* fileName,
uint32_t flags,
int add_ftyp,
int add_iods,
char* majorBrand,
uint32_t minorVersion,
char** supportedBrands,
uint32_t supportedBrandsCount )
{
m_createFlags = flags;
Open( fileName, File::MODE_CREATE, NULL );
// generate a skeletal atom tree
m_pRootAtom = MP4Atom::CreateAtom(*this, NULL, NULL);
m_pRootAtom->Generate();
if (add_ftyp != 0) {
MakeFtypAtom(majorBrand, minorVersion,
supportedBrands, supportedBrandsCount);
}
CacheProperties();
// create mdat, and insert it after ftyp, and before moov
(void)InsertChildAtom(m_pRootAtom, "mdat",
add_ftyp != 0 ? 1 : 0);
// start writing
m_pRootAtom->BeginWrite();
if (add_iods != 0) {
(void)AddChildAtom("moov", "iods");
}
}
bool MP4File::Use64Bits (const char *atomName)
{
uint32_t atomid = ATOMID(atomName);
if (atomid == ATOMID("mdat") || atomid == ATOMID("stbl")) {
return (m_createFlags & MP4_CREATE_64BIT_DATA) == MP4_CREATE_64BIT_DATA;
}
if (atomid == ATOMID("mvhd") ||
atomid == ATOMID("tkhd") ||
atomid == ATOMID("mdhd")) {
return (m_createFlags & MP4_CREATE_64BIT_TIME) == MP4_CREATE_64BIT_TIME;
}
return false;
}
void MP4File::Check64BitStatus (const char *atomName)
{
uint32_t atomid = ATOMID(atomName);
if (atomid == ATOMID("mdat") || atomid == ATOMID("stbl")) {
m_createFlags |= MP4_CREATE_64BIT_DATA;
} else if (atomid == ATOMID("mvhd") ||
atomid == ATOMID("tkhd") ||
atomid == ATOMID("mdhd")) {
m_createFlags |= MP4_CREATE_64BIT_TIME;
}
}
bool MP4File::Modify( const char* fileName )
{
Open( fileName, File::MODE_MODIFY, NULL );
ReadFromFile();
// find the moov atom
MP4Atom* pMoovAtom = m_pRootAtom->FindAtom("moov");
uint32_t numAtoms;
if (pMoovAtom == NULL) {
// there isn't one, odd but we can still proceed
log.warningf("%s: \"%s\": no moov atom, can't modify",
__FUNCTION__, GetFilename().c_str());
return false;
//pMoovAtom = AddChildAtom(m_pRootAtom, "moov");
} else {
numAtoms = m_pRootAtom->GetNumberOfChildAtoms();
// work backwards thru the top level atoms
int32_t i;
bool lastAtomIsMoov = true;
MP4Atom* pLastAtom = NULL;
for (i = numAtoms - 1; i >= 0; i--) {
MP4Atom* pAtom = m_pRootAtom->GetChildAtom(i);
const char* type = pAtom->GetType();
// get rid of any trailing free or skips
if (!strcmp(type, "free") || !strcmp(type, "skip")) {
m_pRootAtom->DeleteChildAtom(pAtom);
continue;
}
if (strcmp(type, "moov")) {
if (pLastAtom == NULL) {
pLastAtom = pAtom;
lastAtomIsMoov = false;
}
continue;
}
// now at moov atom
// multiple moov atoms?!?
if (pAtom != pMoovAtom) {
throw new Exception(
"Badly formed mp4 file, multiple moov atoms",
__FILE__,__LINE__,__FUNCTION__);
}
if (lastAtomIsMoov) {
// position to start of moov atom,
// effectively truncating file
// prior to adding new mdat
SetPosition(pMoovAtom->GetStart());
} else { // last atom isn't moov
// need to place a free atom
MP4Atom* pFreeAtom = MP4Atom::CreateAtom(*this, NULL, "free");
// in existing position of the moov atom
m_pRootAtom->InsertChildAtom(pFreeAtom, i);
m_pRootAtom->DeleteChildAtom(pMoovAtom);
m_pRootAtom->AddChildAtom(pMoovAtom);
// write free atom to disk
SetPosition(pMoovAtom->GetStart());
pFreeAtom->SetSize(pMoovAtom->GetSize());
pFreeAtom->Write();
// finally set our file position to the end of the last atom
SetPosition(pLastAtom->GetEnd());
}
break;
}
ASSERT(i != -1);
}
CacheProperties(); // of moov atom
numAtoms = m_pRootAtom->GetNumberOfChildAtoms();
// insert another mdat prior to moov atom (the last atom)
MP4Atom* pMdatAtom = InsertChildAtom(m_pRootAtom, "mdat", numAtoms - 1);
// start writing new mdat
pMdatAtom->BeginWrite(Use64Bits("mdat"));
return true;
}
void MP4File::Optimize( const char* srcFileName, const char* dstFileName )
{
File* src = NULL;
File* dst = NULL;
// compute destination filename
string dname;
if( dstFileName ) {
dname = dstFileName;
} else {
// No destination given, so let's kludge together a temporary file.
// We'll try to create it in the same directory as the srcFileName, since
// it's more likely that directory is writable. In the absence of that,
// we'll create it in "./", which is the default pathnameTemp() provides.
string s(srcFileName);
size_t pos = s.find_last_of("\\/");
const char *d;
if (pos == string::npos) {
d = ".";
} else {
s = s.substr(0, pos);
d = s.c_str();
}
FileSystem::pathnameTemp( dname, d, "tmp", ".mp4" );
}
try {
// file source to optimize
Open( srcFileName, File::MODE_READ, NULL );
ReadFromFile();
CacheProperties(); // of moov atom
src = m_file;
m_file = NULL;
// optimized file destination
Open( dname.c_str(), File::MODE_CREATE, NULL );
dst = m_file;
SetIntegerProperty( "moov.mvhd.modificationTime", MP4GetAbsTimestamp() );
// writing meta info in the optimal order
((MP4RootAtom*)m_pRootAtom)->BeginOptimalWrite();
// write data in optimal order
RewriteMdat( *src, *dst );
// finish writing
((MP4RootAtom*)m_pRootAtom)->FinishOptimalWrite();
}
catch (...) {
// cleanup and rethrow. Without this, we'd leak memory and an open file handle(s).
if(src == NULL && dst == NULL)
delete m_file;// We didn't make it far enough to have m_file go to src or dst.
m_file = NULL;
delete dst;
delete src;
throw;
}
// cleanup
delete dst;
delete src;
m_file = NULL;
// move temporary file into place
if( !dstFileName )
Rename( dname.c_str(), srcFileName );
}
void MP4File::RewriteMdat( File& src, File& dst )
{
uint32_t numTracks = m_pTracks.Size();
MP4ChunkId* chunkIds = new MP4ChunkId[numTracks];
MP4ChunkId* maxChunkIds = new MP4ChunkId[numTracks];
MP4Timestamp* nextChunkTimes = new MP4Timestamp[numTracks];
for( uint32_t i = 0; i < numTracks; i++ ) {
chunkIds[i] = 1;
maxChunkIds[i] = m_pTracks[i]->GetNumberOfChunks();
nextChunkTimes[i] = MP4_INVALID_TIMESTAMP;
}
for( ;; ) {
uint32_t nextTrackIndex = (uint32_t)-1;
MP4Timestamp nextTime = MP4_INVALID_TIMESTAMP;
for( uint32_t i = 0; i < numTracks; i++ ) {
if( chunkIds[i] > maxChunkIds[i] )
continue;
if( nextChunkTimes[i] == MP4_INVALID_TIMESTAMP ) {
MP4Timestamp chunkTime = m_pTracks[i]->GetChunkTime( chunkIds[i] );
nextChunkTimes[i] = MP4ConvertTime( chunkTime, m_pTracks[i]->GetTimeScale(), GetTimeScale() );
}
// time is not earliest so far
if( nextChunkTimes[i] > nextTime )
continue;
// prefer hint tracks to media tracks if times are equal
if( nextChunkTimes[i] == nextTime && strcmp( m_pTracks[i]->GetType(), MP4_HINT_TRACK_TYPE ))
continue;
// this is our current choice of tracks
nextTime = nextChunkTimes[i];
nextTrackIndex = i;
}
if( nextTrackIndex == (uint32_t)-1 )
break;
uint8_t* pChunk;
uint32_t chunkSize;
// point into original mp4 file for read chunk call
m_file = &src;
m_pTracks[nextTrackIndex]->ReadChunk( chunkIds[nextTrackIndex], &pChunk, &chunkSize );
// point back at the new mp4 file for write chunk
m_file = &dst;
m_pTracks[nextTrackIndex]->RewriteChunk( chunkIds[nextTrackIndex], pChunk, chunkSize );
MP4Free( pChunk );
chunkIds[nextTrackIndex]++;
nextChunkTimes[nextTrackIndex] = MP4_INVALID_TIMESTAMP;
}
delete [] chunkIds;
delete [] maxChunkIds;
delete [] nextChunkTimes;
}
void MP4File::Open( const char* name, File::Mode mode, const MP4FileProvider* provider )
{
ASSERT( !m_file );
m_file = new File( name, mode, provider ? new io::CustomFileProvider( *provider ) : NULL );
if( m_file->open() ) {
ostringstream msg;
msg << "open(" << name << ") failed";
throw new Exception( msg.str(), __FILE__, __LINE__, __FUNCTION__);
}
switch( mode ) {
case File::MODE_READ:
case File::MODE_MODIFY:
m_fileOriginalSize = m_file->size;
break;
case File::MODE_CREATE:
default:
m_fileOriginalSize = 0;
break;
}
}
void MP4File::ReadFromFile()
{
// ensure we start at beginning of file
SetPosition(0);
// create a new root atom
ASSERT(m_pRootAtom == NULL);
m_pRootAtom = MP4Atom::CreateAtom(*this, NULL, NULL);
uint64_t fileSize = GetSize();
m_pRootAtom->SetStart(0);
m_pRootAtom->SetSize(fileSize);
m_pRootAtom->SetEnd(fileSize);
m_pRootAtom->Read();
// create MP4Track's for any tracks in the file
GenerateTracks();
}
void MP4File::GenerateTracks()
{
uint32_t trackIndex = 0;
while (true) {
char trackName[32];
snprintf(trackName, sizeof(trackName), "moov.trak[%u]", trackIndex);
// find next trak atom
MP4Atom* pTrakAtom = m_pRootAtom->FindAtom(trackName);
// done, no more trak atoms
if (pTrakAtom == NULL) {
break;
}
// find track id property
MP4Integer32Property* pTrackIdProperty = NULL;
(void)pTrakAtom->FindProperty(
"trak.tkhd.trackId",
(MP4Property**)&pTrackIdProperty);
// find track type property
MP4StringProperty* pTypeProperty = NULL;
(void)pTrakAtom->FindProperty(
"trak.mdia.hdlr.handlerType",
(MP4Property**)&pTypeProperty);
// ensure we have the basics properties
if (pTrackIdProperty && pTypeProperty) {
m_trakIds.Add(pTrackIdProperty->GetValue());
MP4Track* pTrack = NULL;
try {
if (!strcmp(pTypeProperty->GetValue(), MP4_HINT_TRACK_TYPE)) {
pTrack = new MP4RtpHintTrack(*this, *pTrakAtom);
} else {
pTrack = new MP4Track(*this, *pTrakAtom);
}
m_pTracks.Add(pTrack);
}
catch( Exception* x ) {
log.errorf(*x);
delete x;
}
// remember when we encounter the OD track
if (pTrack && !strcmp(pTrack->GetType(), MP4_OD_TRACK_TYPE)) {
if (m_odTrackId == MP4_INVALID_TRACK_ID) {
m_odTrackId = pTrackIdProperty->GetValue();
} else {
log.warningf("%s: \"%s\": multiple OD tracks present",
__FUNCTION__, GetFilename().c_str() );
}
}
} else {
m_trakIds.Add(0);
}
trackIndex++;
}
}
void MP4File::CacheProperties()
{
FindIntegerProperty("moov.mvhd.modificationTime",
(MP4Property**)&m_pModificationProperty);
FindIntegerProperty("moov.mvhd.timeScale",
(MP4Property**)&m_pTimeScaleProperty);
FindIntegerProperty("moov.mvhd.duration",
(MP4Property**)&m_pDurationProperty);
}
void MP4File::BeginWrite()
{
m_pRootAtom->BeginWrite();
}
void MP4File::FinishWrite(uint32_t options)
{
// remove empty moov.udta.meta.ilst
{
MP4Atom* ilst = FindAtom( "moov.udta.meta.ilst" );
if( ilst ) {
if( ilst->GetNumberOfChildAtoms() == 0 ) {
ilst->GetParentAtom()->DeleteChildAtom( ilst );
delete ilst;
}
}
}
// remove empty moov.udta.meta
{
MP4Atom* meta = FindAtom( "moov.udta.meta" );
if( meta ) {
if( meta->GetNumberOfChildAtoms() == 0 ) {
meta->GetParentAtom()->DeleteChildAtom( meta );
delete meta;
}
else if( meta->GetNumberOfChildAtoms() == 1 ) {
if( ATOMID( meta->GetChildAtom( 0 )->GetType() ) == ATOMID( "hdlr" )) {
meta->GetParentAtom()->DeleteChildAtom( meta );
delete meta;
}
}
}
}
// remove empty moov.udta.name
{
MP4Atom* name = FindAtom( "moov.udta.name" );
if( name ) {
unsigned char *val = NULL;
uint32_t valSize = 0;
GetBytesProperty("moov.udta.name.value", (uint8_t**)&val, &valSize);
if( valSize == 0 ) {
name->GetParentAtom()->DeleteChildAtom( name );
delete name;
}
}
}
// remove empty moov.udta
{
MP4Atom* udta = FindAtom( "moov.udta" );
if( udta ) {
if( udta->GetNumberOfChildAtoms() == 0 ) {
udta->GetParentAtom()->DeleteChildAtom( udta );
delete udta;
}
}
}
// for all tracks, flush chunking buffers
for( uint32_t i = 0; i < m_pTracks.Size(); i++ ) {
ASSERT( m_pTracks[i] );
m_pTracks[i]->FinishWrite(options);
}
// ask root atom to write
m_pRootAtom->FinishWrite();
// finished all writes, if position < size then file has shrunk and
// we mark remaining bytes as free atom; otherwise trailing garbage remains.
if( GetPosition() < GetSize() ) {
MP4RootAtom* root = (MP4RootAtom*)FindAtom( "" );
ASSERT( root );
// compute size of free atom; always has 8 bytes of overhead
uint64_t size = GetSize() - GetPosition();
if( size < 8 )
size = 0;
else
size -= 8;
MP4FreeAtom* freeAtom = (MP4FreeAtom*)MP4Atom::CreateAtom( *this, NULL, "free" );
ASSERT( freeAtom );
freeAtom->SetSize( size );
root->AddChildAtom( freeAtom );
freeAtom->Write();
}
}
void MP4File::UpdateDuration(MP4Duration duration)
{
MP4Duration currentDuration = GetDuration();
if (duration > currentDuration) {
SetDuration(duration);
}
}
void MP4File::Dump( bool dumpImplicits )
{
log.dump(0, MP4_LOG_VERBOSE1, "\"%s\": Dumping meta-information...", m_file->name.c_str() );
m_pRootAtom->Dump( 0, dumpImplicits);
}
void MP4File::Close(uint32_t options)
{
if( IsWriteMode() ) {
SetIntegerProperty( "moov.mvhd.modificationTime", MP4GetAbsTimestamp() );
FinishWrite(options);
}
delete m_file;
m_file = NULL;
}
void MP4File::Rename(const char* oldFileName, const char* newFileName)
{
if( FileSystem::rename( oldFileName, newFileName ))
throw new PlatformException( sys::getLastErrorStr(), sys::getLastError(), __FILE__, __LINE__, __FUNCTION__ );
}
void MP4File::ProtectWriteOperation(const char* file,
int line,
const char* func )
{
if( !IsWriteMode() )
throw new Exception( "operation not permitted in read mode", file, line, func );
}
MP4Track* MP4File::GetTrack(MP4TrackId trackId)
{
return m_pTracks[FindTrackIndex(trackId)];
}
MP4Atom* MP4File::FindAtom(const char* name)
{
MP4Atom* pAtom = NULL;
if (!name || !strcmp(name, "")) {
pAtom = m_pRootAtom;
} else {
pAtom = m_pRootAtom->FindAtom(name);
}
return pAtom;
}
MP4Atom* MP4File::AddChildAtom(
const char* parentName,
const char* childName)
{
return AddChildAtom(FindAtom(parentName), childName);
}
MP4Atom* MP4File::AddChildAtom(
MP4Atom* pParentAtom,
const char* childName)
{
return InsertChildAtom(pParentAtom, childName,
pParentAtom->GetNumberOfChildAtoms());
}
MP4Atom* MP4File::InsertChildAtom(
const char* parentName,
const char* childName,
uint32_t index)
{
return InsertChildAtom(FindAtom(parentName), childName, index);
}
MP4Atom* MP4File::InsertChildAtom(
MP4Atom* pParentAtom,
const char* childName,
uint32_t index)
{
MP4Atom* pChildAtom = MP4Atom::CreateAtom(*this, pParentAtom, childName);
ASSERT(pParentAtom);
pParentAtom->InsertChildAtom(pChildAtom, index);
pChildAtom->Generate();
return pChildAtom;
}
MP4Atom* MP4File::AddDescendantAtoms(
const char* ancestorName,
const char* descendantNames)
{
return AddDescendantAtoms(FindAtom(ancestorName), descendantNames);
}
MP4Atom* MP4File::AddDescendantAtoms(
MP4Atom* pAncestorAtom, const char* descendantNames)
{
ASSERT(pAncestorAtom);
MP4Atom* pParentAtom = pAncestorAtom;
MP4Atom* pChildAtom = NULL;
while (true) {
char* childName = MP4NameFirst(descendantNames);
if (childName == NULL) {
break;
}
descendantNames = MP4NameAfterFirst(descendantNames);
pChildAtom = pParentAtom->FindChildAtom(childName);
if (pChildAtom == NULL) {
pChildAtom = AddChildAtom(pParentAtom, childName);
}
pParentAtom = pChildAtom;
MP4Free(childName);
}
return pChildAtom;
}
bool MP4File::FindProperty(const char* name,
MP4Property** ppProperty, uint32_t* pIndex)
{
if( pIndex )
*pIndex = 0; // set the default answer for index
return m_pRootAtom->FindProperty(name, ppProperty, pIndex);
}
void MP4File::FindIntegerProperty(const char* name,
MP4Property** ppProperty, uint32_t* pIndex)
{
if (!FindProperty(name, ppProperty, pIndex)) {
ostringstream msg;
msg << "no such property - " << name;
throw new Exception(msg.str(), __FILE__, __LINE__, __FUNCTION__);
}
switch ((*ppProperty)->GetType()) {
case Integer8Property:
case Integer16Property:
case Integer24Property:
case Integer32Property:
case Integer64Property:
break;
default:
ostringstream msg;
msg << "type mismatch - property " << name << " type " << (*ppProperty)->GetType();
throw new Exception(msg.str(), __FILE__, __LINE__, __FUNCTION__);
}
}
uint64_t MP4File::GetIntegerProperty(const char* name)
{
MP4Property* pProperty;
uint32_t index;
FindIntegerProperty(name, &pProperty, &index);
return ((MP4IntegerProperty*)pProperty)->GetValue(index);
}
void MP4File::SetIntegerProperty(const char* name, uint64_t value)
{
ProtectWriteOperation(__FILE__, __LINE__, __FUNCTION__);
MP4Property* pProperty = NULL;
uint32_t index = 0;
FindIntegerProperty(name, &pProperty, &index);
((MP4IntegerProperty*)pProperty)->SetValue(value, index);
}
void MP4File::FindFloatProperty(const char* name,
MP4Property** ppProperty, uint32_t* pIndex)
{
if (!FindProperty(name, ppProperty, pIndex)) {
ostringstream msg;
msg << "no such property - " << name;
throw new Exception(msg.str(), __FILE__, __LINE__, __FUNCTION__);
}
if ((*ppProperty)->GetType() != Float32Property) {
ostringstream msg;
msg << "type mismatch - property " << name << " type " << (*ppProperty)->GetType();
throw new Exception(msg.str(), __FILE__, __LINE__, __FUNCTION__);
}
}
float MP4File::GetFloatProperty(const char* name)
{
MP4Property* pProperty;
uint32_t index;
FindFloatProperty(name, &pProperty, &index);
return ((MP4Float32Property*)pProperty)->GetValue(index);
}
void MP4File::SetFloatProperty(const char* name, float value)
{
ProtectWriteOperation(__FILE__, __LINE__, __FUNCTION__);
MP4Property* pProperty;
uint32_t index;
FindFloatProperty(name, &pProperty, &index);
((MP4Float32Property*)pProperty)->SetValue(value, index);
}
void MP4File::FindStringProperty(const char* name,
MP4Property** ppProperty, uint32_t* pIndex)
{
if (!FindProperty(name, ppProperty, pIndex)) {
ostringstream msg;
msg << "no such property - " << name;
throw new Exception(msg.str(), __FILE__, __LINE__, __FUNCTION__);
}
if ((*ppProperty)->GetType() != StringProperty) {
ostringstream msg;
msg << "type mismatch - property " << name << " type " << (*ppProperty)->GetType();
throw new Exception(msg.str(), __FILE__, __LINE__, __FUNCTION__);
}
}
const char* MP4File::GetStringProperty(const char* name)
{
MP4Property* pProperty;
uint32_t index;
FindStringProperty(name, &pProperty, &index);
return ((MP4StringProperty*)pProperty)->GetValue(index);
}
void MP4File::SetStringProperty(const char* name, const char* value)
{
ProtectWriteOperation(__FILE__, __LINE__, __FUNCTION__);
MP4Property* pProperty;
uint32_t index;
FindStringProperty(name, &pProperty, &index);
((MP4StringProperty*)pProperty)->SetValue(value, index);
}
void MP4File::FindBytesProperty(const char* name,
MP4Property** ppProperty, uint32_t* pIndex)
{
if (!FindProperty(name, ppProperty, pIndex)) {
ostringstream msg;
msg << "no such property " << name;
throw new Exception(msg.str(), __FILE__, __LINE__, __FUNCTION__);
}
if ((*ppProperty)->GetType() != BytesProperty) {
ostringstream msg;
msg << "type mismatch - property " << name << " - type " << (*ppProperty)->GetType();
throw new Exception(msg.str(), __FILE__, __LINE__, __FUNCTION__);
}
}
void MP4File::GetBytesProperty(const char* name,
uint8_t** ppValue, uint32_t* pValueSize)
{
MP4Property* pProperty;
uint32_t index;
FindBytesProperty(name, &pProperty, &index);
((MP4BytesProperty*)pProperty)->GetValue(ppValue, pValueSize, index);
}
void MP4File::SetBytesProperty(const char* name,
const uint8_t* pValue, uint32_t valueSize)
{
ProtectWriteOperation(__FILE__, __LINE__, __FUNCTION__);
MP4Property* pProperty;
uint32_t index;
FindBytesProperty(name, &pProperty, &index);
((MP4BytesProperty*)pProperty)->SetValue(pValue, valueSize, index);
}
// track functions
MP4TrackId MP4File::AddTrack(const char* type, uint32_t timeScale)
{
ProtectWriteOperation(__FILE__, __LINE__, __FUNCTION__);
// create and add new trak atom
MP4Atom* pTrakAtom = AddChildAtom("moov", "trak");
ASSERT(pTrakAtom);
// allocate a new track id
MP4TrackId trackId = AllocTrackId();
m_trakIds.Add(trackId);
// set track id
MP4Integer32Property* pInteger32Property = NULL;
(void)pTrakAtom->FindProperty("trak.tkhd.trackId",
(MP4Property**)&pInteger32Property);
ASSERT(pInteger32Property);
pInteger32Property->SetValue(trackId);
// set track type
const char* normType = MP4NormalizeTrackType(type);
// sanity check for user defined types
if (strlen(normType) > 4) {
log.warningf("%s: \"%s\": type truncated to four characters",
__FUNCTION__, GetFilename().c_str());
// StringProperty::SetValue() will do the actual truncation
}
MP4StringProperty* pStringProperty = NULL;
(void)pTrakAtom->FindProperty("trak.mdia.hdlr.handlerType",
(MP4Property**)&pStringProperty);
ASSERT(pStringProperty);
pStringProperty->SetValue(normType);
// set track time scale
pInteger32Property = NULL;
(void)pTrakAtom->FindProperty("trak.mdia.mdhd.timeScale",
(MP4Property**)&pInteger32Property);
ASSERT(pInteger32Property);
pInteger32Property->SetValue(timeScale ? timeScale : 1000);
// now have enough to create MP4Track object
MP4Track* pTrack = NULL;
if (!strcmp(normType, MP4_HINT_TRACK_TYPE)) {
pTrack = new MP4RtpHintTrack(*this, *pTrakAtom);
} else {
pTrack = new MP4Track(*this, *pTrakAtom);
}
m_pTracks.Add(pTrack);
// mark non-hint tracks as enabled
if (strcmp(normType, MP4_HINT_TRACK_TYPE)) {
SetTrackIntegerProperty(trackId, "tkhd.flags", 1);
}
// mark track as contained in this file
// LATER will provide option for external data references
AddDataReference(trackId, NULL);
return trackId;
}
void MP4File::AddTrackToIod(MP4TrackId trackId)
{
MP4DescriptorProperty* pDescriptorProperty = NULL;
(void)m_pRootAtom->FindProperty("moov.iods.esIds",
(MP4Property**)&pDescriptorProperty);
ASSERT(pDescriptorProperty);
MP4Descriptor* pDescriptor =
pDescriptorProperty->AddDescriptor(MP4ESIDIncDescrTag);
ASSERT(pDescriptor);
MP4Integer32Property* pIdProperty = NULL;
(void)pDescriptor->FindProperty("id",
(MP4Property**)&pIdProperty);
ASSERT(pIdProperty);
pIdProperty->SetValue(trackId);
}
void MP4File::RemoveTrackFromIod(MP4TrackId trackId, bool shallHaveIods)
{
MP4DescriptorProperty* pDescriptorProperty = NULL;
if (!m_pRootAtom->FindProperty("moov.iods.esIds",(MP4Property**)&pDescriptorProperty)
|| pDescriptorProperty == NULL)
return;
for (uint32_t i = 0; i < pDescriptorProperty->GetCount(); i++) {
/* static */
char name[32];
snprintf(name, sizeof(name), "esIds[%u].id", i);
MP4Integer32Property* pIdProperty = NULL;
(void)pDescriptorProperty->FindProperty(name,
(MP4Property**)&pIdProperty);