-
Notifications
You must be signed in to change notification settings - Fork 1
/
matroska_parser.cpp
2651 lines (2371 loc) · 87.5 KB
/
matroska_parser.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
/*
* Part of the foobar2000 Matroska plugin
*
* Copyright (C) Jory 'jcsston' Stone (jcsston at toughguy net) - 2003-2004
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
* WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
*/
/*!
\file matroska_parser.cpp
\version $Id$
\brief An audio slated Matroska Reader+Parser
\author Jory Stone <jcsston @ toughguy.net>
*/
#include "matroska_parser.h"
#include <string>
using std::string;
using namespace LIBEBML_NAMESPACE;
using namespace LIBMATROSKA_NAMESPACE;
static const char * rg_fields[]=
{
"REPLAYGAIN_GAIN",
"REPLAYGAIN_PEAK"
};
static const char * rg_track_fields[]=
{
"REPLAYGAIN_TRACK_GAIN",
"REPLAYGAIN_TRACK_PEAK"
};
static const char * rg_album_fields[]=
{
"REPLAYGAIN_ALBUM_GAIN",
"REPLAYGAIN_ALBUM_PEAK"
};
#define MATROSKA_TAG_IDX 0
#define FOOBAR2K_TAG_IDX 1
static const char * chapter_tag_mapping[][2] =
{
{ "PART_NUMBER", "TRACKNUMBER" },
{ "DATE_RELEASED", "DATE" },
//{ "LEAD_PERFORMER", "PERFORMER" },
//{ "ACCOMPANIMENT", "BAND" },
//{ "LYRICIST", "WRITER" }
};
static const char * edition_tag_mapping[][2] =
{
{ "TITLE", "ALBUM" },
{ "CATALOG_NUMBER", "CATALOG" },
{ "TOTAL_PARTS", "TOTALTRACKS" },
//{ "PART_NUMBER", "DISCNUMBER" },
//{ "TOTAL_DISCS", "TOTALDISCS" }
};
static const char * hidden_edition_field[] =
{
"___DUMMY___",
};
static const char * hidden_chapter_field[] =
{
"CDAUDIO_TRACK_FLAGS",
};
bool starts_with(const string &s, const char *start) {
return strncmp(s.c_str(), start, strlen(start)) == 0;
};
uint64 MatroskaAudioParser::SecondsToTimecode(double seconds)
{
return (uint64)floor(seconds * 1000000000);
};
double MatroskaAudioParser::TimecodeToSeconds(uint64 code,unsigned samplerate_hint)
{
return ((double)(int64)code / 1000000000);
};
MatroskaAudioFrame::MatroskaAudioFrame()
{
timecode = 0;
duration = 0;
add_id = 0;
};
MatroskaAttachment::MatroskaAttachment()
{
FileName = L"";
MimeType = "";
Description = L"";
SourceFilename = L"";
SourceStartPos = 0;
SourceDataLength = 0;
};
void MatroskaAudioFrame::Reset()
{
timecode = 0;
duration = 0;
add_id = 0;
};
MatroskaSimpleTag::MatroskaSimpleTag()
{
name = L"";
value = L"";
language = "und";
defaultFlag = 1;
hidden = false;
removalPending = false;
};
MatroskaTagInfo::MatroskaTagInfo()
{
targetTrackUID = 0;
targetEditionUID = 0;
targetChapterUID = 0;
targetAttachmentUID = 0;
targetTypeValue = 0;
};
void MatroskaTagInfo::SetTagValue(const char *name, const char *value, int index)
{
for (size_t s = 0; s < tags.size(); s++)
{
MatroskaSimpleTag ¤tSimpleTag = tags.at(s);
if (strcmpi(currentSimpleTag.name.GetUTF8().c_str(), name) == 0)
{
if(index == 0)
{
currentSimpleTag.value.SetUTF8(value);
currentSimpleTag.removalPending = false;
return;
}
index--;
}
}
// If we are here then we didn't find this tag in the vector already
MatroskaSimpleTag newSimpleTag;
newSimpleTag.name.SetUTF8(name);
newSimpleTag.value.SetUTF8(value);
newSimpleTag.removalPending = false;
tags.push_back(newSimpleTag);
};
void MatroskaTagInfo::RemoveMarkedTags()
{
for (int i = tags.size()-1; i >= 0; i--)
{
MatroskaSimpleTag &simpleTag = tags.at(i);
if(simpleTag.removalPending == true)
{
tags.erase(tags.begin() + i);
}
}
}
void MatroskaTagInfo::MarkAllAsRemovalPending()
{
for (int i = tags.size()-1; i >= 0; i--)
{
MatroskaSimpleTag &simpleTag = tags.at(i);
simpleTag.removalPending = true;
}
}
MatroskaChapterDisplayInfo::MatroskaChapterDisplayInfo() {
string = L"";
};
MatroskaChapterInfo::MatroskaChapterInfo() {
chapterUID = 0;
timeStart = 0;
timeEnd = 0;
}
MatroskaEditionInfo::MatroskaEditionInfo() {
editionUID = 0;
}
MatroskaTrackInfo::MatroskaTrackInfo() {
trackNumber = 0;
trackUID = 0;
duration = 0;
channels = 1;
samplesPerSec = 0;
samplesOutputPerSec = 0;
bitsPerSample = 0;
avgBytesPerSec = 0;
defaultDuration = 0;
name = L"";
codecPrivateReady = false;
};
MatroskaAudioParser::MatroskaAudioParser(service_ptr_t<file> input, abort_callback & p_abort)
: m_IOCallback(input, p_abort),
m_InputStream(m_IOCallback)
{
m_TimecodeScale = TIMECODE_SCALE;
m_FileDate = 0;
m_Duration = 0;
m_CurrentTimecode = 0;
//m_ElementLevel0 = NULL;
//UpperElementLevel = 0;
m_CurrentEdition = 0;
m_CurrentChapter = 0;
m_FileSize = input->get_size(p_abort);
m_TagPos = 0;
m_TagSize = 0;
m_TagScanRange = 1024 * 64;
m_CurrentTrackNo = 0;
};
MatroskaAudioParser::~MatroskaAudioParser() {
//if (m_ElementLevel0 != NULL)
// _DELETE(m_ElementLevel0);
//delete m_ElementLevel0;
while (!m_Queue.empty()) {
MatroskaAudioFrame *currentPacket = m_Queue.front();
//delete currentPacket;
_DELETE(currentPacket);
m_Queue.pop();
}
};
int MatroskaAudioParser::Parse(bool bInfoOnly, bool bBreakAtClusters)
{
try {
int UpperElementLevel = 0;
bool bAllowDummy = false;
// Elements for different levels
ElementPtr ElementLevel1;
ElementPtr ElementLevel2;
ElementPtr ElementLevel3;
ElementPtr ElementLevel4;
ElementPtr ElementLevel5;
ElementPtr NullElement;
// Be sure we are at the beginning of the file
m_IOCallback.setFilePointer(0);
// Find the EbmlHead element. Must be the first one.
m_ElementLevel0 = ElementPtr(m_InputStream.FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFFFFFFFFFL));
if (m_ElementLevel0 == NullElement) {
return 1;
}
//We must have found the EBML head :)
m_ElementLevel0->SkipData(m_InputStream, m_ElementLevel0->Generic().Context);
//delete m_ElementLevel0;
//_DELETE(m_ElementLevel0);
// Next element must be a segment
m_ElementLevel0 = ElementPtr(m_InputStream.FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFFFFFFFFFL));
if (m_ElementLevel0 == NullElement) {
//No segment/level 0 element found.
return 1;
}
if (!(EbmlId(*m_ElementLevel0) == KaxSegment::ClassInfos.GlobalId)) {
//delete m_ElementLevel0;
//m_ElementLevel0 = NULL;
//_DELETE(m_ElementLevel0);
return 1;
}
UpperElementLevel = 0;
// We've got our segment, so let's find the tracks
ElementLevel1 = ElementPtr(m_InputStream.FindNextElement(m_ElementLevel0->Generic().Context, UpperElementLevel, 0xFFFFFFFFFFFFFFFFL, true, 1));
while (ElementLevel1 != NullElement) {
if (UpperElementLevel > 0) {
break;
}
if (UpperElementLevel < 0) {
UpperElementLevel = 0;
}
if (EbmlId(*ElementLevel1) == KaxSeekHead::ClassInfos.GlobalId) {
if (m_IOCallback.seekable()) {
Parse_MetaSeek(ElementLevel1, bInfoOnly);
if (m_TagPos == 0) {
// Search for them at the end of the file
if (m_TagScanRange > 0)
{
m_IOCallback.setFilePointer(m_FileSize - m_TagScanRange);
uint64 init_pos = m_IOCallback.getFilePointer();
/*
BM Search
*/
binary buf[1024*64];
binary pat[3]; pat[0] = 0x54; pat[1] = 0xc3; pat[2] = 0x67;
uint64 s_pos = m_IOCallback.getFilePointer();
m_IOCallback.read(buf, m_TagScanRange);
MatroskaSearch search(buf, pat);
int pos = search.Match();
if (pos != -1) {
do {
m_IOCallback.setFilePointer(s_pos+pos+3);
uint64 startPos = m_IOCallback.getFilePointer();
m_IOCallback.setFilePointer(-4, seek_current);
ElementPtr levelUnknown = ElementPtr(m_InputStream.FindNextID(KaxTags::ClassInfos, 0xFFFFFFFFFFFFFFFFL));
if ((levelUnknown != NullElement)
&& (m_FileSize >= startPos + levelUnknown->GetSize())
&& (EbmlId(*levelUnknown) == KaxTags::ClassInfos.GlobalId))
{
Parse_Tags(static_cast<KaxTags *>(levelUnknown.get()));
break;
}
m_IOCallback.setFilePointer(s_pos);
pos = search.Match(pos+1);
} while (pos != -1);
/*
~BM Search
*/
} else {
m_IOCallback.setFilePointer(init_pos);
binary Buffer[4];
while (m_IOCallback.read(Buffer, 3) >= 3)
{//0x18
if ((Buffer[0] == 0x54) && (Buffer[1] == 0xc3) && (Buffer[2] == 0x67))
{
uint64 startPos = m_IOCallback.getFilePointer();
//seek back 3 bytes, so libmatroska can find the Tags element Ebml ID
m_IOCallback.setFilePointer(-4, seek_current);
ElementPtr levelUnknown = ElementPtr(m_InputStream.FindNextID(KaxTags::ClassInfos, 0xFFFFFFFFFFFFFFFFL));
if ((levelUnknown != NullElement)
&& (m_FileSize >= startPos + levelUnknown->GetSize())
&& (EbmlId(*levelUnknown) == KaxTags::ClassInfos.GlobalId))
{
Parse_Tags(static_cast<KaxTags *>(levelUnknown.get()));
//_DELETE(levelUnknown);
break;
}
//_DELETE(levelUnknown);
//Restore the file pos
m_IOCallback.setFilePointer(startPos);
}
//seek back 2 bytes
m_IOCallback.setFilePointer(-2, seek_current);
}
}
} else {
//m_TagPos = m_FileSize;
}
}
}
}else if (EbmlId(*ElementLevel1) == KaxInfo::ClassInfos.GlobalId) {
// General info about this Matroska file
ElementLevel2 = ElementPtr(m_InputStream.FindNextElement(ElementLevel1->Generic().Context, UpperElementLevel, 0xFFFFFFFFFFFFFFFFL, bAllowDummy));
while (ElementLevel2 != NullElement) {
if (UpperElementLevel > 0) {
break;
}
if (UpperElementLevel < 0) {
UpperElementLevel = 0;
}
if (EbmlId(*ElementLevel2) == KaxTimecodeScale::ClassInfos.GlobalId) {
KaxTimecodeScale &TimeScale = *static_cast<KaxTimecodeScale *>(ElementLevel2.get());
TimeScale.ReadData(m_InputStream.I_O());
//matroskaGlobalTrack->SetTimecodeScale(uint64(TimeScale));
m_TimecodeScale = uint64(TimeScale);
} else if (EbmlId(*ElementLevel2) == KaxDuration::ClassInfos.GlobalId) {
KaxDuration &duration = *static_cast<KaxDuration *>(ElementLevel2.get());
duration.ReadData(m_InputStream.I_O());
// it's in milliseconds? -- in nanoseconds.
m_Duration = double(duration) * m_TimecodeScale;
} else if (EbmlId(*ElementLevel2) == KaxDateUTC::ClassInfos.GlobalId) {
KaxDateUTC & DateUTC = *static_cast<KaxDateUTC *>(ElementLevel2.get());
DateUTC.ReadData(m_InputStream.I_O());
m_FileDate = DateUTC.GetEpochDate();
} else if (EbmlId(*ElementLevel2) == KaxSegmentFilename::ClassInfos.GlobalId) {
KaxSegmentFilename &tag_SegmentFilename = *static_cast<KaxSegmentFilename *>(ElementLevel2.get());
tag_SegmentFilename.ReadData(m_InputStream.I_O());
m_SegmentFilename = *static_cast<EbmlUnicodeString *>(&tag_SegmentFilename);
} else if (EbmlId(*ElementLevel2) == KaxMuxingApp::ClassInfos.GlobalId) {
KaxMuxingApp &tag_MuxingApp = *static_cast<KaxMuxingApp *>(ElementLevel2.get());
tag_MuxingApp.ReadData(m_InputStream.I_O());
m_MuxingApp = *static_cast<EbmlUnicodeString *>(&tag_MuxingApp);
} else if (EbmlId(*ElementLevel2) == KaxWritingApp::ClassInfos.GlobalId) {
KaxWritingApp &tag_WritingApp = *static_cast<KaxWritingApp *>(ElementLevel2.get());
tag_WritingApp.ReadData(m_InputStream.I_O());
m_WritingApp = *static_cast<EbmlUnicodeString *>(&tag_WritingApp);
} else if (EbmlId(*ElementLevel2) == KaxTitle::ClassInfos.GlobalId) {
KaxTitle &Title = *static_cast<KaxTitle*>(ElementLevel2.get());
Title.ReadData(m_InputStream.I_O());
m_FileTitle = UTFstring(Title).c_str();
}
if (UpperElementLevel > 0) { // we're coming from ElementLevel3
UpperElementLevel--;
//delete ElementLevel2;
ElementLevel2 = ElementLevel3;
if (UpperElementLevel > 0)
break;
} else {
ElementLevel2->SkipData(m_InputStream, ElementLevel2->Generic().Context);
//delete ElementLevel2;
//_DELETE(ElementLevel2);
ElementLevel2 = ElementPtr(m_InputStream.FindNextElement(ElementLevel1->Generic().Context, UpperElementLevel, 0xFFFFFFFFFFFFFFFFL, bAllowDummy));
}
}
}else if (EbmlId(*ElementLevel1) == KaxChapters::ClassInfos.GlobalId) {
Parse_Chapters(static_cast<KaxChapters *>(ElementLevel1.get()));
}else if (EbmlId(*ElementLevel1) == KaxTags::ClassInfos.GlobalId) {
Parse_Tags(static_cast<KaxTags *>(ElementLevel1.get()));
} else if (EbmlId(*ElementLevel1) == KaxTracks::ClassInfos.GlobalId) {
// Yep, we've found our KaxTracks element. Now find all tracks
// contained in this segment.
KaxTracks *Tracks = static_cast<KaxTracks *>(ElementLevel1.get());
EbmlElement* tmpElement = ElementLevel2.get();
Tracks->Read(m_InputStream, KaxTracks::ClassInfos.Context, UpperElementLevel, tmpElement, bAllowDummy);
unsigned int Index0;
for (Index0 = 0; Index0 < Tracks->ListSize(); Index0++) {
if ((*Tracks)[Index0]->Generic().GlobalId == KaxTrackEntry::ClassInfos.GlobalId) {
KaxTrackEntry &TrackEntry = *static_cast<KaxTrackEntry *>((*Tracks)[Index0]);
// Create a new MatroskaTrack
MatroskaTrackInfo newTrack;
unsigned int Index1;
for (Index1 = 0; Index1 < TrackEntry.ListSize(); Index1++) {
if (TrackEntry[Index1]->Generic().GlobalId == KaxTrackNumber::ClassInfos.GlobalId) {
KaxTrackNumber &TrackNumber = *static_cast<KaxTrackNumber*>(TrackEntry[Index1]);
newTrack.trackNumber = TrackNumber;
} else if (TrackEntry[Index1]->Generic().GlobalId == KaxTrackUID::ClassInfos.GlobalId) {
KaxTrackUID &TrackUID = *static_cast<KaxTrackUID*>(TrackEntry[Index1]);
newTrack.trackUID = TrackUID;
} else if (TrackEntry[Index1]->Generic().GlobalId == KaxTrackType::ClassInfos.GlobalId) {
KaxTrackType &TrackType = *static_cast<KaxTrackType*>(TrackEntry[Index1]);
if (uint8(TrackType) != track_audio) {
newTrack.trackNumber = 0xFFFF;
break;
}
} else if (TrackEntry[Index1]->Generic().GlobalId == KaxTrackTimecodeScale::ClassInfos.GlobalId) {
KaxTrackTimecodeScale &TrackTimecodeScale = *static_cast<KaxTrackTimecodeScale*>(TrackEntry[Index1]);
// TODO: Support Tracks with different timecode scales?
//newTrack->TrackTimecodeScale = TrackTimecodeScale;
} else if (TrackEntry[Index1]->Generic().GlobalId == KaxTrackDefaultDuration::ClassInfos.GlobalId) {
KaxTrackDefaultDuration &TrackDefaultDuration = *static_cast<KaxTrackDefaultDuration*>(TrackEntry[Index1]);
newTrack.defaultDuration = uint64(TrackDefaultDuration);
} else if (TrackEntry[Index1]->Generic().GlobalId == KaxCodecID::ClassInfos.GlobalId) {
KaxCodecID &CodecID = *static_cast<KaxCodecID*>(TrackEntry[Index1]);
newTrack.codecID = std::string(CodecID);
} else if (TrackEntry[Index1]->Generic().GlobalId == KaxCodecPrivate::ClassInfos.GlobalId) {
KaxCodecPrivate &CodecPrivate = *static_cast<KaxCodecPrivate*>(TrackEntry[Index1]);
newTrack.codecPrivate.resize(CodecPrivate.GetSize());
memcpy(&newTrack.codecPrivate[0], CodecPrivate.GetBuffer(), CodecPrivate.GetSize());
} else if (TrackEntry[Index1]->Generic().GlobalId == KaxTrackFlagDefault::ClassInfos.GlobalId) {
KaxTrackFlagDefault &TrackFlagDefault = *static_cast<KaxTrackFlagDefault*>(TrackEntry[Index1]);
//newTrack->FlagDefault = TrackFlagDefault;
/* Matroska2
} else if (TrackEntry[Index1]->Generic().GlobalId == KaxTrackFlagEnabled::ClassInfos.GlobalId) {
KaxTrackFlagEnabled &TrackFlagEnabled = *static_cast<KaxTrackFlagEnabled*>(TrackEntry[Index1]);
//newTrack->FlagEnabled = TrackFlagEnabled;
*/
} else if (TrackEntry[Index1]->Generic().GlobalId == KaxTrackFlagLacing::ClassInfos.GlobalId) {
KaxTrackFlagLacing &TrackFlagLacing = *static_cast<KaxTrackFlagLacing*>(TrackEntry[Index1]);
//newTrack->FlagLacing = TrackFlagLacing;
} else if (TrackEntry[Index1]->Generic().GlobalId == KaxTrackLanguage::ClassInfos.GlobalId) {
KaxTrackLanguage &TrackLanguage = *static_cast<KaxTrackLanguage*>(TrackEntry[Index1]);
newTrack.language = std::string(TrackLanguage);
} else if (TrackEntry[Index1]->Generic().GlobalId == KaxTrackMaxCache::ClassInfos.GlobalId) {
KaxTrackMaxCache &TrackMaxCache = *static_cast<KaxTrackMaxCache*>(TrackEntry[Index1]);
//newTrack->MaxCache = TrackMaxCache;
} else if (TrackEntry[Index1]->Generic().GlobalId == KaxTrackMinCache::ClassInfos.GlobalId) {
KaxTrackMinCache &TrackMinCache = *static_cast<KaxTrackMinCache*>(TrackEntry[Index1]);
//newTrack->MinCache = TrackMinCache;
} else if (TrackEntry[Index1]->Generic().GlobalId == KaxTrackName::ClassInfos.GlobalId) {
KaxTrackName &TrackName = *static_cast<KaxTrackName*>(TrackEntry[Index1]);
newTrack.name = TrackName;
} else if (TrackEntry[Index1]->Generic().GlobalId == KaxTrackAudio::ClassInfos.GlobalId) {
KaxTrackAudio &TrackAudio = *static_cast<KaxTrackAudio*>(TrackEntry[Index1]);
unsigned int Index2;
for (Index2 = 0; Index2 < TrackAudio.ListSize(); Index2++) {
if (TrackAudio[Index2]->Generic().GlobalId == KaxAudioBitDepth::ClassInfos.GlobalId) {
KaxAudioBitDepth &AudioBitDepth = *static_cast<KaxAudioBitDepth*>(TrackAudio[Index2]);
newTrack.bitsPerSample = AudioBitDepth;
/* Matroska2
} else if (TrackAudio[Index2]->Generic().GlobalId == KaxAudioPosition::ClassInfos.GlobalId) {
KaxAudioPosition &AudioPosition = *static_cast<KaxAudioPosition*>(TrackAudio[Index2]);
// TODO: Support multi-channel?
//newTrack->audio->ChannelPositionSize = AudioPosition.GetSize();
//newTrack->audio->ChannelPosition = new binary[AudioPosition.GetSize()+1];
//memcpy(newTrack->audio->ChannelPosition, AudioPosition.GetBuffer(), AudioPosition.GetSize());
*/
} else if (TrackAudio[Index2]->Generic().GlobalId == KaxAudioChannels::ClassInfos.GlobalId) {
KaxAudioChannels &AudioChannels = *static_cast<KaxAudioChannels*>(TrackAudio[Index2]);
newTrack.channels = AudioChannels;
} else if (TrackAudio[Index2]->Generic().GlobalId == KaxAudioOutputSamplingFreq::ClassInfos.GlobalId) {
KaxAudioOutputSamplingFreq &AudioOutputSamplingFreq = *static_cast<KaxAudioOutputSamplingFreq*>(TrackAudio[Index2]);
newTrack.samplesOutputPerSec = AudioOutputSamplingFreq;
} else if (TrackAudio[Index2]->Generic().GlobalId == KaxAudioSamplingFreq::ClassInfos.GlobalId) {
KaxAudioSamplingFreq &AudioSamplingFreq = *static_cast<KaxAudioSamplingFreq*>(TrackAudio[Index2]);
newTrack.samplesPerSec = AudioSamplingFreq;
}
}
}
}
if (newTrack.trackNumber != 0xFFFF)
m_Tracks.push_back(newTrack);
}
}
} else if (EbmlId(*ElementLevel1) == KaxCluster::ClassInfos.GlobalId) {
if (bBreakAtClusters) {
m_IOCallback.setFilePointer(ElementLevel1->GetElementPosition());
//delete ElementLevel1;
//ElementLevel1 = NULL;
//_DELETE(ElementLevel1);
break;
}
} else if (EbmlId(*ElementLevel1) == KaxAttachments::ClassInfos.GlobalId) {
// Yep, we've found our KaxAttachment element. Now find all attached files
// contained in this segment.
#if 1
ElementLevel2 = ElementPtr(m_InputStream.FindNextElement(ElementLevel1->Generic().Context, UpperElementLevel, 0xFFFFFFFFL, true, 1));
while (ElementLevel2 != NullElement) {
if (UpperElementLevel > 0) {
break;
}
if (UpperElementLevel < 0) {
UpperElementLevel = 0;
}
if (EbmlId(*ElementLevel2) == KaxAttached::ClassInfos.GlobalId) {
// We actually found a attached file entry :D
MatroskaAttachment newAttachment;
ElementLevel3 = ElementPtr(m_InputStream.FindNextElement(ElementLevel2->Generic().Context, UpperElementLevel, 0xFFFFFFFFL, true, 1));
while (ElementLevel3 != NullElement) {
if (UpperElementLevel > 0) {
break;
}
if (UpperElementLevel < 0) {
UpperElementLevel = 0;
}
// Now evaluate the data belonging to this track
if (EbmlId(*ElementLevel3) == KaxFileName::ClassInfos.GlobalId) {
KaxFileName &attached_filename = *static_cast<KaxFileName *>(ElementLevel3.get());
attached_filename.ReadData(m_InputStream.I_O());
newAttachment.FileName = UTFstring(attached_filename);
} else if (EbmlId(*ElementLevel3) == KaxMimeType::ClassInfos.GlobalId) {
KaxMimeType &attached_mime_type = *static_cast<KaxMimeType *>(ElementLevel3.get());
attached_mime_type.ReadData(m_InputStream.I_O());
newAttachment.MimeType = std::string(attached_mime_type);
} else if (EbmlId(*ElementLevel3) == KaxFileDescription::ClassInfos.GlobalId) {
KaxFileDescription &attached_description = *static_cast<KaxFileDescription *>(ElementLevel3.get());
attached_description.ReadData(m_InputStream.I_O());
newAttachment.Description = UTFstring(attached_description);
} else if (EbmlId(*ElementLevel3) == KaxFileData::ClassInfos.GlobalId) {
KaxFileData &attached_data = *static_cast<KaxFileData *>(ElementLevel3.get());
//We don't what to read the data into memory because it could be very large
//attached_data.ReadData(m_InputStream.I_O());
//Instead we store the Matroska filename, the start of the data and the length, so we can read it
//later at the users request. IMHO This will save a lot of memory
newAttachment.SourceStartPos = attached_data.GetElementPosition() + attached_data.HeadSize();
newAttachment.SourceDataLength = attached_data.GetSize();
}
if (UpperElementLevel > 0) { // we're coming from ElementLevel4
UpperElementLevel--;
ElementLevel3 = ElementLevel4;
if (UpperElementLevel > 0)
break;
} else {
ElementLevel3->SkipData(m_InputStream, ElementLevel3->Generic().Context);
ElementLevel3 = ElementPtr(m_InputStream.FindNextElement(ElementLevel2->Generic().Context, UpperElementLevel, 0xFFFFFFFFL, true, 1));
}
} // while (ElementLevel3 != NULL)
//m_AttachmentList.push_back(newAttachment);
m_AttachmentList.add_item(newAttachment);
}
if (UpperElementLevel > 0) { // we're coming from ElementLevel3
UpperElementLevel--;
ElementLevel2 = ElementLevel3;
if (UpperElementLevel > 0)
break;
} else {
ElementLevel2->SkipData(m_InputStream, ElementLevel2->Generic().Context);
ElementLevel2 = ElementPtr(m_InputStream.FindNextElement(ElementLevel1->Generic().Context, UpperElementLevel, 0xFFFFFFFFL, true, 1));
}
} // while (ElementLevel2 != NULL)
#endif
}
if (UpperElementLevel > 0) { // we're coming from ElementLevel2
UpperElementLevel--;
//delete ElementLevel1;
//_DELETE(ElementLevel1);
ElementLevel1 = ElementLevel2;
if (UpperElementLevel > 0)
break;
} else {
ElementLevel1->SkipData(m_InputStream, ElementLevel1->Generic().Context);
//delete ElementLevel1;
//ElementLevel1 = NULL;
//_DELETE(ElementLevel1);
ElementLevel1 = ElementPtr(m_InputStream.FindNextElement(m_ElementLevel0->Generic().Context, UpperElementLevel, 0xFFFFFFFFFFFFFFFFL, true, 1));
}
} // while (ElementLevel1 != NULL)
//_DELETE(ElementLevel3);
//_DELETE(ElementLevel2);
//_DELETE(ElementLevel1);
} catch (std::exception &) {
return 1;
} catch (...) {
return 1;
}
CountClusters();
return 0;
};
//int MatroskaAudioParser::WriteTags(const file_info & info)
int MatroskaAudioParser::WriteTags()
{
KaxTags & MyKaxTags = GetChild<KaxTags>(*static_cast<EbmlMaster *>(m_ElementLevel0.get()));
// On to writing :)
if (m_TagPos == 0) {
// Ok, we need to append the tags onto the end of the file, no existing tag element
m_TagPos = m_FileSize;
} else {
}
//Start going through the list and adding tags
KaxTag *MyKaxTag_last = NULL;
for(size_t current_tag_track = 0; current_tag_track < m_Tags.size(); current_tag_track++) {
KaxTag *MyKaxTag = NULL;
if (MyKaxTag_last != NULL)
{
MyKaxTag = &GetNextChild<KaxTag>(MyKaxTags, *MyKaxTag_last);
MyKaxTag_last = MyKaxTag;
}else {
MyKaxTag = &GetChild<KaxTag>(MyKaxTags);
MyKaxTag_last = MyKaxTag;
}
MatroskaTagInfo ¤tTag = m_Tags.at(current_tag_track);
//The Targets group
KaxTagTargets & MyKaxTagTargets = GetChild<KaxTagTargets>(*MyKaxTag);
if (currentTag.targetTrackUID != 0) {
KaxTagTrackUID & MyKaxTagTrackUID = GetChild<KaxTagTrackUID>(MyKaxTagTargets);
*static_cast<EbmlUInteger *>(&MyKaxTagTrackUID) = currentTag.targetTrackUID;
}
if (currentTag.targetEditionUID != 0) {
KaxTagEditionUID & MyKaxTagEditionUID = GetChild<KaxTagEditionUID>(MyKaxTagTargets);
*static_cast<EbmlUInteger *>(&MyKaxTagEditionUID) = currentTag.targetEditionUID;
}
if (currentTag.targetChapterUID != 0) {
KaxTagChapterUID & MyKaxTagChapterUID = GetChild<KaxTagChapterUID>(MyKaxTagTargets);
*static_cast<EbmlUInteger *>(&MyKaxTagChapterUID) = currentTag.targetChapterUID;
}
if (currentTag.targetAttachmentUID != 0) {
KaxTagAttachmentUID & MyKaxTagAttachmentUID = GetChild<KaxTagAttachmentUID>(MyKaxTagTargets);
*static_cast<EbmlUInteger *>(&MyKaxTagAttachmentUID) = currentTag.targetAttachmentUID;
}
if(currentTag.targetTypeValue != 0) {
KaxTagTargetTypeValue& MyKaxTagTargetTypeValue = GetChild<KaxTagTargetTypeValue>(MyKaxTagTargets);
*static_cast<EbmlUInteger *>(&MyKaxTagTargetTypeValue) = currentTag.targetTypeValue;
if(!currentTag.targetType.empty())
{
KaxTagTargetType& MyKaxTagTargetType = GetChild<KaxTagTargetType>(MyKaxTagTargets);
*static_cast<EbmlString *>(&MyKaxTagTargetType) = currentTag.targetType;
}
}
// Add the millions of simple tags we can have ;)
KaxTagSimple *MySimpleTag_last = NULL;
for(size_t st = 0; st < currentTag.tags.size(); st++) {
KaxTagSimple *MySimpleTag = NULL;
if (MySimpleTag_last != NULL)
{
MySimpleTag = &GetNextChild<KaxTagSimple>(*MyKaxTag, *MySimpleTag_last);
MySimpleTag_last = MySimpleTag;
}else {
MySimpleTag = &GetChild<KaxTagSimple>(*MyKaxTag);
MySimpleTag_last = MySimpleTag;
}
MatroskaSimpleTag ¤tSimpleTag = currentTag.tags.at(st);
KaxTagName & MyKaxTagName = GetChild<KaxTagName>(*MySimpleTag);
*static_cast<EbmlUnicodeString *>(&MyKaxTagName) = currentSimpleTag.name;
KaxTagString & MyKaxTagString = GetChild<KaxTagString>(*MySimpleTag);
*static_cast<EbmlUnicodeString *>(&MyKaxTagString) = currentSimpleTag.value;
KaxTagLangue& MyKaxTagLangue = GetChild<KaxTagLangue>(*MySimpleTag);
*static_cast<EbmlString *>(&MyKaxTagLangue) = currentSimpleTag.language;
KaxTagDefault& MyKaxTagDefault = GetChild<KaxTagDefault>(*MySimpleTag);
*static_cast<EbmlUInteger *>(&MyKaxTagDefault) = currentSimpleTag.defaultFlag;
}
m_IOCallback.setFilePointer(m_TagPos);
// Now we write the tags to the file
EbmlVoid & Dummy = GetChild<EbmlVoid>(*static_cast<EbmlMaster *>(m_ElementLevel0.get()));
uint64 size_of_tags = m_TagSize;
MyKaxTags.UpdateSize(true);
if (size_of_tags < MyKaxTags.GetSize())
size_of_tags = MyKaxTags.GetSize();
Dummy.SetSize(size_of_tags+8); // Size of the previous tag element
uint64 pos = m_IOCallback.getFilePointer();
if (pos == 0)
//We don't want to overwrite the EBML header :P
return 2;
Dummy.Render(m_IOCallback);
m_IOCallback.setFilePointer(Dummy.GetElementPosition());
pos = m_IOCallback.getFilePointer();
if (pos == 0)
//We don't want to overwrite the EBML header :P
return 2;
MyKaxTags.Render(m_IOCallback);
//l0->UpdateSize(false, true);
std::auto_ptr<KaxSegment> new_segment(new KaxSegment);
KaxSegment * segment = (KaxSegment *)m_ElementLevel0.get();
m_IOCallback.setFilePointer(segment->GetElementPosition());
new_segment->WriteHead(m_IOCallback, segment->HeadSize() - 4);
m_IOCallback.setFilePointer(0, seek_end);
int ret = new_segment->ForceSize(m_IOCallback.getFilePointer() - segment->HeadSize() - segment->GetElementPosition());
if (!ret) {
segment->OverwriteHead(m_IOCallback);
/*("Wrote the element at the end of the file but could "
"not update the segment size. Therefore the element "
"will not be visible. Aborting the process. The file "
"has been changed!")*/
m_IOCallback.setFilePointer(segment->HeadSize() - segment->GetElementPosition());
m_IOCallback.truncate();
return 1;
} else {
new_segment->OverwriteHead(m_IOCallback);
}
}
return 0;
};
static const char* foobar2k_to_matroska_edition_tag(const char * name)
{
if (!stricmp_utf8(name, "ALBUM"))
return "TITLE";
else if (!stricmp_utf8(name, "SUBALBUM"))
return "SUBTITLE";
else if (starts_with(name, "ALBUM ")) {
static char newname[255];
ZeroMemory(newname,255);
strncpy(newname,name+6,254);
name = newname;
}
for (int i = 0; i < tabsize(edition_tag_mapping); i++)
if (!stricmp_utf8(name, edition_tag_mapping[i][FOOBAR2K_TAG_IDX]))
return edition_tag_mapping[i][MATROSKA_TAG_IDX];
return name;
}
static const char* foobar2k_to_matroska_chapter_tag(const char * name)
{
for (int i = 0; i < tabsize(chapter_tag_mapping); i++)
if (!stricmp_utf8(name, chapter_tag_mapping[i][FOOBAR2K_TAG_IDX]))
return chapter_tag_mapping[i][MATROSKA_TAG_IDX];
return name;
}
int meta_get_num(const file_info &info, const char* name, int idx)
{
assert(pfc::is_valid_utf8(name));
int n, m = min(info.meta_get_count(), idx);
int rv = 0;
for(n=0; n<m; n++)
{
if (!stricmp_utf8(name, info.meta_enum_name(n)))
rv++;
}
return rv;
}
bool isEditionTag(const char * name) {
if (starts_with(name, "ALBUM") ||
starts_with(name, "SUBALBUM") ||
starts_with(name, "DISCID") ||
starts_with(name, "CATALOG"))
{
return true;
} else {
return false;
}
}
void MatroskaAudioParser::SetTags(const file_info &info)
{
int i, idx;
const char *name, *value;
if (m_Chapters.size() == 0)
{
// No chapters, works on track
MatroskaTagInfo *trackTag;
trackTag = FindTagWithTrackUID(m_Tracks.at(m_CurrentTrackNo).trackUID);
if (trackTag == NULL) {
// The tag doesn't exist yet
MatroskaTagInfo tempTag;
tempTag.targetTrackUID = m_Tracks.at(m_CurrentTrackNo).trackUID;
m_Tags.push_back(tempTag);
trackTag = &m_Tags.at(m_Tags.size()-1);
}
//if(trackTag->targetTypeValue == 0)
// trackTag->targetTypeValue = 50;
trackTag->targetTypeValue = 30;
trackTag->MarkAllAsRemovalPending();
int metaDataCount = info.meta_get_count();
for (i = 0; i < metaDataCount; i++)
{
for (int j = 0; j != info.meta_enum_value_count(i); ++j) {
name = info.meta_enum_name(i);
value = info.meta_enum_value(i, j);
//idx = meta_get_num(info, name, i);
idx = j;
name = foobar2k_to_matroska_chapter_tag(name);
if ((name != NULL) && (value != NULL)) {
trackTag->SetTagValue(name, value, idx);
}
}
}
// Add the replay_gain tags
replaygain_info rg = info.get_replaygain();
if (rg.is_track_gain_present()) {
char tmp[rg.text_buffer_size];
pfc::float_to_string(tmp, rg.text_buffer_size, rg.m_track_gain, 7);
value = (const char*)tmp;
} else {
value = NULL;
}
if (value)
trackTag->SetTagValue("REPLAYGAIN_GAIN", value);
if (rg.is_track_peak_present()) {
char tmp[rg.text_buffer_size];
pfc::float_to_string(tmp, rg.text_buffer_size, rg.m_track_peak, 7);
value = (const char*)tmp;
} else {
value = NULL;
}
if (value)
trackTag->SetTagValue("REPLAYGAIN_PEAK", value);
trackTag->RemoveMarkedTags();
}
// Set global track tags as album tags
if ((m_Chapters.size() > 0) && (m_CurrentChapter != NULL))
{
MatroskaTagInfo *trackTag;
trackTag = FindTagWithTrackUID(m_Tracks.at(m_CurrentTrackNo).trackUID);
if (trackTag == NULL)
{
MatroskaTagInfo tempTag;
tempTag.targetTrackUID = m_Tracks.at(m_CurrentTrackNo).trackUID;
m_Tags.push_back(tempTag);
trackTag = &m_Tags.at(m_Tags.size()-1);
}
if(trackTag->targetTypeValue == 0)
trackTag->targetTypeValue = 50;
trackTag->MarkAllAsRemovalPending();
int metaDataCount = info.meta_get_count();
for (i = 0; i < metaDataCount; i++)
{
for (int j = 0; j != info.meta_enum_value_count(i); ++j) {
name = info.meta_enum_name(i);
value = info.meta_enum_value(i, j);
//idx = meta_get_num(info, name, i);
idx = j;
if (isEditionTag(name))
{
name = foobar2k_to_matroska_edition_tag(name);
} else {
name = NULL;
}
if ((name != NULL) && (value != NULL)) {
trackTag->SetTagValue(name, value, idx);
}
}
}
replaygain_info rg = info.get_replaygain();
if (rg.is_album_gain_present()) {
char tmp[rg.text_buffer_size];
pfc::float_to_string(tmp, rg.text_buffer_size, rg.m_album_gain, 7);
value = (const char*)tmp;
} else {
value = NULL;
}
if (value)
trackTag->SetTagValue("REPLAYGAIN_GAIN", value);
if (rg.is_album_peak_present()) {
char tmp[rg.text_buffer_size];
pfc::float_to_string(tmp, rg.text_buffer_size, rg.m_album_peak, 7);
value = (const char*)tmp;
} else {
value = NULL;
}
if (value)
trackTag->SetTagValue("REPLAYGAIN_PEAK", value);
trackTag->RemoveMarkedTags();
}
//If there's not only a track, set all the chapter tags
if ((m_Chapters.size() > 0) && (m_CurrentChapter != NULL))
{
// Ok we add the tags to tag with chapter+track UID's
MatroskaTagInfo *chapterTag;
chapterTag = FindTagWithChapterUID(m_CurrentChapter->chapterUID,
m_Tracks.at(m_CurrentTrackNo).trackUID);
if (chapterTag == NULL)
{
MatroskaTagInfo tempTag;
tempTag.targetTrackUID = m_Tracks.at(m_CurrentTrackNo).trackUID;
tempTag.targetChapterUID = m_CurrentChapter->chapterUID;
m_Tags.push_back(tempTag);
chapterTag = &m_Tags.at(m_Tags.size()-1);
}
if(chapterTag->targetTypeValue == 0)
chapterTag->targetTypeValue = 30;
chapterTag->MarkAllAsRemovalPending();
int metaDataCount = info.meta_get_count();
for (i = 0; i < metaDataCount; i++)
{
for (int j = 0; j != info.meta_enum_value_count(i); ++j) {
name = info.meta_enum_name(i);
value = info.meta_enum_value(i, j);
//idx = meta_get_num(info, name, i);
idx = j;
if (isEditionTag(name))
{
name = NULL;
} else {
name = foobar2k_to_matroska_chapter_tag(name);
}
if ((name != NULL) && (value != NULL)) {
chapterTag->SetTagValue(name, value, idx);
}