1 /*  Copyright (c) MediaArea.net SARL. All Rights Reserved.
2  *
3  *  Use of this source code is governed by a BSD-style license that can
4  *  be found in the License.html file in the root of the source tree.
5  */
6 
7 //---------------------------------------------------------------------------
8 // Pre-compilation
9 #include "MediaInfo/PreComp.h"
10 #ifdef __BORLANDC__
11     #pragma hdrstop
12 #endif
13 //---------------------------------------------------------------------------
14 
15 //---------------------------------------------------------------------------
16 #include "MediaInfo/Setup.h"
17 //---------------------------------------------------------------------------
18 
19 //***************************************************************************
20 // Infos (Common)
21 //***************************************************************************
22 
23 //---------------------------------------------------------------------------
24 #if defined(MEDIAINFO_AC3_YES) || defined(MEDIAINFO_DVDV_YES) || defined(MEDIAINFO_MPEGPS_YES) || defined(MEDIAINFO_MPEGTS_YES) || defined(MEDIAINFO_MIXML_YES)
25 //---------------------------------------------------------------------------
26 
27 #include "ZenLib/Conf.h"
28 using namespace ZenLib;
29 
30 namespace MediaInfoLib
31 {
32 
33 //---------------------------------------------------------------------------
34 extern const float64 Mpegv_frame_rate[16];
35 
36 //---------------------------------------------------------------------------
37 extern const int32u AC3_SamplingRate[]=
38 { 48000,  44100,  32000,      0,};
39 
40 //---------------------------------------------------------------------------
41 const char*  AC3_Mode[] =
42 {
43     "CM",
44     "ME",
45     "VI",
46     "HI",
47     "D",
48     "C",
49     "E",
50     "VO",
51 };
52 
53 //---------------------------------------------------------------------------
54 const char*  AC3_Mode_String[] =
55 {
56     "Complete Main",
57     "Music and Effects",
58     "Visually Impaired",
59     "Hearing Impaired",
60     "Dialogue",
61     "Commentary",
62     "Emergency",
63     "Voice Over",
64 };
65 
66 //---------------------------------------------------------------------------
67 const char*  AC3_Surround[]=
68 {
69     "",
70     "Not Dolby Surround encoded",
71     "Dolby Surround encoded",
72     "",
73 };
74 
75 //---------------------------------------------------------------------------
76 extern const int16u AC3_BitRate[]=
77 {
78 
79      32,
80      40,
81      48,
82      56,
83      64,
84      80,
85      96,
86     112,
87     128,
88     160,
89     192,
90     224,
91     256,
92     320,
93     384,
94     448,
95     512,
96     576,
97     640,
98 };
99 
100 //---------------------------------------------------------------------------
101 extern const int8u AC3_Channels[]=
102 {2, 1, 2, 3, 3, 4, 4, 5};
103 
104 //---------------------------------------------------------------------------
105 } //NameSpace
106 
107 //---------------------------------------------------------------------------
108 #endif //...
109 //---------------------------------------------------------------------------
110 
111 //***************************************************************************
112 //
113 //***************************************************************************
114 
115 //---------------------------------------------------------------------------
116 #if defined(MEDIAINFO_AC3_YES)
117 //---------------------------------------------------------------------------
118 
119 //---------------------------------------------------------------------------
120 #include "MediaInfo/Audio/File_Ac3.h"
121 #include <vector>
122 #include <cmath>
123 #if MEDIAINFO_EVENTS
124     #include "MediaInfo/MediaInfo_Config_MediaInfo.h"
125     #include "MediaInfo/MediaInfo_Events_Internal.h"
126 #endif //MEDIAINFO_EVENTS
127 #include "MediaInfo/MediaInfo_Internal.h"
128 using namespace ZenLib;
129 using namespace std;
130 //---------------------------------------------------------------------------
131 
132 namespace MediaInfoLib
133 {
134 
135 //***************************************************************************
136 // Infos
137 //***************************************************************************
138 
139 //---------------------------------------------------------------------------
140 const int32u AC3_SamplingRate2[]=
141 { 24000,  22050,  16000,      0,};
142 
143 //---------------------------------------------------------------------------
144 const char*  AC3_ChannelPositions[]=
145 {
146     "Dual mono",
147     "Front: C",
148     "Front: L R",
149     "Front: L C R",
150     "Front: L R,   Back: C",
151     "Front: L C R, Back: C",
152     "Front: L R,   Side: L R",
153     "Front: L C R, Side: L R",
154 };
155 
156 //---------------------------------------------------------------------------
157 const char*  AC3_ChannelPositions2[]=
158 {
159     "1+1",
160     "1/0/0",
161     "2/0/0",
162     "3/0/0",
163     "2/1/0",
164     "3/1/0",
165     "2/2/0",
166     "3/2/0",
167 };
168 
169 //---------------------------------------------------------------------------
170 const char*  AC3_ChannelLayout_lfeoff[]=
171 {
172     "M M",
173     "C",
174     "L R",
175     "L R C",
176     "L R S",
177     "L R C Cs",
178     "L R Ls Rs",
179     "L R C Ls Rs",
180 };
181 
182 //---------------------------------------------------------------------------
183 const char*  AC3_ChannelLayout_lfeon[]=
184 {
185     "1+1 LFE",
186     "C LFE",
187     "L R LFE",
188     "L R C LFE",
189     "L R S LFE",
190     "L R C LFE Cs",
191     "L R LFE Ls Rs",
192     "L R C LFE Ls Rs",
193 };
194 
195 //---------------------------------------------------------------------------
196 int16u AC3_acmod2chanmap[]=
197 {
198     0xA000,
199     0x4000,
200     0xA000,
201     0xE000,
202     0xA100,
203     0xE100,
204     0xB800,
205     0xF800,
206 };
207 
208 //---------------------------------------------------------------------------
AC3_chanmap_ChannelPositions(int16u chanmap)209 Ztring AC3_chanmap_ChannelPositions (int16u chanmap)
210 {
211     Ztring Front;
212     Ztring Side;
213     Ztring Back;
214     Ztring More;
215 
216     for (int8u Pos=0; Pos<16; Pos++)
217     {
218         if (chanmap&(1<<(15-Pos)))
219         {
220             switch (Pos)
221             {
222                 case  0 :   Front+=__T(" L"); break;
223                 case  1 :   Front+=__T(" C"); break;
224                 case  2 :   Front+=__T(" R"); break;
225                 case  3 :   Side+=__T(" L"); break;
226                 case  4 :   Side+=__T(" R"); break;
227                 case  5 :   {
228                             bool HasR=false;
229                             if (Front.find(__T(" R"))!=string::npos)
230                             {
231                                 Front.resize(Front.size()-2);
232                                 HasR=true;
233                             }
234                             Front+=__T(" C C");
235                             if (HasR)
236                                 Front+=__T(" R");
237                             }
238                             break;
239                 case  6 :   Back+=__T(" L R"); break;
240                 case  7 :   if (Back.empty())
241                                 Back=__T(" C");
242                             else
243                                 Back=__T(" L C R");
244                             break;
245                 case 15 :   More+=__T(", LFE");
246                             break;
247                 default: ;
248             }
249         }
250     }
251 
252     Ztring ToReturn;
253     if (!Front.empty())
254     {
255         ToReturn+=__T("Front:")+Front;
256     }
257     if (!Side.empty())
258     {
259         if (!ToReturn.empty())
260             ToReturn+=__T(", ");
261         ToReturn+=__T("Side:")+Side;
262     }
263     if (!Back.empty())
264     {
265         if (!ToReturn.empty())
266             ToReturn+=__T(", ");
267         ToReturn+=__T("Back:")+Back;
268     }
269     ToReturn+=More;
270 
271     return ToReturn;
272 }
273 
274 //---------------------------------------------------------------------------
AC3_chanmap_Channels(int16u chanmap)275 int8u AC3_chanmap_Channels (int16u chanmap)
276 {
277     int8u Channels=0;
278 
279     for (int8u Pos=0; Pos<16; Pos++)
280     {
281         if (chanmap&(1<<(15-Pos)))
282         {
283             switch (Pos)
284             {
285                 case  5 :
286                 case  6 :
287                 case  9 :
288                 case 10 :
289                 case 11 :
290                 case 13 :
291                             Channels+=2; break;
292                 default:
293                             Channels++; break;
294             }
295         }
296     }
297 
298     return Channels;
299 }
300 
301 //---------------------------------------------------------------------------
302 static const char* AC3_chanmap_ChannelLayout_List[16] =
303 {
304     "L",
305     "C",
306     "R",
307     "Ls",
308     "Rs",
309     "Lc Rc",
310     "Lrs Rrs",
311     "Cs",
312     "Ts",
313     "Lsd Rsd",
314     "Lw Rw",
315     "Lvh Rvh",
316     "Vhc", // Cvh is a typo in specs
317     "Lts Rts",
318     "LFE2",
319     "LFE",
320 };
AC3_chanmap_ChannelLayout(int16u chanmap,const Ztring & ChannelLayout0)321 Ztring AC3_chanmap_ChannelLayout (int16u chanmap, const Ztring &ChannelLayout0)
322 {
323     Ztring ToReturn=ChannelLayout0;
324 
325     for (int8u Pos=5; Pos<15; Pos++) // Custom ones only
326     {
327         if (chanmap&(1<<(15-Pos)))
328         {
329             if (!ChannelLayout0.empty())
330                 ToReturn+=__T(' ');
331             ToReturn+=Ztring().From_UTF8(AC3_chanmap_ChannelLayout_List[Pos]);
332         }
333     }
334 
335     return ToReturn;
336 }
337 
338 //---------------------------------------------------------------------------
339 static const char* AC3_nonstd_bed_channel_assignment_mask_ChannelLayout_List[17] =
340 {
341     "L",
342     "R",
343     "C",
344     "LFE",
345     "Ls",
346     "Rs",
347     "Lrs",
348     "Rrs",
349     "Lvh", // Lfh in spec but same as Lvh from E-AC-3
350     "Rvh", // Rfh in spec but same as Rvh from E-AC-3
351     "Lts", // Ltm in spec but same as Lts from E-AC-3
352     "Rts", // Rtm in spec but same as Rts from E-AC-3
353     "Lrh",
354     "Rrh",
355     "Lw",
356     "Rw",
357     "LFE2",
358 };
359 static int8s AC3_nonstd_bed_channel_assignment_mask_ChannelLayout_Reordering[17] =
360 {
361     0,
362     0,
363     0,
364     0,
365     0,
366     0,
367     0,
368     0,
369     6, // Wide channels before top layer
370     6, // Wide channels before top layer
371     -2,
372     -2,
373     -2,
374     -2,
375     -2,
376     -2,
377     0,
378 };
AC3_nonstd_bed_channel_assignment_mask_ChannelLayout(int32u nonstd_bed_channel_assignment_mask)379 Ztring AC3_nonstd_bed_channel_assignment_mask_ChannelLayout(int32u nonstd_bed_channel_assignment_mask)
380 {
381     Ztring ToReturn;
382 
383     for (int8u i=0; i<17; i++)
384     {
385         int8u i2=i+AC3_nonstd_bed_channel_assignment_mask_ChannelLayout_Reordering[i];
386         if (nonstd_bed_channel_assignment_mask&(1<<i2))
387         {
388             ToReturn+=Ztring().From_UTF8(AC3_nonstd_bed_channel_assignment_mask_ChannelLayout_List[i2]);
389             ToReturn+=__T(' ');
390         }
391     }
392 
393     if (!ToReturn.empty())
394         ToReturn.resize(ToReturn.size()-1);
395 
396     return ToReturn;
397 }
398 //---------------------------------------------------------------------------
399 static const int8u AC3_bed_channel_assignment_mask_ChannelLayout_Mapping[10] =
400 {
401     2,
402     1,
403     1,
404     2,
405     2,
406     2,
407     2,
408     2,
409     2,
410     1,
411 };
AC3_bed_channel_assignment_mask_2_nonstd(int16u bed_channel_assignment_mask)412 extern int32u AC3_bed_channel_assignment_mask_2_nonstd(int16u bed_channel_assignment_mask)
413 {
414     int32u ToReturn=0;
415 
416     int8u j=0;
417     for (int8u i=0; i<10; i++)
418     {
419         if (bed_channel_assignment_mask&(1<<i))
420         {
421             ToReturn|=(1<<(j++));
422             if (AC3_bed_channel_assignment_mask_ChannelLayout_Mapping[i]>1)
423                 ToReturn|=(1<<(j++));
424         }
425         else
426             j+=AC3_bed_channel_assignment_mask_ChannelLayout_Mapping[i];
427     }
428 
429     return ToReturn;
430 }
431 
432 
433 //---------------------------------------------------------------------------
434 const int16u AC3_FrameSize[27][4]=
435 {
436     { 128,  138,  192,    0},
437     { 160,  174,  240,    0},
438     { 192,  208,  288,    0},
439     { 224,  242,  336,    0},
440     { 256,  278,  384,    0},
441     { 320,  348,  480,    0},
442     { 384,  416,  576,    0},
443     { 448,  486,  672,    0},
444     { 512,  556,  768,    0},
445     { 640,  696,  960,    0},
446     { 768,  834, 1152,    0},
447     { 896,  974, 1344,    0},
448     {1024, 1114, 1536,    0},
449     {1280, 1392, 1920,    0},
450     {1536, 1670, 2304,    0},
451     {1792, 1950, 2688,    0},
452     {2048, 2228, 3072,    0},
453     {2304, 2506, 3456,    0},
454     {2560, 2786, 3840,    0},
455     {   0,    0,    0,    0},
456     {   0,    0,    0,    0},
457     {   0,    0,    0,    0},
458     {   0,    0,    0,    0},
459     {   0,    0,    0,    0},
460     {   0,    0,    0,    0},
461     {   0,    0,    0,    0},
462     { 768,    0,    0,    0},
463 };
464 
465 //---------------------------------------------------------------------------
AC3_FrameSize_Get(int8u frmsizecod,int8u fscod)466 int16u AC3_FrameSize_Get(int8u frmsizecod, int8u fscod)
467 {
468     bool Padding=(frmsizecod%2)?true:false;
469     int16u frame_size_id=frmsizecod/2;
470 
471     if (frame_size_id>26 || fscod>3)
472         return 0;
473 
474     int16u FrameSize=AC3_FrameSize[frame_size_id][fscod];
475     if (fscod==1 && Padding)
476         FrameSize+=2; // frame lengths are padded by 1 word (16 bits) at 44100 Hz
477     return FrameSize;
478 }
479 
480 //---------------------------------------------------------------------------
481 // CRC_16_Table
482 // A CRC is computed like this:
483 // Init: int32u CRC_16 = 0x0000;
484 // for each data byte do
485 //     CRC_16=(CRC_16<<8) ^ CRC_16_Table[(CRC_16>>8)^(data_byte)];
486 extern const int16u CRC_16_Table[256] =
487 {
488     0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
489     0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
490     0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
491     0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
492     0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
493     0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
494     0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
495     0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
496     0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
497     0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
498     0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
499     0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
500     0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
501     0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
502     0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
503     0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
504     0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
505     0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
506     0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
507     0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
508     0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
509     0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
510     0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
511     0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
512     0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
513     0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
514     0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
515     0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
516     0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
517     0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
518     0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
519     0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
520 };
521 
CRC16_Init(int16u * Table,int16u Polynomial)522 int CRC16_Init(int16u *Table, int16u Polynomial)
523 {
524     for (size_t Pos=0; Pos<256; Pos++)
525     {
526         Table[Pos]=(int16u)Pos<<8;
527 
528         for(int8u bit=0; bit<8; bit++)
529         {
530             if (Table[Pos]&0x8000)
531                 Table[Pos]=(Table[Pos]<<1)^Polynomial;
532             else
533                 Table[Pos]=Table[Pos]<<1;
534         }
535     }
536     return 0;
537 }
538 
539 //---------------------------------------------------------------------------
540 const float64 AC3_dynrng[]=
541 {
542       6.02,
543      12.04,
544      18.06,
545      24.08,
546     -18.06,
547     -12.04,
548     - 6.02,
549       0.00,
550 };
551 
552 //---------------------------------------------------------------------------
553 const float64 AC3_compr[]=
554 {
555       6.02,
556      12.04,
557      18.06,
558      24.08,
559      30.10,
560      36.12,
561      42.14,
562      48.16,
563     -42.14,
564     -36.12,
565     -30.10,
566     -24.08,
567     -18.06,
568     -12.04,
569     - 6.02,
570       0.00,
571 };
572 
573 //---------------------------------------------------------------------------
AC3_HD_StreamType(int8u StreamType)574 const char* AC3_HD_StreamType(int8u StreamType)
575 {
576     switch (StreamType)
577     {
578         case 0xBA : return "TrueHD";
579         case 0xBB : return "MLP";
580         default   : return "";
581     }
582 }
583 
584 //---------------------------------------------------------------------------
AC3_HD_SamplingRate(int8u SamplingRate)585 int32u AC3_HD_SamplingRate(int8u SamplingRate)
586 {
587     if (SamplingRate==0xF)
588         return 0;
589 
590     return ((SamplingRate&8)?44100:48000)<<(SamplingRate&7) ;
591 }
592 
593 //---------------------------------------------------------------------------
594 static const int8u AC3_TrueHD_ChannelCountPerBit[13]=
595 {
596     2, //LR
597     1, //C
598     1, //LFE
599     2, //LRs
600     2, //LRvh
601     2, //LRc
602     2, //LRrs
603     1, //Cs
604     1, //Ts
605     2, //LRsd
606     2, //LRw
607     1, //Cvh
608     1, //LFE2
609 };
610 
611 //---------------------------------------------------------------------------
AC3_TrueHD_Channels(int16u ChannelsMap)612 int8u AC3_TrueHD_Channels(int16u ChannelsMap)
613 {
614     int8u Channels=0;
615 
616     for (int8u Pos=0; Pos<13; Pos++)
617         Channels+=AC3_TrueHD_ChannelCountPerBit[Pos]*((ChannelsMap>>Pos)&0x1);
618 
619     return Channels;
620 }
621 
622 //---------------------------------------------------------------------------
AC3_TrueHD_Channels_Positions(int16u ChannelsMap,bool Bit11=false)623 std::string AC3_TrueHD_Channels_Positions(int16u ChannelsMap, bool Bit11=false)
624 {
625     std::string Text;
626     if ((ChannelsMap&0x0003)==0x0003)
627         Text+="Front: L C R";
628     else
629     {
630         if (ChannelsMap&0x0001)
631             Text+="Front: C";
632         if (ChannelsMap&0x0002)
633             Text+="Front: L, R";
634     }
635 
636     if (ChannelsMap&0x08)
637         Text+=", Side: L R";
638 
639     if (ChannelsMap&0x80)
640         Text+=", Back: C";
641 
642     if ((ChannelsMap&0x0810)==0x0810 && Bit11)
643         Text+=", vh: L C R";
644     else
645     {
646         if (ChannelsMap&0x0010 && !Bit11)
647             Text+=", vh: L R";
648         if (ChannelsMap&0x0800)
649             Text+=", vh: C";
650     }
651 
652     if (ChannelsMap&0x0020)
653         Text+=", c: L R";
654     if (ChannelsMap&0x0040)
655         Text+=", Back: L R";
656     if (ChannelsMap&0x0100)
657         Text+=", s: T";
658     if (ChannelsMap&0x0200)
659         Text+=", sd: L R";
660     if (ChannelsMap&0x0400)
661         Text+=", w: L R";
662 
663     if (ChannelsMap&0x0004)
664         Text+=", LFE";
665     if (ChannelsMap&0x1000)
666         Text+=", LFE2";
667 
668     return Text;
669 }
670 
671 //---------------------------------------------------------------------------
AC3_TrueHD_Channels_Positions2(int16u ChannelsMap,bool Bit11=false)672 Ztring AC3_TrueHD_Channels_Positions2(int16u ChannelsMap, bool Bit11=false)
673 {
674     int8u Front=0, Surround=0, Rear=0, LFE=0;
675 
676     if (ChannelsMap&0x0001)
677         Front++;
678     if (ChannelsMap&0x0002)
679         Front+=2;
680 
681     if (ChannelsMap&0x08)
682         Surround+=2;
683     if (ChannelsMap&0x80)
684         Surround++;
685 
686     if (ChannelsMap & 0x0010)
687         Rear+=2; //vh
688     if (!Bit11)
689     {
690     if (ChannelsMap&0x0800)
691         Rear++;  //vh
692 
693 
694     if (ChannelsMap&0x0020)
695         Rear+=2; //c
696     if (ChannelsMap&0x0040)
697         Rear+=2; //rs
698     if (ChannelsMap&0x0100)
699         Rear+=2; //s
700     if (ChannelsMap&0x0200)
701         Rear+=2; //sd
702     if (ChannelsMap&0x0400)
703         Rear+=2; //w
704 
705     if (ChannelsMap&0x0004)
706         LFE++;
707     if (ChannelsMap&0x1000)
708         LFE++;
709     }
710 
711     Ztring Text;
712     Text+=Ztring::ToZtring(Front);
713     Text+=__T('/')+Ztring::ToZtring(Surround);
714     Text+=__T('/')+Ztring::ToZtring(Rear);
715     Text+=__T('.')+Ztring::ToZtring(LFE);
716     return Text;
717 }
718 
719 //---------------------------------------------------------------------------
720 static const size_t AC3_TrueHD_ChannelLayoutNames_Size=13;
721 const char* AC3_TrueHD_ChannelLayoutNames[AC3_TrueHD_ChannelLayoutNames_Size]=
722 {
723     "L R",
724     "C",
725     "LFE",
726     "Ls Rs",
727     "Tfl Tfr",
728     "Lsc Rsc",
729     "Lb Rb",
730     "Cb",
731     "Tc",
732     "Lsd Rsd",
733     "Lw Rw",
734     "Tfc",
735     "LFE2",
736 };
737 static const size_t AC3_TrueHD_ChannelLayoutNames2_Size=1;
738 const char* AC3_TrueHD_ChannelLayoutNames2[AC3_TrueHD_ChannelLayoutNames2_Size]=
739 {
740     "Tsl Tsr",
741 };
AC3_TrueHD_Channels_ChannelLayout(int16u ChannelsMap,bool Bit11=false)742 std::string AC3_TrueHD_Channels_ChannelLayout(int16u ChannelsMap, bool Bit11=false)
743 {
744     std::string Text;
745 
746     for (size_t i=0; i<16; i++)
747         if (ChannelsMap&(1<<i))
748         {
749             if (!Text.empty())
750                 Text+=' ';
751 
752             if ((!Bit11 && i>=AC3_TrueHD_ChannelLayoutNames_Size) || (Bit11 && i>=4 && i-4>=AC3_TrueHD_ChannelLayoutNames2_Size))
753             {
754                 Text+='+'; //Unknown layout
755                 return Text;
756             }
757 
758             Text+=(Bit11 && i>=4)?AC3_TrueHD_ChannelLayoutNames2[i-4]:AC3_TrueHD_ChannelLayoutNames[i];
759         }
760 
761     return Text;
762 }
763 
764 //---------------------------------------------------------------------------
765 static const int32u AC3_MLP_Channels[32]=
766 {
767     1,
768     2,
769     3,
770     4,
771     3,
772     4,
773     5,
774     3,
775     4,
776     5,
777     4,
778     5,
779     6,
780     4,
781     5,
782     4,
783     5,
784     6,
785     5,
786     5,
787     6,
788     0,
789     0,
790     0,
791     0,
792     0,
793     0,
794     0,
795     0,
796     0,
797     0,
798     0,
799 };
800 
801 //---------------------------------------------------------------------------
802 static const int32u AC3_MLP_Resolution[16]=
803 {
804     16,
805     20,
806     24,
807     0,
808     0,
809     0,
810     0,
811     0,
812     0,
813     0,
814     0,
815     0,
816     0,
817     0,
818     0,
819     0,
820 };
821 
822 //---------------------------------------------------------------------------
823 extern const char* Ac3_emdf_payload_id[16]=
824 {
825     "Container End",
826     "Programme loudness data",
827     "Programme information",
828     "E-AC-3 substream structure",
829     "Dynamic range compression data for portable devices",
830     "Programme Language",
831     "External Data",
832     "Headphone rendering data",
833     "",
834     "",
835     "",
836     "OAMD",
837     "",
838     "Personalized Audio Mix-Graph",
839     "JOC",
840     "",
841 };
842 
843 //---------------------------------------------------------------------------
Ac3_variable_bits(BitStream_Fast & Search2,int8u Bits)844 int32u Ac3_variable_bits(BitStream_Fast &Search2, int8u Bits)
845 {
846     int32u ToReturn = 0;
847 
848     do
849     {
850         ToReturn += Search2.Get4(Bits);
851     }
852     while (Search2.GetB());
853 
854     return ToReturn;
855 }
856 
857 //---------------------------------------------------------------------------
Ac3_EMDF_Test(const BitStream_Fast & Search)858 bool Ac3_EMDF_Test(const BitStream_Fast &Search)
859 {
860     BitStream_Fast Search2(Search);
861     Search2.Skip(16); //syncword
862     size_t Size=((size_t)Search2.Get2(16))*8+17; //emdf_container_length
863     if (Size>Search2.Remain())
864         return false;
865     size_t End=Search2.Remain()-Size;
866     if (Search2.Get1(2)) //emdf_version
867         return false;
868     if (Search2.Get1(3) == 0x7) //key_id
869         Ac3_variable_bits(Search2, 3);
870     for (;;)
871     {
872         int8u emdf_payload_id=Search2.Get1(5);
873         if (!emdf_payload_id)
874             break;
875         if (emdf_payload_id == 0x1F)
876             Ac3_variable_bits(Search2, 5);
877         bool smploffste=Search2.GetB();
878         if (smploffste)
879             Search2.Skip(12);
880         if (Search2.GetB()) //duratione
881             Ac3_variable_bits(Search2, 11); //duration
882         if (Search2.GetB()) //groupide
883             Ac3_variable_bits(Search2, 2); //groupid
884         if (Search2.GetB()) //codecdatae
885             return false; //must be 0
886         if (!Search2.GetB()) //discard_unknown_payload
887         {
888             bool payload_frame_aligned=false;
889             if (!smploffste)
890             {
891                 payload_frame_aligned=Search2.GetB();
892                 if (payload_frame_aligned)
893                     Search2.Skip(2);
894             }
895             if (smploffste || payload_frame_aligned)
896                 Search2.Skip(7);
897         }
898         size_t emdf_payload_size=((size_t)Ac3_variable_bits(Search2, 8))*8;
899         Search2.Skip(emdf_payload_size);
900     }
901     int8u protection_length_primary=Search2.Get1(2);
902     switch (protection_length_primary)
903     {
904         case 0: return false;
905         case 1: protection_length_primary=8; break;
906         case 2: protection_length_primary=32; break;
907         case 3: protection_length_primary=128; break;
908         default: ;
909     }
910     int8u protection_bits_secondary=Search2.Get1(2);
911     switch (protection_bits_secondary)
912     {
913         case 0: protection_bits_secondary=0; break;
914         case 1: protection_bits_secondary=8; break;
915         case 2: protection_bits_secondary=32; break;
916         case 3: protection_bits_secondary=128; break;
917         default: ;
918     }
919     Search2.Skip(protection_length_primary);
920     Search2.Skip(protection_bits_secondary);
921     return Search2.Remain()>=17?true:false;
922 }
923 
924 //---------------------------------------------------------------------------
925 /*
926 static const int8u ecplsubbndtab[]=
927 {
928     13,
929     19,
930     25,
931     31,
932     37,
933     49,
934     61,
935     73,
936     85,
937     97,
938     109,
939     121,
940     133,
941     145,
942     157,
943     169,
944     181,
945     193,
946     205,
947     217,
948     229,
949     241,
950     253,
951 };
952 */
953 
954 //***************************************************************************
955 // Constructor/Destructor
956 //***************************************************************************
957 
958 //---------------------------------------------------------------------------
File_Ac3()959 File_Ac3::File_Ac3()
960 :File__Analyze()
961 {
962     //Configuration
963     #if MEDIAINFO_EVENTS
964         ParserIDs[0]=MediaInfo_Parser_Ac3;
965         StreamIDs_Width[0]=0;
966     #endif //MEDIAINFO_EVENTS
967     #if MEDIAINFO_TRACE
968         Trace_Layers_Update(8); //Stream
969     #endif //MEDIAINFO_TRACE
970     MustSynchronize=true;
971     Buffer_TotalBytes_FirstSynched_Max=32*1024;
972     Buffer_TotalBytes_Fill_Max=1024*1024;
973     PTS_DTS_Needed=true;
974     StreamSource=IsStream;
975     Frame_Count_NotParsedIncluded=0;
976 
977     //In
978     Frame_Count_Valid=0;
979     MustParse_dac3=false;
980     MustParse_dec3=false;
981     MustParse_dmlp=false;
982     CalculateDelay=false;
983 
984     //Buffer
985     Save_Buffer=NULL;
986 
987     //Temp
988     Frame_Count_HD=0;
989     addbsi_Buffer=NULL;
990     addbsi_Buffer_Size=0;
991     fscod=0;
992     fscod2=0;
993     frmsizecod=0;
994     bsid_Max=(int8u)-1;
995     Formats[0]=0;
996     Formats[1]=0;
997     for (int8u Pos=0; Pos<8; Pos++)
998         for (int8u Pos2=0; Pos2<9; Pos2++)
999         {
1000             frmsizplus1_Max[Pos][Pos2]=0;
1001             acmod_Max[Pos][Pos2]=(int8u)-1;
1002             lfeon_Max[Pos][Pos2]=false;
1003             bsmod_Max[Pos][Pos2]=0;
1004             dsurmod_Max[Pos][Pos2]=0;
1005             chanmape_Max[Pos][Pos2]=false;
1006             chanmap_Max[Pos][Pos2]=0;
1007         }
1008     numblkscod=0;
1009     dsurexmod=0;
1010     dheadphonmod=0;
1011     substreamid_Independant_Current=0;
1012     substreams_Count=0;
1013     joc_complexity_index_Container=(int8u)-1;
1014     joc_complexity_index_Stream=(int8u)-1;
1015     num_dynamic_objects=(int8u)-1;
1016     nonstd_bed_channel_assignment_mask=(int32u)-1;
1017     dxc3_Parsed=false;
1018     HD_MajorSync_Parsed=false;
1019     Core_IsPresent=false;
1020     HD_IsPresent=false;
1021     HD_HasAtmos=false;
1022     dynrnge_Exists=false;
1023     TimeStamp_IsPresent=false;
1024     TimeStamp_IsParsing=false;
1025     TimeStamp_Parsed=false;
1026     TimeStamp_Count=0;
1027     BigEndian=true;
1028     IgnoreCrc_Done=false;
1029 }
1030 
1031 //---------------------------------------------------------------------------
~File_Ac3()1032 File_Ac3::~File_Ac3()
1033 {
1034     delete[] addbsi_Buffer;
1035 }
1036 
1037 //***************************************************************************
1038 // Streams management
1039 //***************************************************************************
1040 
1041 //---------------------------------------------------------------------------
Streams_Fill()1042 void File_Ac3::Streams_Fill()
1043 {
1044     if (dxc3_Parsed)
1045     {
1046         if (Count_Get(Stream_Audio)==0)
1047             Stream_Prepare(Stream_Audio);
1048     }
1049 
1050     if (HD_MajorSync_Parsed)
1051     {
1052         if (Count_Get(Stream_Audio)==0)
1053             Stream_Prepare(Stream_Audio);
1054         if (HD_BitRate_Max)
1055             Fill(Stream_Audio, 0, Audio_BitRate_Maximum, (HD_BitRate_Max*AC3_HD_SamplingRate(HD_SamplingRate2)+8)>>4);
1056 
1057         if (HD_StreamType==0xBA) //TrueHD
1058         {
1059             {
1060                 Fill(Stream_Audio, 0, Audio_Format, "MLP FBA");
1061                 Fill(Stream_Audio, 0, Audio_Codec, "MLP FBA");
1062             }
1063             if (HD_HasAtmos)
1064             {
1065                 Fill(Stream_Audio, 0, Audio_Format_Profile, "MLP FBA 16-ch / MLP FBA");
1066                 Fill(Stream_Audio, 0, Audio_Codec_Profile, "MLP FBA 16-ch / MLP FBA");
1067             }
1068             Fill(Stream_Audio, 0, Audio_BitRate_Mode, "VBR");
1069             Fill(Stream_Audio, 0, Audio_Compression_Mode, "Lossless");
1070             Ztring Sampling;
1071             Sampling.From_Number(AC3_HD_SamplingRate(HD_SamplingRate1));
1072             Fill(Stream_Audio, 0, Audio_SamplingRate, Sampling);
1073             Fill(Stream_Audio, 0, Audio_Channel_s_, AC3_TrueHD_Channels(HD_Channels2));
1074             Fill(Stream_Audio, 0, Audio_ChannelPositions, AC3_TrueHD_Channels_Positions(HD_Channels2, HD_flags&(1<<11)));
1075             Fill(Stream_Audio, 0, Audio_ChannelPositions_String2, AC3_TrueHD_Channels_Positions2(HD_Channels2, HD_flags&(1<<11)));
1076             Fill(Stream_Audio, 0, Audio_ChannelLayout, AC3_TrueHD_Channels_ChannelLayout(HD_Channels2, HD_flags&(1<<11)));
1077         }
1078 
1079         if (HD_StreamType==0xBB) //TrueHD
1080         {
1081             {
1082                 Fill(Stream_Audio, 0, Audio_Format, "MLP");
1083                 Fill(Stream_Audio, 0, Audio_Codec,  "MLP");
1084             }
1085             Fill(Stream_Audio, 0, Audio_BitRate_Mode, "VBR");
1086             Fill(Stream_Audio, 0, Audio_Compression_Mode, "Lossless");
1087             Fill(Stream_Audio, 0, Audio_SamplingRate, AC3_HD_SamplingRate(HD_SamplingRate2));
1088             if (HD_SamplingRate1!=HD_SamplingRate2)
1089                 Fill(Stream_Audio, 0, Audio_SamplingRate, AC3_HD_SamplingRate(HD_SamplingRate2));
1090             Fill(Stream_Audio, 0, Audio_Channel_s_, AC3_MLP_Channels[HD_Channels1]);
1091             if (MediaInfoLib::Config.LegacyStreamDisplay_Get() && HD_Channels1!=HD_Channels2)
1092                 Fill(Stream_Audio, 0, Audio_Channel_s_, AC3_MLP_Channels[HD_Channels1]);
1093             Fill(Stream_Audio, 0, Audio_BitDepth, AC3_MLP_Resolution[HD_Resolution2]);
1094             if (MediaInfoLib::Config.LegacyStreamDisplay_Get() && HD_Resolution1!=HD_Resolution2)
1095                 Fill(Stream_Audio, 0, Audio_BitDepth, AC3_MLP_Resolution[HD_Resolution1]);
1096         }
1097     }
1098 
1099     bool HasJOC = joc_num_objects_map.size()==1 && (joc_num_objects_map.begin()->second >= Frame_Count_Valid / 8 || joc_num_objects_map.begin()->second >= Frame_Count / 8); //Accepting that some frames do not contain JOC
1100     if (HasJOC || HD_HasAtmos)
1101     {
1102         if (Count_Get(Stream_Audio)==0)
1103             Stream_Prepare(Stream_Audio);
1104         if (HasJOC)
1105         {
1106             Fill(Stream_Audio, 0, Audio_Format_Profile, bsid_Max<=0x09?"AC-3 JOC":"E-AC-3 JOC");
1107             Fill(Stream_Audio, 0, Audio_Codec_Profile, bsid_Max<=0x09?"AC-3 JOC":"E-AC-3 JOC");
1108         }
1109         if (dxc3_Parsed && joc_complexity_index_Container!=(int8u)-1)
1110             Fill(Stream_Audio, 0, "ComplexityIndex", joc_complexity_index_Container);
1111         if (dxc3_Parsed && joc_complexity_index_Container==(int8u)-1 && joc_complexity_index_Stream!=(int8u)-1)
1112             Fill(Stream_Audio, 0, "ComplexityIndex", "Not present");
1113         if (joc_complexity_index_Stream!=(int8u)-1 && joc_complexity_index_Stream!=joc_complexity_index_Container)
1114             Fill(Stream_Audio, 0, "ComplexityIndex", joc_complexity_index_Stream);
1115         if (dxc3_Parsed && joc_complexity_index_Container!=(int8u)-1 && joc_complexity_index_Stream==(int8u)-1)
1116             Fill(Stream_Audio, 0, "ComplexityIndex", "Not present");
1117         if (num_dynamic_objects!=(int8u)-1)
1118             Fill(Stream_Audio, 0, "NumberOfDynamicObjects", num_dynamic_objects);
1119         if (nonstd_bed_channel_assignment_mask !=(int32u)-1)
1120         {
1121             Ztring BedChannelConfiguration=AC3_nonstd_bed_channel_assignment_mask_ChannelLayout(nonstd_bed_channel_assignment_mask);
1122             size_t BedChannelCount=0;
1123             if (!BedChannelConfiguration.empty())
1124                 for (size_t i=0; i<BedChannelConfiguration.size();)
1125                 {
1126                     BedChannelCount++;
1127                     i=BedChannelConfiguration.find(__T(' '), i+1);
1128                 }
1129             Fill(Stream_Audio, 0, "BedChannelCount", BedChannelCount);
1130             Fill_SetOptions(Stream_Audio, 0, "BedChannelCount", "N NIY");
1131             Fill(Stream_Audio, 0, "BedChannelCount/String", MediaInfoLib::Config.Language_Get(Ztring::ToZtring(BedChannelCount), __T(" channel")));
1132             Fill_SetOptions(Stream_Audio, 0, "BedChannelCount/String", "Y NIN");
1133             Fill(Stream_Audio, 0, "BedChannelConfiguration", BedChannelConfiguration);
1134         }
1135     }
1136 
1137     //Surround
1138     if (dsurmod_Max[0][0]==2)
1139     {
1140         Fill(Stream_Audio, 0, Audio_Format_Settings, "Dolby Surround");
1141         Fill(Stream_Audio, 0, Audio_Format_Settings_Mode, "Dolby Surround");
1142     }
1143     if (dsurexmod==2)
1144     {
1145         Fill(Stream_Audio, 0, Audio_Format_Settings, "Dolby Surround EX");
1146         Fill(Stream_Audio, 0, Audio_Format_Settings_Mode, "Dolby Surround EX");
1147     }
1148     if (dsurexmod==3)
1149     {
1150         Fill(Stream_Audio, 0, Audio_Format_Settings, "Dolby Pro Logic IIz");
1151         Fill(Stream_Audio, 0, Audio_Format_Settings_Mode, "Dolby Pro Logic IIz");
1152     }
1153     if (dheadphonmod==2)
1154     {
1155         Fill(Stream_Audio, 0, Audio_Format_Settings, "Dolby Headphone");
1156         Fill(Stream_Audio, 0, Audio_Format_Settings_Mode, "Dolby Headphone");
1157     }
1158 
1159     //AC-3
1160     if (bsid_Max<=0x09)
1161     {
1162         if (Count_Get(Stream_Audio)==0)
1163             Stream_Prepare(Stream_Audio);
1164         if (Retrieve(Stream_Audio, 0, Audio_Format).empty() || MediaInfoLib::Config.LegacyStreamDisplay_Get())
1165         {
1166             Fill(Stream_Audio, 0, Audio_Format, "AC-3");
1167             Fill(Stream_Audio, 0, Audio_Codec, "AC3");
1168         }
1169 
1170         int32u Divider=bsid_Max==9?2:1; // Unofficial hack for low sample rate (e.g. 22.05 kHz)
1171         if (Ztring::ToZtring(AC3_SamplingRate[fscod]/Divider)!=Retrieve(Stream_Audio, 0, Audio_SamplingRate))
1172             Fill(Stream_Audio, 0, Audio_SamplingRate, AC3_SamplingRate[fscod]/Divider);
1173         if (frmsizecod/2<19)
1174         {
1175             if (Frame_Count_HD)
1176                 Fill(Stream_Audio, 0, Audio_BitRate, "Unknown");
1177             int32u BitRate=AC3_BitRate[frmsizecod/2]*1000;
1178             int32u Divider=bsid_Max==9?2:1; // Unofficial hack for low sample rate (e.g. 22.05 kHz)
1179             int32u TimeStamp_BitRate=0;
1180             if (TimeStamp_Count==Frame_Count || TimeStamp_Count>Frame_Count/2) // In case of corrupted stream, check that there is a minimal count of timestamps
1181                 TimeStamp_BitRate+=float32_int32s(AC3_SamplingRate[fscod]/Divider/12.0); // 12 = 1536 samples per frame / 128 bits per timestamp frame
1182             Fill(Stream_Audio, 0, Audio_BitRate, BitRate/Divider);
1183             if (TimeStamp_BitRate)
1184                 Fill(Stream_Audio, 0, Audio_BitRate_Encoded, BitRate/Divider+TimeStamp_BitRate);
1185             if (CalculateDelay && Buffer_TotalBytes_FirstSynched>100 && BitRate>0)
1186             {
1187                 Fill(Stream_Audio, 0, Audio_Delay, (float)Buffer_TotalBytes_FirstSynched*8*1000/BitRate, 0);
1188                 Fill(Stream_Audio, 0, Audio_Delay_Source, "Stream");
1189             }
1190         }
1191 
1192         Fill(Stream_Audio, 0, Audio_ServiceKind, AC3_Mode[bsmod_Max[0][0]]);
1193         Fill(Stream_Audio, 0, Audio_ServiceKind_String, AC3_Mode_String[bsmod_Max[0][0]]);
1194         if ((MediaInfoLib::Config.LegacyStreamDisplay_Get() || Retrieve(Stream_Audio, 0, Audio_ChannelLayout).empty()) && acmod_Max[0][0]!=(int8u)-1)
1195         {
1196             int8u Channels=AC3_Channels[acmod_Max[0][0]];
1197             Ztring ChannelPositions; ChannelPositions.From_UTF8(AC3_ChannelPositions[acmod_Max[0][0]]);
1198             Ztring ChannelPositions2; ChannelPositions2.From_UTF8(AC3_ChannelPositions2[acmod_Max[0][0]]);
1199             Ztring ChannelLayout; ChannelLayout.From_UTF8(lfeon_Max[0][0]?AC3_ChannelLayout_lfeon[acmod_Max[0][0]]:AC3_ChannelLayout_lfeoff[acmod_Max[0][0]]);
1200             if (lfeon_Max[0][0])
1201             {
1202                 Channels+=1;
1203                 ChannelPositions+=__T(", LFE");
1204                 ChannelPositions2+=__T(".1");
1205             }
1206             if (Ztring::ToZtring(Channels)!=Retrieve(Stream_Audio, 0, Audio_Channel_s_))
1207                 Fill(Stream_Audio, 0, Audio_Channel_s_, Channels);
1208             if (ChannelPositions!=Retrieve(Stream_Audio, 0, Audio_ChannelPositions))
1209                 Fill(Stream_Audio, 0, Audio_ChannelPositions, ChannelPositions);
1210             if (ChannelPositions2!=Retrieve(Stream_Audio, 0, Audio_ChannelPositions_String2))
1211                 Fill(Stream_Audio, 0, Audio_ChannelPositions_String2, ChannelPositions2);
1212             if (Retrieve(Stream_Audio, 0, Audio_ChannelLayout).empty())
1213                 Fill(Stream_Audio, 0, Audio_ChannelLayout, ChannelLayout);
1214         }
1215         if (!Retrieve(Stream_Audio, 0, Audio_Format_Profile).empty())
1216             Fill(Stream_Audio, 0, Audio_Format_Profile, "AC-3");
1217         if (!Retrieve(Stream_Audio, 0, Audio_Codec_Profile).empty())
1218             Fill(Stream_Audio, 0, Audio_Codec_Profile, "AC-3");
1219         if ((MediaInfoLib::Config.LegacyStreamDisplay_Get() && __T("CBR")!=Retrieve(Stream_Audio, 0, Audio_BitRate_Mode)) || Retrieve(Stream_Audio, 0, Audio_BitRate_Mode).empty())
1220             Fill(Stream_Audio, 0, Audio_BitRate_Mode, "CBR");
1221     }
1222 
1223     //E-AC-3
1224     else if (bsid_Max<=0x10)
1225     {
1226         for (size_t Pos=0; Pos<8; Pos++)
1227             if (acmod_Max[Pos][0]!=(int8u)-1)
1228             {
1229                 if (Count_Get(Stream_Audio)==0)
1230                     Stream_Prepare(Stream_Audio);
1231                 if (Retrieve(Stream_Audio, 0, Audio_Format).empty())
1232                 {
1233                     Fill(Stream_Audio, 0, Audio_Format, Formats[0]?"AC-3":"E-AC-3");
1234                     Fill(Stream_Audio, 0, Audio_Codec, Formats[0] ?"AC-3":"AC3+");
1235                 }
1236 
1237                 if (acmod_Max[1][0]!=(int8u)-1)
1238                     Fill(Stream_Audio, 0, Audio_ID, 1+Pos);
1239 
1240                 Fill(Stream_Audio, 0, Audio_BitRate_Mode, "CBR");
1241                 int8u numblks=numblkscod==3?6:numblkscod+1;
1242                 int32u frmsiz_Total=0;
1243                 for (size_t Pos2=0; Pos2<8; Pos2++)
1244                     frmsiz_Total+=frmsizplus1_Max[Pos][Pos2];
1245                 int32u SamplingRate;
1246                 if (fscod!=3)
1247                     SamplingRate=AC3_SamplingRate[fscod];
1248                 else
1249                     SamplingRate=AC3_SamplingRate2[fscod2];
1250                 int32u TimeStamp_Size=0;
1251                 if (TimeStamp_Count==Frame_Count || TimeStamp_Count>Frame_Count/2) // In case of corrupted stream, check that there is a minimal count of timestamps
1252                     TimeStamp_Size=16;
1253                 Fill(Stream_Audio, 0, Audio_SamplingRate, SamplingRate);
1254                 Fill(Stream_Audio, 0, Audio_BitRate, ((int64u)frmsiz_Total)*SamplingRate/32/numblks);
1255                 if (TimeStamp_Size)
1256                     Fill(Stream_Audio, 0, Audio_BitRate_Encoded, ((int64u)frmsiz_Total+TimeStamp_Size)*SamplingRate/32/numblks);
1257 
1258                 if (acmod_Max[Pos][1]!=(int8u)-1)
1259                 {
1260                     int16u chanmap_Final=0;
1261                     for (int8u Pos2=0; Pos2<9; Pos2++)
1262                         if (acmod_Max[Pos][Pos2]!=(int8u)-1)
1263                         {
1264                             if (chanmape_Max[Pos][Pos2])
1265                                 chanmap_Final|=chanmap_Max[Pos][Pos2];
1266                             else
1267                             {
1268                                 chanmap_Final|=AC3_acmod2chanmap[acmod_Max[Pos][Pos2]];
1269                                 if (lfeon_Max[Pos][Pos2])
1270                                     chanmap_Final|=1; // LFE position in chanmap is bit 0
1271                             }
1272                         }
1273 
1274                     Fill(Stream_Audio, 0, Audio_Format_Profile, "E-AC-3+Dep");
1275                     Fill(Stream_Audio, 0, Audio_Codec_Profile, "E-AC-3+Dep");
1276                     Fill(Stream_Audio, 0, Audio_Channel_s_, AC3_chanmap_Channels(chanmap_Final));
1277                     Fill(Stream_Audio, 0, Audio_ChannelPositions, AC3_chanmap_ChannelPositions(chanmap_Final));
1278                     Ztring ChannelPositions2; ChannelPositions2.From_UTF8(AC3_ChannelPositions2[acmod_Max[0][0]]); //TODO: handle the dependancy
1279                     if (lfeon_Max[Pos][0])
1280                     {
1281                         ChannelPositions2+=__T(".1");
1282                     }
1283                     Fill(Stream_Audio, 0, Audio_ChannelPositions_String2, ChannelPositions2);
1284                     if (MediaInfoLib::Config.LegacyStreamDisplay_Get() || Retrieve(Stream_Audio, 0, Audio_ChannelLayout).empty())
1285                     {
1286                         Ztring ChannelLayout; ChannelLayout.From_UTF8(lfeon_Max[0][0]?AC3_ChannelLayout_lfeon[acmod_Max[0][0]]:AC3_ChannelLayout_lfeoff[acmod_Max[0][0]]);
1287                         Fill(Stream_Audio, 0, Audio_ChannelLayout, AC3_chanmap_ChannelLayout(chanmap_Final, ChannelLayout));
1288                     }
1289                 }
1290                 if (!Retrieve(Stream_Audio, 0, Audio_Format_Profile).empty())
1291                     Fill(Stream_Audio, 0, Audio_Format_Profile, Retrieve(Stream_Audio, 0, Audio_Format));
1292                 if (!Retrieve(Stream_Audio, 0, Audio_Codec_Profile).empty())
1293                     Fill(Stream_Audio, 0, Audio_Codec_Profile, Retrieve(Stream_Audio, 0, Audio_Format));
1294                 Fill(Stream_Audio, 0, Audio_ServiceKind, AC3_Mode[bsmod_Max[0][0]]);
1295                 Fill(Stream_Audio, 0, Audio_ServiceKind_String, AC3_Mode_String[bsmod_Max[0][0]]);
1296                 if ((MediaInfoLib::Config.LegacyStreamDisplay_Get() || Retrieve(Stream_Audio, 0, Audio_Channel_s_).empty()) && acmod_Max[Pos][0]!=(int8u)-1)
1297                 {
1298                     int8u Channels=AC3_Channels[acmod_Max[Pos][0]];
1299                     Ztring ChannelPositions; ChannelPositions.From_UTF8(AC3_ChannelPositions[acmod_Max[Pos][0]]);
1300                     Ztring ChannelPositions2; ChannelPositions2.From_UTF8(AC3_ChannelPositions2[acmod_Max[0][0]]);
1301                     if (lfeon_Max[Pos][0])
1302                     {
1303                         Channels+=1;
1304                         ChannelPositions+=__T(", LFE");
1305                         ChannelPositions2+=__T(".1");
1306                     }
1307                     Fill(Stream_Audio, 0, Audio_Channel_s_, Channels);
1308                     Fill(Stream_Audio, 0, Audio_ChannelPositions, ChannelPositions);
1309                     Fill(Stream_Audio, 0, Audio_ChannelPositions_String2, ChannelPositions2);
1310                     Fill(Stream_Audio, 0, Audio_ChannelLayout, lfeon_Max[0][0]?AC3_ChannelLayout_lfeon[acmod_Max[0][0]]:AC3_ChannelLayout_lfeoff[acmod_Max[0][0]]);
1311                 }
1312             }
1313     }
1314 
1315     if (HD_MajorSync_Parsed)
1316     {
1317         //Filling Maximum bitrate with the constant core bitrate for better coherancy
1318         ZtringList List;
1319         List.Separator_Set(0, __T(" / "));
1320         List.Write(Retrieve(Stream_Audio, 0, Audio_BitRate));
1321         if (List.size()>=2)
1322             Fill(Stream_Audio, 0, Audio_BitRate_Maximum, List[1]);
1323     }
1324 
1325     //Dolby Metadata
1326     if (Core_IsPresent)
1327     {
1328         //Endianess
1329         Fill(Stream_Audio, 0, Audio_Format_Settings_Endianness, BigEndian?"Big":"Little");
1330         Fill(Stream_Audio, 0, "bsid", bsid_Max);
1331 
1332         Fill(Stream_Audio, 0, "dialnorm", FirstFrame_Dolby.dialnorm==0?-31:-FirstFrame_Dolby.dialnorm);
1333         Fill_SetOptions(Stream_Audio, 0, "dialnorm", "N NT");
1334         Fill(Stream_Audio, 0, "dialnorm/String", Ztring::ToZtring(FirstFrame_Dolby.dialnorm==0?-31:-FirstFrame_Dolby.dialnorm)+__T(" dB"));
1335         Fill_SetOptions(Stream_Audio, 0, "dialnorm/String", "N NTN");
1336         if (FirstFrame_Dolby.compre)
1337         {
1338             float64 Value=AC3_compr[FirstFrame_Dolby.compr>>4]+20*std::log10(((float)(0x10+(FirstFrame_Dolby.compr&0x0F)))/32);
1339             Fill(Stream_Audio, 0, "compr", Value, 2);
1340             Fill_SetOptions(Stream_Audio, 0, "compr", "N NT");
1341             Fill(Stream_Audio, 0, "compr/String", Ztring::ToZtring(Value, 2)+__T(" dB"));
1342             Fill_SetOptions(Stream_Audio, 0, "compr/String", "N NTN");
1343         }
1344         if (FirstFrame_Dolby.dynrnge)
1345         {
1346             float64 Value;
1347             if (FirstFrame_Dolby.dynrng==0)
1348                 Value=0; //Special case in the formula
1349             else
1350                 Value=AC3_dynrng[FirstFrame_Dolby.dynrng>>5]+20*std::log10(((float)(0x20+(FirstFrame_Dolby.dynrng&0x1F)))/64);
1351             Fill(Stream_Audio, 0, "dynrng", Value, 2);
1352             Fill_SetOptions(Stream_Audio, 0, "dynrng", "N NT");
1353             Fill(Stream_Audio, 0, "dynrng/String", Ztring::ToZtring(Value, 2)+__T(" dB"));
1354             Fill_SetOptions(Stream_Audio, 0, "dynrng/String", "N NTN");
1355         }
1356 
1357         for (int8u Pos=0; Pos<8; Pos++)
1358             for (int8u Pos2=0; Pos2<9; Pos2++)
1359             {
1360                 if (acmod_Max[Pos][Pos2]==(int8u)-1)
1361                     break;
1362                 else
1363                 {
1364                     if (acmod_Max[Pos][Pos2]==2)
1365                     {
1366                         Fill(Stream_Audio, 0, "dsurmod", dsurmod_Max[Pos][Pos2]);
1367                         Fill_SetOptions(Stream_Audio, 0, "dsurmod", "N NT");
1368                         Fill(Stream_Audio, 0, "dsurmod/String", AC3_Surround[dsurmod_Max[Pos][Pos2]]);
1369                         Fill_SetOptions(Stream_Audio, 0, "dsurmod/String", "N NTN");
1370                     }
1371                     Fill_SetOptions(Stream_Audio, 0, "bsid", "N NT");
1372                     Fill(Stream_Audio, 0, "acmod", acmod_Max[Pos][Pos2]);
1373                     Fill_SetOptions(Stream_Audio, 0, "acmod", "N NT");
1374                     Fill(Stream_Audio, 0, "lfeon", (lfeon_Max[Pos][Pos2])?1:0);
1375                     Fill_SetOptions(Stream_Audio, 0, "lfeon", "N NT");
1376                 }
1377             }
1378     }
1379 
1380     //TimeStamp
1381     if (TimeStamp_IsPresent)
1382     {
1383         Ztring TimeCode_FrameRate=Ztring::ToZtring((float64)TimeStamp_FirstFrame.FramesPerSecond/((TimeStamp_FirstFrame.DropFrame|TimeStamp_FirstFrame.FramesPerSecond_Is1001)?1.001:1.000), 3);
1384         if (TimeStamp_FirstFrame.MoreSamples)
1385             TimeStamp_FirstFrame.MoreSamples_Frequency=Retrieve(Stream_Audio, 0, Audio_SamplingRate).To_int32s();
1386         Fill(Stream_Audio, 0, "TimeCode_FirstFrame", TimeStamp_FirstFrame.ToString());
1387         Fill_SetOptions(Stream_Audio, 0, "TimeCode_FirstFrame", "N YCY");
1388         Fill(Stream_Audio, 0, "TimeCode_FirstFrame/String", TimeStamp_FirstFrame.ToString()+" ("+TimeCode_FrameRate.To_UTF8()+" fps), embedded in stream");
1389         Fill_SetOptions(Stream_Audio, 0, "TimeCode_FirstFrame/String", "Y NTN");
1390         Fill(Stream_Audio, 0, "TimeCode_FirstFrame_FrameRate", TimeStamp_FirstFrame.ToString());
1391         Fill_SetOptions(Stream_Audio, 0, "TimeCode_FirstFrame_FrameRate", "N YFY");
1392         Fill(Stream_Audio, 0, "TimeCode_Source", "Stream");
1393         Fill_SetOptions(Stream_Audio, 0, "TimeCode_Source", "N YTY");
1394         Fill(Stream_Audio, 0, Audio_Delay, TimeStamp_FirstFrame.ToMilliseconds());
1395         Fill(Stream_Audio, 0, Audio_Delay_Source, "Stream");
1396         Fill(Stream_Audio, 0, Audio_Delay_Settings, TimeStamp_FirstFrame.DropFrame?"drop_frame_flag=1":"drop_frame_flag=0");
1397     }
1398 
1399     //Samples per frame
1400     int16u SamplesPerFrame;
1401     if (bsid_Max<=0x08)
1402         SamplesPerFrame=1536;
1403     else if (bsid_Max<=0x09)
1404         SamplesPerFrame=768; // Unofficial hack for low sample rate (e.g. 22.05 kHz)
1405     else if (bsid_Max>0x0A && bsid_Max<=0x10)
1406         SamplesPerFrame=256*(numblkscod==3?6:(numblkscod+1));
1407     else if (HD_MajorSync_Parsed && (HD_StreamType==0xBA || HD_StreamType==0xBB)) // TrueHD or MLP
1408     {
1409         int64u HD_SamplingRate=Retrieve_Const(Stream_Audio, 0, Audio_SamplingRate).To_int64u();
1410         if (HD_SamplingRate<44100)
1411             SamplesPerFrame=0; //Unknown
1412         else if (HD_SamplingRate<=48000)
1413             SamplesPerFrame=40;
1414         else if (HD_SamplingRate<=96000)
1415             SamplesPerFrame=80;
1416         else if (HD_SamplingRate<=192000)
1417             SamplesPerFrame=160;
1418         else
1419             SamplesPerFrame=0; //Unknown
1420     }
1421     else
1422         SamplesPerFrame=0;
1423     if (SamplesPerFrame)
1424         Fill(Stream_Audio, 0, Audio_SamplesPerFrame, SamplesPerFrame);
1425 
1426     // Commercial name
1427     if (Retrieve(Stream_Audio, 0, Audio_Format)==__T("E-AC-3") || Retrieve(Stream_Audio, 0, Audio_Format_Profile).find(__T("E-AC-3"))==0)
1428     {
1429         if (HasJOC)
1430             Fill(Stream_Audio, 0, Audio_Format_Commercial_IfAny, "Dolby Digital Plus with Dolby Atmos");
1431         else
1432             Fill(Stream_Audio, 0, Audio_Format_Commercial_IfAny, "Dolby Digital Plus");
1433     }
1434     else if (Retrieve(Stream_Audio, 0, Audio_Format)==__T("MLP FBA") || Retrieve(Stream_Audio, 0, Audio_Format_Profile).find(__T("MLP FBA"))==0)
1435     {
1436         if (HasJOC || HD_HasAtmos)
1437             Fill(Stream_Audio, 0, Audio_Format_Commercial_IfAny, "Dolby TrueHD with Dolby Atmos");
1438         else
1439             Fill(Stream_Audio, 0, Audio_Format_Commercial_IfAny, "Dolby TrueHD");
1440     }
1441     else if (Retrieve(Stream_Audio, 0, Audio_Format)==__T("MLP") || Retrieve(Stream_Audio, 0, Audio_Format_Profile).find(__T("MLP"))==0)
1442     {
1443         Fill(Stream_Audio, 0, Audio_Format_Commercial_IfAny, "MLP Lossless");
1444     }
1445     else if (Retrieve(Stream_Audio, 0, Audio_Format)==__T("AC-3"))
1446         Fill(Stream_Audio, 0, Audio_Format_Commercial_IfAny, "Dolby Digital");
1447     Fill(Stream_General, 0, General_Format, Retrieve(Stream_Audio, 0, Audio_Format), true);
1448     Fill(Stream_General, 0, General_Format_Profile, Retrieve(Stream_Audio, 0, Audio_Format_Profile));
1449     Fill(Stream_General, 0, General_Format_Commercial_IfAny, Retrieve(Stream_Audio, 0, Audio_Format_Commercial_IfAny));
1450 }
1451 
1452 //---------------------------------------------------------------------------
Streams_Finish()1453 void File_Ac3::Streams_Finish()
1454 {
1455     //Stats
1456     if (!dialnorms.empty())
1457     {
1458         int8u Minimum_Raw=1;
1459         int8u Maximum_Raw=31;
1460         float64 Sum_Intensity=0;
1461         int64u Count=0;
1462         for (int8u Pos=0; (size_t)Pos<dialnorms.size(); Pos++)
1463             if (dialnorms[Pos])
1464             {
1465                 if (Minimum_Raw<(Pos==0?31:Pos))
1466                     Minimum_Raw=(Pos==0?31:Pos);
1467                 if (Maximum_Raw>(Pos==0?31:Pos))
1468                     Maximum_Raw=(Pos==0?31:Pos);
1469                 Sum_Intensity+=dialnorms[Pos]*pow(10, -((float64)Pos)/10);
1470                 Count+=dialnorms[Pos];
1471             }
1472         if (Count)
1473         {
1474             float64 Average_dB = log10(Sum_Intensity / Count) * 10;
1475             Fill(Stream_Audio, 0, "dialnorm_Average", Average_dB, 0);
1476             Fill_SetOptions(Stream_Audio, 0, "dialnorm_Average", "N NT");
1477             Fill(Stream_Audio, 0, "dialnorm_Average/String", Ztring::ToZtring(Average_dB, 0) + __T(" dB"));
1478             Fill_SetOptions(Stream_Audio, 0, "dialnorm_Average/String", "N NTN");
1479             Fill(Stream_Audio, 0, "dialnorm_Minimum", -Minimum_Raw);
1480             Fill_SetOptions(Stream_Audio, 0, "dialnorm_Minimum", "N NT");
1481             Fill(Stream_Audio, 0, "dialnorm_Minimum/String", Ztring::ToZtring(-Minimum_Raw) + __T(" dB"));
1482             Fill_SetOptions(Stream_Audio, 0, "dialnorm_Minimum/String", "N NTN");
1483             Fill(Stream_Audio, 0, "dialnorm_Maximum", -Maximum_Raw);
1484             Fill_SetOptions(Stream_Audio, 0, "dialnorm_Maximum", "N NTN");
1485             Fill(Stream_Audio, 0, "dialnorm_Maximum/String", Ztring::ToZtring(-Maximum_Raw) + __T(" dB"));
1486             Fill_SetOptions(Stream_Audio, 0, "dialnorm_Maximum/String", "N NTN");
1487             Fill(Stream_Audio, 0, "dialnorm_Count", Count);
1488             Fill_SetOptions(Stream_Audio, 0, "dialnorm_Count", "N NTN");
1489         }
1490     }
1491     if (!comprs.empty())
1492     {
1493         float64 Minimum_dB=47.89;
1494         float64 Maximum_dB=-48.16;
1495         float64 Sum_Intensity=0;
1496         int64u Count=0;
1497         for (size_t Pos=0; Pos<comprs.size(); Pos++)
1498             if (comprs[Pos])
1499             {
1500                 float64 Value=AC3_compr[Pos>>4]+20*std::log10(((float)(0x10+(Pos&0x0F)))/32);
1501                 if (Minimum_dB>Value)
1502                     Minimum_dB=Value;
1503                 if (Maximum_dB<Value)
1504                     Maximum_dB=Value;
1505                 Sum_Intensity+=comprs[Pos]*pow(10, Value/10);
1506                 Count+=comprs[Pos];
1507             }
1508         if (Count)
1509         {
1510             float64 Average_dB = log10(Sum_Intensity / Count) * 10;
1511             Fill(Stream_Audio, 0, "compr_Average", Average_dB, 2);
1512             Fill_SetOptions(Stream_Audio, 0, "compr_Average", "N NT");
1513             Fill(Stream_Audio, 0, "compr_Average/String", Ztring::ToZtring(Average_dB, 2) + __T(" dB"));
1514             Fill_SetOptions(Stream_Audio, 0, "compr_Average/String", "N NTN");
1515             Fill(Stream_Audio, 0, "compr_Minimum", Minimum_dB, 2);
1516             Fill_SetOptions(Stream_Audio, 0, "compr_Minimum", "N NT");
1517             Fill(Stream_Audio, 0, "compr_Minimum/String", Ztring::ToZtring(Minimum_dB, 2) + __T(" dB"));
1518             Fill_SetOptions(Stream_Audio, 0, "compr_Minimum/String", "N NTN");
1519             Fill(Stream_Audio, 0, "compr_Maximum", Maximum_dB, 2);
1520             Fill_SetOptions(Stream_Audio, 0, "compr_Maximum", "N NT");
1521             Fill(Stream_Audio, 0, "compr_Maximum/String", Ztring::ToZtring(Maximum_dB, 2) + __T(" dB"));
1522             Fill_SetOptions(Stream_Audio, 0, "compr_Maximum/String", "N NTN");
1523             Fill(Stream_Audio, 0, "compr_Count", Count);
1524             Fill_SetOptions(Stream_Audio, 0, "compr_Count", "N NT");
1525         }
1526     }
1527     if (dynrnge_Exists && !dynrngs.empty())
1528     {
1529         float64 Minimum_dB=23.95;
1530         float64 Maximum_dB=-24.08;
1531         float64 Sum_Intensity=0;
1532         int64u Count=0;
1533         for (size_t Pos=0; Pos<dynrngs.size(); Pos++)
1534             if (dynrngs[Pos])
1535             {
1536                 float64 Value;
1537                 if (Pos==0)
1538                     Value=0; //Special case in the formula
1539                 else
1540                     Value=AC3_dynrng[Pos>>5]+20*std::log10(((float)(0x20+(Pos&0x1F)))/64);
1541                 if (Minimum_dB>Value)
1542                     Minimum_dB=Value;
1543                 if (Maximum_dB<Value)
1544                     Maximum_dB=Value;
1545                 Sum_Intensity+=dynrngs[Pos]*pow(10, Value/10);
1546                 Count+=dynrngs[Pos];
1547             }
1548         if (Count)
1549         {
1550             float64 Average_dB = log10(Sum_Intensity / Count) * 10;
1551             Fill(Stream_Audio, 0, "dynrng_Average", Average_dB, 2);
1552             Fill_SetOptions(Stream_Audio, 0, "dynrng_Average", "N NT");
1553             Fill(Stream_Audio, 0, "dynrng_Average/String", Ztring::ToZtring(Average_dB, 2) + __T(" dB"));
1554             Fill_SetOptions(Stream_Audio, 0, "dynrng_Average/String", "N NTN");
1555             Fill(Stream_Audio, 0, "dynrng_Minimum", Minimum_dB, 2);
1556             Fill_SetOptions(Stream_Audio, 0, "dynrng_Minimum", "N NT");
1557             Fill(Stream_Audio, 0, "dynrng_Minimum/String", Ztring::ToZtring(Minimum_dB, 2) + __T(" dB"));
1558             Fill_SetOptions(Stream_Audio, 0, "dynrng_Minimum/String", "N NTN");
1559             Fill(Stream_Audio, 0, "dynrng_Maximum", Maximum_dB, 2);
1560             Fill_SetOptions(Stream_Audio, 0, "dynrng_Maximum", "N NT");
1561             Fill(Stream_Audio, 0, "dynrng_Maximum/String", Ztring::ToZtring(Maximum_dB, 2) + __T(" dB"));
1562             Fill_SetOptions(Stream_Audio, 0, "dynrng_Maximum/String", "N NTN");
1563             Fill(Stream_Audio, 0, "dynrng_Count", Count);
1564             Fill_SetOptions(Stream_Audio, 0, "dynrng_Count", "N NT");
1565         }
1566     }
1567 
1568     //Duration
1569     if (!IsSub)
1570     {
1571         int64u Frame_Count_ForDuration=0;
1572         if (Config->ParseSpeed>=1)
1573         {
1574             Frame_Count_ForDuration=Frame_Count; //We have the exact count of frames
1575             Fill(Stream_Audio, 0, Audio_StreamSize, File_Offset+Buffer_Offset+Element_Size-File_Offset_FirstSynched);
1576         }
1577         else if (bsid_Max<=9 && frmsizecods.size()==1 && fscods.size()==1 && Frame_Count_HD==0)
1578         {
1579             int16u Size=AC3_FrameSize_Get(frmsizecods.begin()->first, fscods.begin()->first);
1580             if (Size)
1581             {
1582                 if (TimeStamp_IsPresent)
1583                     Size+=16;
1584                 Frame_Count_ForDuration=(File_Size-File_Offset_FirstSynched)/Size; //Only complete frames
1585                 Fill(Stream_Audio, 0, Audio_StreamSize, Frame_Count_ForDuration*Size);
1586             }
1587         }
1588         if (Frame_Count_ForDuration)
1589         {
1590             Clear(Stream_Audio, 0, Audio_BitRate);
1591 
1592             //HD part
1593             if (Frame_Count_HD)
1594             {
1595                 int32u HD_SamplingRate=AC3_HD_SamplingRate(HD_SamplingRate1);
1596                 if (HD_SamplingRate)
1597                 {
1598                     int8u FrameDuration; //In samples
1599                     if (HD_SamplingRate<44100)
1600                         FrameDuration=0; //Unknown
1601                     else if (HD_SamplingRate<=48000)
1602                         FrameDuration=40;
1603                     else if (HD_SamplingRate<=96000)
1604                         FrameDuration=80;
1605                     else if (HD_SamplingRate<=192000)
1606                         FrameDuration=160;
1607                     else
1608                         FrameDuration=0; //Unknown
1609                     if (FrameDuration)
1610                     {
1611                         int64u SamplingCount=Frame_Count_HD*FrameDuration;
1612                         Fill(Stream_Audio, 0, Audio_Duration, SamplingCount/(((float64)HD_SamplingRate)/1000), 0);
1613                         Fill(Stream_Audio, 0, Audio_SamplingCount, SamplingCount);
1614                         Fill(Stream_Audio, 0, Audio_BitRate, (File_Size-File_Offset_FirstSynched)/(SamplingCount/(((float64)HD_SamplingRate)/1000))*8, 0);
1615                     }
1616                     Fill(Stream_Audio, 0, Audio_FrameCount, Frame_Count_HD);
1617                 }
1618             }
1619             if (Core_IsPresent)
1620             {
1621                 Fill(Stream_Audio, 0, Audio_FrameCount, Frame_Count_ForDuration);
1622                 if (AC3_SamplingRate[fscod])
1623                 {
1624                     float64 FrameDuration;
1625                     if (bsid_Max<=0x08)
1626                         FrameDuration=32;
1627                     else if (bsid_Max<=0x09)
1628                         FrameDuration=16; // Unofficial hack for low sample rate (e.g. 22.05 kHz)
1629                     else
1630                         FrameDuration=0;
1631                     if (FrameDuration)
1632                     {
1633                         FrameDuration*=((float64)48000)/AC3_SamplingRate[fscod]; //32 ms for 48 KHz, else proportional (34.83 for 44.1 KHz, 48 ms for 32 KHz)
1634                         Fill(Stream_Audio, 0, Audio_SamplingCount, Frame_Count_ForDuration*1536);
1635                         Fill(Stream_Audio, 0, Audio_Duration, Frame_Count_ForDuration*FrameDuration, 0);
1636                         if (frmsizecod/2<19)
1637                         {
1638                             int32u BitRate=AC3_BitRate[frmsizecod/2]*1000;
1639                             int32u Divider=bsid_Max == 9?2:1; // Unofficial hack for low sample rate (e.g. 22.05 kHz)
1640                             Fill(Stream_Audio, 0, Audio_BitRate, BitRate/Divider);
1641                         }
1642                     }
1643                 }
1644             }
1645         }
1646     }
1647     else if (FrameInfo.PTS!=(int64u)-1 && FrameInfo.PTS>PTS_Begin)
1648     {
1649         Fill(Stream_Audio, 0, Audio_Duration, float64_int64s(((float64)(FrameInfo.PTS-PTS_Begin))/1000000));
1650         float64 FrameDuration;
1651         if (bsid_Max<=0x08)
1652             FrameDuration=32;
1653         else if (bsid_Max<=0x09)
1654             FrameDuration=16; // Unofficial hack for low sample rate (e.g. 22.05 kHz)
1655         else if (bsid_Max>0x0A && bsid_Max<=0x10)
1656         {
1657             int8u numblks=numblkscod==3?6:numblkscod+1;
1658             FrameDuration=((float64)32)/6*numblks;
1659         }
1660         else
1661             FrameDuration=0;
1662         if (FrameDuration)
1663             Fill(Stream_Audio, 0, Audio_FrameCount, float64_int64s(((float64)(FrameInfo.PTS-PTS_Begin))/1000000/FrameDuration));
1664     }
1665 }
1666 
1667 //---------------------------------------------------------------------------
Read_Buffer_Unsynched()1668 void File_Ac3::Read_Buffer_Unsynched()
1669 {
1670     delete[] Save_Buffer; Save_Buffer=NULL;
1671 
1672     if (File_GoTo==0)
1673         Synched_Init();
1674 }
1675 
1676 //---------------------------------------------------------------------------
1677 #if MEDIAINFO_SEEK
Read_Buffer_Seek(size_t Method,int64u Value,int64u)1678 size_t File_Ac3::Read_Buffer_Seek (size_t Method, int64u Value, int64u /*ID*/)
1679 {
1680     GoTo(0);
1681     Open_Buffer_Unsynch();
1682     return 1;
1683 }
1684 #endif //MEDIAINFO_SEEK
1685 
1686 //***************************************************************************
1687 // Buffer - Synchro
1688 //***************************************************************************
1689 
1690 //---------------------------------------------------------------------------
FileHeader_Begin()1691 bool File_Ac3::FileHeader_Begin()
1692 {
1693     //Specific cases
1694     if (MustParse_dac3 || MustParse_dec3)
1695         return true;
1696 
1697     //Must have enough buffer for having header
1698     if (Buffer_Size<4)
1699         return false; //Must wait for more data
1700 
1701     //False positives detection: detect Matroska files, AC-3 parser is not smart enough
1702     if (!FileHeader_Begin_0x000001())
1703     {
1704         Finish("AC-3");
1705         return false;
1706     }
1707 
1708     //All should be OK...
1709     return true;
1710 }
1711 
1712 //***************************************************************************
1713 // Buffer - Synchro
1714 //***************************************************************************
1715 
1716 //---------------------------------------------------------------------------
Synchronize()1717 bool File_Ac3::Synchronize()
1718 {
1719     //Specific cases
1720     if (MustParse_dac3 || MustParse_dec3)
1721         return true;
1722 
1723     //Synchronizing
1724     while (Buffer_Offset+8<=Buffer_Size)
1725     {
1726         if (!FrameSynchPoint_Test())
1727             return false; //Need more data
1728         if (Synched)
1729             break;
1730         Buffer_Offset++;
1731     }
1732 
1733     //Parsing last bytes if needed
1734     if (Buffer_Offset+8>Buffer_Size)
1735     {
1736         //We must keep more bytes in order to detect TimeStamp
1737         if (Frame_Count==0)
1738         {
1739             if (Buffer_Offset>=16)
1740                 Buffer_Offset-=16;
1741             else
1742                 Buffer_Offset=0;
1743             return false;
1744         }
1745 
1746         if (Buffer_Offset+7==Buffer_Size && CC3(Buffer+Buffer_Offset+4)!=0xF8726F && CC2(Buffer+Buffer_Offset)!=0x0B77 && CC2(Buffer+Buffer_Offset)!=0x770B)
1747             Buffer_Offset++;
1748         if (Buffer_Offset+6==Buffer_Size && CC2(Buffer+Buffer_Offset+4)!=0xF872   && CC2(Buffer+Buffer_Offset)!=0x0B77 && CC2(Buffer+Buffer_Offset)!=0x770B)
1749             Buffer_Offset++;
1750         if (Buffer_Offset+5==Buffer_Size && CC1(Buffer+Buffer_Offset+4)!=0xF8     && CC2(Buffer+Buffer_Offset)!=0x0B77 && CC2(Buffer+Buffer_Offset)!=0x770B)
1751             Buffer_Offset++;
1752         if (Buffer_Offset+4==Buffer_Size && CC2(Buffer+Buffer_Offset)!=0x0B77 && CC2(Buffer+Buffer_Offset)!=0x770B)
1753             Buffer_Offset++;
1754         if (Buffer_Offset+3==Buffer_Size && CC2(Buffer+Buffer_Offset)!=0x0B77 && CC2(Buffer+Buffer_Offset)!=0x770B)
1755             Buffer_Offset++;
1756         if (Buffer_Offset+2==Buffer_Size && CC2(Buffer+Buffer_Offset)!=0x0B77 && CC2(Buffer+Buffer_Offset)!=0x770B)
1757             Buffer_Offset++;
1758         if (Buffer_Offset+1==Buffer_Size && CC1(Buffer+Buffer_Offset)!=0x0B && CC1(Buffer+Buffer_Offset)!=0x77)
1759             Buffer_Offset++;
1760         return false;
1761     }
1762 
1763     //Testing if we have TimeStamp
1764     if (Buffer_Offset>=16)
1765     {
1766         if ( Buffer[Buffer_Offset-0x10+0x00]==0x01      //Magic value? Always 0x01
1767          &&  Buffer[Buffer_Offset-0x10+0x01]==0x10      //Size? Always 0x10
1768          &&  Buffer[Buffer_Offset-0x10+0x02]==0x00      //First  byte of HH? Always 0x00
1769          && (Buffer[Buffer_Offset-0x10+0x03]>>4 )<0x6   //Second byte of HH? First  4 bits must be <0x6
1770          && (Buffer[Buffer_Offset-0x10+0x03]&0xF)<0xA   //Second byte of HH? Second 4 bits must be <0xA
1771          &&  Buffer[Buffer_Offset-0x10+0x04]==0x00      //First  byte of MM? Always 0x00
1772          && (Buffer[Buffer_Offset-0x10+0x05]>>4 )<0x6   //Second byte of MM? First  4 bits must be <0x6
1773          && (Buffer[Buffer_Offset-0x10+0x05]&0xF)<0xA   //Second byte of MM? Second 4 bits must be <0xA
1774          &&  Buffer[Buffer_Offset-0x10+0x06]==0x00      //First  byte of SS? Always 0x00
1775          && (Buffer[Buffer_Offset-0x10+0x07]>>4 )<0x6   //Second byte of SS? First  4 bits must be <0x6
1776          && (Buffer[Buffer_Offset-0x10+0x07]&0xF)<0xA   //Second byte of SS? Second 4 bits must be <0xA
1777          &&  Buffer[Buffer_Offset-0x10+0x08]==0x00      //First  byte of FF? Always 0x00
1778          && (Buffer[Buffer_Offset-0x10+0x09]>>4 )<0x4   //Second byte of FF? First  4 bits must be <0x4
1779          && (Buffer[Buffer_Offset-0x10+0x09]&0xF)<0xA   //Second byte of FF? Second 4 bits must be <0xA
1780          && !(Buffer[Buffer_Offset-0x10+0x00]==0x00     //We want at least a byte not zero, in order to differentiate TimeStamp from padding
1781            && Buffer[Buffer_Offset-0x10+0x01]==0x00
1782            && Buffer[Buffer_Offset-0x10+0x0C]==0x00
1783            && Buffer[Buffer_Offset-0x10+0x0D]==0x00
1784            && Buffer[Buffer_Offset-0x10+0x0E]==0x00
1785            && Buffer[Buffer_Offset-0x10+0x0F]==0x00))
1786         {
1787             TimeStamp_IsPresent=true;
1788             Buffer_Offset-=16;
1789         }
1790     }
1791 
1792     //Synched
1793     return true;
1794 }
1795 
1796 //---------------------------------------------------------------------------
Synched_Init()1797 void File_Ac3::Synched_Init()
1798 {
1799     if (!Frame_Count_Valid)
1800         Frame_Count_Valid=Config->ParseSpeed>=0.3?32:2;
1801 
1802     //FrameInfo
1803     PTS_End=0;
1804     if (!IsSub)
1805     {
1806         FrameInfo.DTS=0; //No DTS in container
1807         FrameInfo.PTS=0; //No PTS in container
1808     }
1809     DTS_Begin=FrameInfo.DTS;
1810     DTS_End=FrameInfo.DTS;
1811     if (Frame_Count_NotParsedIncluded==(int64u)-1)
1812         Frame_Count_NotParsedIncluded=0; //No Frame_Count_NotParsedIncluded in the container
1813 }
1814 
1815 //---------------------------------------------------------------------------
Synched_Test()1816 bool File_Ac3::Synched_Test()
1817 {
1818     //Specific cases
1819     if (MustParse_dac3 || MustParse_dec3)
1820         return true;
1821 
1822     //Must have enough buffer for having header
1823     if (Buffer_Offset+(TimeStamp_IsPresent?16:0)+6>Buffer_Size)
1824         return false;
1825 
1826     //TimeStamp
1827     if (TimeStamp_IsPresent && !TimeStamp_Parsed)
1828     {
1829         if (!( Buffer[Buffer_Offset+0x00]==0x01         //Magic value? Always 0x01
1830            &&  Buffer[Buffer_Offset+0x01]==0x10         //Size? Always 0x10
1831            &&  Buffer[Buffer_Offset+0x02]==0x00         //First  byte of HH? Always 0x00
1832            && (Buffer[Buffer_Offset+0x03]>>4 )<0x6      //Second byte of HH? First  4 bits must be <0x6
1833            && (Buffer[Buffer_Offset+0x03]&0xF)<0xA      //Second byte of HH? Second 4 bits must be <0xA
1834            &&  Buffer[Buffer_Offset+0x04]==0x00         //First  byte of MM? Always 0x00
1835            && (Buffer[Buffer_Offset+0x05]>>4 )<0x6      //Second byte of MM? First  4 bits must be <0x6
1836            && (Buffer[Buffer_Offset+0x05]&0xF)<0xA      //Second byte of MM? Second 4 bits must be <0xA
1837            &&  Buffer[Buffer_Offset+0x06]==0x00         //First  byte of SS? Always 0x00
1838            && (Buffer[Buffer_Offset+0x07]>>4 )<0x6      //Second byte of SS? First  4 bits must be <0x6
1839            && (Buffer[Buffer_Offset+0x07]&0xF)<0xA      //Second byte of SS? Second 4 bits must be <0xA
1840            &&  Buffer[Buffer_Offset+0x08]==0x00         //First  byte of FF? Always 0x00
1841            && (Buffer[Buffer_Offset+0x09]>>4 )<0x4      //Second byte of FF? First  4 bits must be <0x4
1842            && (Buffer[Buffer_Offset+0x09]&0xF)<0xA))    //Second byte of FF? Second 4 bits must be <0xA
1843             TimeStamp_IsPresent=false;
1844     }
1845     if (TimeStamp_IsPresent && !TimeStamp_Parsed)
1846         Buffer_Offset+=16;
1847 
1848     //Quick test of synchro
1849     if (!FrameSynchPoint_Test())
1850     {
1851         if (TimeStamp_IsPresent && !TimeStamp_Parsed && Buffer_Offset>=16)
1852             Buffer_Offset-=16;
1853         return false; //Need more data
1854     }
1855     if (!Synched)
1856         return true;
1857 
1858     //TimeStamp
1859     if (TimeStamp_IsPresent && !TimeStamp_Parsed)
1860     {
1861         Buffer_Offset-=16;
1862         if (Synched)
1863         {
1864             TimeStamp_IsParsing=true;
1865             TimeStamp_Parsed=false;
1866         }
1867         else
1868         {
1869             TimeStamp_IsParsing=false;
1870             TimeStamp_Parsed=false;
1871         }
1872     }
1873 
1874     //We continue
1875     return true;
1876 }
1877 
1878 //***************************************************************************
1879 // Buffer - Demux
1880 //***************************************************************************
1881 
1882 //---------------------------------------------------------------------------
1883 #if MEDIAINFO_DEMUX
Demux_UnpacketizeContainer_Test()1884 bool File_Ac3::Demux_UnpacketizeContainer_Test()
1885 {
1886     if (TimeStamp_IsPresent)
1887         Buffer_Offset+=16;
1888 
1889     if (!HD_IsPresent && Frame_Count==0 && Save_Buffer==NULL)
1890     {
1891         //Searching HD part
1892         size_t Buffer_Offset_Save=Buffer_Offset;
1893         Buffer_Offset++;
1894         Synched=false;
1895         while (Buffer_Offset+8<=Buffer_Size)
1896         {
1897             if (!FrameSynchPoint_Test())
1898             {
1899                 Buffer_Offset=Buffer_Offset_Save;
1900                 return false; //Need more data
1901             }
1902             if (Synched)
1903                 break;
1904             Buffer_Offset++;
1905         }
1906         Buffer_Offset=Buffer_Offset_Save;
1907         if (!Synched)
1908         {
1909             Synched=true;
1910             if (TimeStamp_IsPresent)
1911                 Buffer_Offset-=16;
1912             return false; //Need more data
1913         }
1914     }
1915 
1916     if (Save_Buffer)
1917     {
1918         Demux_TotalBytes-=Buffer_Offset;
1919         Demux_Offset-=Buffer_Offset;
1920         File_Offset+=Buffer_Offset;
1921         swap(Buffer, Save_Buffer);
1922         swap(Buffer_Offset, Save_Buffer_Offset);
1923         swap(Buffer_Size, Save_Buffer_Size);
1924     }
1925 
1926     if (Buffer[Buffer_Offset]==0x0B && Buffer[Buffer_Offset+1]==0x77)
1927     {
1928         int8u bsid=Buffer[Buffer_Offset+5]>>3;
1929         if (bsid<=0x08)
1930             FrameInfo.DUR=32000000;
1931         else if (bsid<=0x09)
1932             FrameInfo.DUR=16000000; // Unofficial hack for low sample rate (e.g. 22.05 kHz)
1933         else if (bsid>0x0A && bsid<=0x10)
1934         {
1935             numblkscod=(Buffer[Buffer_Offset+4]>>4)&0x3;
1936             int64u numblks=numblkscod==3?6:numblkscod+1;
1937             FrameInfo.DUR=32000000*numblks/6;
1938         }
1939 
1940         Demux_Offset=Buffer_Offset+Core_Size_Get();
1941 
1942         //Core part
1943         if (HD_IsPresent)
1944         {
1945             if (TimeStamp_IsPresent)
1946                 Buffer_Offset-=16;
1947 
1948             if (Save_Buffer)
1949             {
1950                 swap(Buffer, Save_Buffer);
1951                 swap(Buffer_Offset, Save_Buffer_Offset);
1952                 swap(Buffer_Size, Save_Buffer_Size);
1953                 Demux_TotalBytes+=Buffer_Offset;
1954                 Demux_Offset+=Buffer_Offset;
1955                 File_Offset-=Buffer_Offset;
1956             }
1957 
1958             return true; //No AC-3 demux
1959         }
1960     }
1961     else
1962     {
1963         Demux_Offset=Buffer_Offset+HD_Size_Get();
1964     }
1965 
1966     if (Demux_Offset>Buffer_Size && File_Offset+Buffer_Size!=File_Size)
1967     {
1968         if (TimeStamp_IsPresent)
1969             Buffer_Offset-=16;
1970 
1971         if (Save_Buffer)
1972         {
1973             swap(Buffer, Save_Buffer);
1974             swap(Buffer_Offset, Save_Buffer_Offset);
1975             swap(Buffer_Size, Save_Buffer_Size);
1976             Demux_TotalBytes+=Buffer_Offset;
1977             Demux_Offset+=Buffer_Offset;
1978             File_Offset-=Buffer_Offset;
1979         }
1980 
1981         return false; //No complete frame
1982     }
1983 
1984     Demux_UnpacketizeContainer_Demux();
1985 
1986     if (Save_Buffer)
1987     {
1988         swap(Buffer, Save_Buffer);
1989         swap(Buffer_Offset, Save_Buffer_Offset);
1990         swap(Buffer_Size, Save_Buffer_Size);
1991         Demux_TotalBytes+=Buffer_Offset;
1992         Demux_Offset+=Buffer_Offset;
1993         File_Offset-=Buffer_Offset;
1994     }
1995 
1996     if (TimeStamp_IsPresent)
1997         Buffer_Offset-=16;
1998 
1999     return true;
2000 }
2001 #endif //MEDIAINFO_DEMUX
2002 
2003 //***************************************************************************
2004 // Buffer - Global
2005 //***************************************************************************
2006 
2007 //---------------------------------------------------------------------------
Read_Buffer_OutOfBand()2008 void File_Ac3::Read_Buffer_OutOfBand()
2009 {
2010     if (MustParse_dmlp)
2011     {
2012         dmlp();
2013         return;
2014     }
2015 }
2016 
2017 //---------------------------------------------------------------------------
Read_Buffer_Continue()2018 void File_Ac3::Read_Buffer_Continue()
2019 {
2020     if (MustParse_dac3)
2021     {
2022         dac3();
2023         return;
2024     }
2025     if (MustParse_dec3)
2026     {
2027         dec3();
2028         return;
2029     }
2030 }
2031 
2032 //***************************************************************************
2033 // Buffer - Per element
2034 //***************************************************************************
2035 
2036 //---------------------------------------------------------------------------
Header_Parse()2037 void File_Ac3::Header_Parse()
2038 {
2039     //TimeStamp
2040     if (TimeStamp_IsParsing)
2041     {
2042         Header_Fill_Size(16);
2043         Header_Fill_Code(2, "TimeStamp");
2044         return;
2045     }
2046 
2047     if (Save_Buffer)
2048     {
2049         File_Offset+=Buffer_Offset;
2050         swap(Buffer, Save_Buffer);
2051         swap(Buffer_Offset, Save_Buffer_Offset);
2052         swap(Buffer_Size, Save_Buffer_Size);
2053     }
2054 
2055     //Filling
2056     if ((Buffer[Buffer_Offset]==0x0B && Buffer[Buffer_Offset+1]==0x77)
2057      || (Buffer[Buffer_Offset]==0x77 && Buffer[Buffer_Offset+1]==0x0B))
2058     {
2059         Header_Fill_Size(Core_Size_Get());
2060         Header_Fill_Code(0, "syncframe");
2061 
2062         //Little Endian management
2063         if (Save_Buffer)
2064         {
2065             swap(Buffer, Save_Buffer);
2066             swap(Buffer_Offset, Save_Buffer_Offset);
2067             swap(Buffer_Size, Save_Buffer_Size);
2068             File_Offset-=Buffer_Offset;
2069         }
2070 
2071         return;
2072     }
2073 
2074     //MLP or TrueHD specific
2075     int16u Size;
2076     BS_Begin();
2077     Skip_S1( 4,                                                 "CRC?");
2078     Get_S2 (12, Size,                                           "Size");
2079     BS_End();
2080     Skip_B2(                                                    "Timestamp?");
2081 
2082     //Little Endian management
2083     if (Save_Buffer)
2084     {
2085         swap(Buffer, Save_Buffer);
2086         swap(Buffer_Offset, Save_Buffer_Offset);
2087         swap(Buffer_Size, Save_Buffer_Size);
2088     }
2089 
2090     //Filling
2091     if (Size<2)
2092     {
2093         Synched=false;
2094         Size=2;
2095     }
2096 
2097     Size*=2;
2098     Header_Fill_Size(Size);
2099     Header_Fill_Code(1, "HD");
2100 }
2101 
2102 //---------------------------------------------------------------------------
Data_Parse()2103 void File_Ac3::Data_Parse()
2104 {
2105     if (Element_Code != 2) // Not time stamp
2106         TimeStamp_Parsed=false; //Currently, only one kind of intermediate element is detected (no TimeStamp and HD part together), and we don't know the precise specification of MLP nor TimeStamp, so we consider next eleemnt is TimeStamp
2107 
2108     if (Save_Buffer)
2109     {
2110         File_Offset+=Buffer_Offset;
2111         swap(Buffer, Save_Buffer);
2112         swap(Buffer_Offset, Save_Buffer_Offset);
2113         swap(Buffer_Size, Save_Buffer_Size);
2114     }
2115 
2116     //Parsing
2117     switch (Element_Code)
2118     {
2119         case 0 :
2120                     Core();
2121                     break;
2122         case 1 :
2123                     Element_Info1C((FrameInfo.PTS!=(int64u)-1), __T("PTS ")+Ztring().Duration_From_Milliseconds(float64_int64s(((float64)FrameInfo.PTS)/1000000)));
2124                     Element_Info1(Frame_Count);
2125                     HD();
2126                     break;
2127         case 2 : TimeStamp();   break;
2128         default: ;
2129     }
2130 
2131     //Little Endian management
2132     if (Save_Buffer)
2133     {
2134         delete[] Buffer;
2135         Buffer=Save_Buffer; Save_Buffer=NULL;
2136         Buffer_Offset=Save_Buffer_Offset;
2137         Buffer_Size=Save_Buffer_Size;
2138         File_Offset-=Buffer_Offset;
2139     }
2140 }
2141 
2142 //---------------------------------------------------------------------------
Core()2143 void File_Ac3::Core()
2144 {
2145     while (Element_Offset<Element_Size)
2146     {
2147         if (substreams_Count)
2148         {
2149             Element_Name("Block");
2150             Element_Begin1("syncframe");
2151         }
2152         Core_Frame();
2153         if (substreams_Count)
2154             Element_End0();
2155     }
2156 
2157     if (acmod_Max[0][0]==(int8u)-1)
2158         return; //Waiting for the first sync frame
2159 
2160     FILLING_BEGIN();
2161         if (bsid>0x10)
2162             return; //Not supported
2163 
2164         //Counting
2165         if (Frame_Count==0)
2166         {
2167             Core_IsPresent=true;
2168             PTS_Begin=FrameInfo.PTS;
2169         }
2170         if (bsid==0x09)
2171             Frequency_b=AC3_SamplingRate2[fscod]; // Unofficial hack for low sample rate (e.g. 22.05 kHz)
2172         else
2173         {
2174             if (fscod!=3)
2175                 Frequency_b=AC3_SamplingRate[fscod];
2176             else
2177                 Frequency_b=AC3_SamplingRate2[fscod2];
2178         }
2179         if (bsid>0x0A)
2180         {
2181             int64u numblks = numblkscod == 3 ? 6 : numblkscod + 1;
2182             TS_Add(numblks*256);
2183         }
2184         else
2185             TS_Add(1536);
2186 
2187         if (File_Offset+Buffer_Offset+Element_Size==File_Size)
2188             Frame_Count_Valid=Frame_Count; //Finish frames in case of there are less than Frame_Count_Valid frames
2189 
2190         //Filling
2191         if (!Status[IsAccepted])
2192             Accept("AC-3");
2193         if (!Status[IsFilled] && Frame_Count>=Frame_Count_Valid)
2194         {
2195             Fill("AC-3");
2196 
2197             //No more need data
2198             if (!IsSub && Config->ParseSpeed<1.0)
2199                 Finish("AC-3");
2200         }
2201     FILLING_END();
2202 }
2203 
2204 //---------------------------------------------------------------------------
Core_Frame()2205 void File_Ac3::Core_Frame()
2206 {
2207     //Save true Element_Size (if Core+substreams, Element_Size is for all elements, and we want to limit to core)
2208     int64u Element_Size_Save=Element_Size;
2209     bsid=CC1(Buffer+Buffer_Offset+Element_Offset+5)>>3;
2210     if (bsid<=0x09)
2211     {
2212         fscod     =(Buffer[(size_t)(Buffer_Offset+4)]&0xC0)>>6;
2213         frmsizecod= Buffer[(size_t)(Buffer_Offset+4)]&0x3F;
2214 
2215         //Filling
2216         fscods[fscod]++;
2217         frmsizecods[frmsizecod]++;
2218         Element_Size=Element_Offset+AC3_FrameSize_Get(frmsizecod, fscod);
2219         if (Element_Size>Element_Size_Save)
2220             Element_Size=Element_Size_Save; // Not expected, but trying to parse the begining
2221     }
2222     else if (bsid>0x0A && bsid<=0x10) //E-AC-3 only
2223     {
2224         int16u frmsiz=CC2(Buffer+Buffer_Offset+(size_t)Element_Offset+2)&0x07FF;
2225         Element_Size=Element_Offset+2+frmsiz*2;
2226         if (Element_Size>Element_Size_Save)
2227             Element_Size=Element_Size_Save; // Not expected, but trying to parse the begining
2228     }
2229     if (Element_Offset==Element_Size)
2230         Element_Size=Element_Size_Save; // Something went wrong, using the whole packet
2231 
2232     //Pre-parsing, finding some elements presence
2233     int16u auxdatal;
2234     if (Buffer[Buffer_Offset+(Element_Size)-3]&0x02) //auxdatae
2235         auxdatal=(((int16u)Buffer[Buffer_Offset+(Element_Size)-4])<<6)
2236                 |(         Buffer[Buffer_Offset+(Element_Size)-3] >>2);
2237     else
2238         auxdatal=(int16u)-1; //auxdata is empty
2239     BitStream_Fast Search(Buffer+Buffer_Offset+Element_Offset, Element_Size-Element_Offset);
2240     while(Search.Remain()>18)
2241     {
2242         if (Search.Peek2(16)==0x5838 && Ac3_EMDF_Test(Search))
2243             break;
2244         Search.Skip(1);
2245     }
2246     if (Search.Remain()>18)
2247         EMDF_RemainPos=Search.Remain();
2248     else
2249         EMDF_RemainPos=(size_t)-1;
2250 
2251     //Parsing
2252     int16u frmsiz=0, chanmap=0;
2253     int8u  dialnorm=(int8u)-1, dialnorm2=(int8u)-1, compr=(int8u)-1, compr2=(int8u)-1, dynrng=(int8u)-1, dynrng2=(int8u)-1;
2254     int8u  strmtyp=0, substreamid=0, acmod=0, bsmod=0, dsurmod=0;
2255     bool   compre=false, compr2e=false, dynrnge=false, dynrng2e=false;
2256     bool   lfeon=false, chanmape=false;
2257     bool   addbsie;
2258 
2259     if (bsid<=0x09)
2260     {
2261         Element_Begin1("synchinfo");
2262             Skip_B2(                                                "syncword");
2263             Skip_B2(                                                "crc1");
2264             BS_Begin();
2265             Get_S1 (2, fscod,                                       "fscod - Sample Rate Code"); Param_Info2(AC3_SamplingRate[fscod], " Hz");
2266             Get_S1 (6, frmsizecod,                                  "frmsizecod - Frame Size Code"); Param_Info2C(frmsizecod/2<19,AC3_BitRate[frmsizecod/2]*1000, " bps");
2267         Element_End0();
2268 
2269         Element_Begin1("bsi");
2270             Get_S1 (5, bsid,                                        "bsid - Bit Stream Identification");
2271             Get_S1 (3, bsmod,                                       "bsmod - Bit Stream Mode"); Param_Info1(AC3_Mode[bsmod]);
2272             Get_S1 (3, acmod,                                       "acmod - Audio Coding Mode"); Param_Info1(AC3_ChannelPositions[acmod]);
2273             if ((acmod&1) && acmod!=1) //central present
2274                 Skip_S1(2,                                          "cmixlev - Center Mix Level");
2275             if (acmod&4) //back present
2276                 Skip_S1(2,                                          "surmixlev - Surround Mix Level");
2277             if (acmod==2)
2278                 Get_S1 (2, dsurmod,                                 "dsurmod - Dolby Surround Mode"); Param_Info1(AC3_Surround[dsurmod]);
2279             Get_SB (   lfeon,                                       "lfeon - Low Frequency Effects");
2280             Get_S1 (5, dialnorm,                                    "dialnorm - Dialogue Normalization");
2281             Get_SB (   compre,                                      "compre - Compression Gain Word Exists");
2282             if (compre)
2283                 Get_S1 (8, compr,                                   "compr - Compression Gain Word");
2284             TEST_SB_SKIP(                                           "langcode - Language Code Exists");
2285                 Skip_S1(8,                                          "langcod - Language Code");
2286             TEST_SB_END();
2287             TEST_SB_SKIP(                                           "audprodie - Audio Production Information Exists");
2288                 Skip_S1(8,                                          "mixlevel - Mixing Level");
2289                 Skip_S1(2,                                          "roomtyp - Room Type");
2290             TEST_SB_END();
2291             if (acmod==0) //1+1 mode
2292             {
2293                 Get_S1 (5, dialnorm2,                               "dialnorm2 - Dialogue Normalization");
2294                 Get_SB (   compr2e,                                 "compr2e - Compression Gain Word Exists");
2295                 if (compr2e)
2296                     Get_S1 (8, compr2,                              "compr2 - Compression Gain Word");
2297                 TEST_SB_SKIP(                                       "langcod2e - Language Code Exists");
2298                     Skip_S1(8,                                      "langcod2 - Language Code");
2299                 TEST_SB_END();
2300                 TEST_SB_SKIP(                                       "audprodi2e - Audio Production Information Exists");
2301                     Skip_S1(8,                                      "mixlevel2 - Mixing Level");
2302                     Skip_S1(2,                                      "roomtyp2 - Room Type");
2303                 TEST_SB_END();
2304             }
2305             Skip_SB(                                                "copyrightb - Copyright Bit");
2306             Skip_SB(                                                "origbs - Original Bit Stream");
2307             if (bsid==0x06)
2308             {
2309                 TEST_SB_SKIP(                                       "xbsi1e");
2310                     Skip_S1(2,                                      "dmixmod");
2311                     Skip_S1(3,                                      "ltrtcmixlev");
2312                     Skip_S1(3,                                      "ltrtsurmixlev");
2313                     Skip_S1(3,                                      "lorocmixlev");
2314                     Skip_S1(3,                                      "lorosurmixlev");
2315                 TEST_SB_END();
2316                 TEST_SB_SKIP(                                       "xbsi2e");
2317                     Get_S1 (2, dsurexmod,                           "dsurexmod");
2318                     Get_S1 (2, dheadphonmod,                        "dheadphonmod");
2319                     Skip_SB(                                        "adconvtyp");
2320                     Skip_S1(8,                                      "xbsi2");
2321                     Skip_SB(                                        "encinfo");
2322                 TEST_SB_END();
2323             }
2324             else
2325             {
2326                 TEST_SB_SKIP(                                       "timecod1e");
2327                     Skip_S2(14,                                     "timecod1");
2328                 TEST_SB_END();
2329                 TEST_SB_SKIP(                                       "timecod2e");
2330                     Skip_S2(14,                                     "timecod2");
2331                 TEST_SB_END();
2332             }
2333             TEST_SB_SKIP(                                           "addbsie");
2334                 int8u addbsil;
2335                 Get_S1 (6, addbsil,                                 "addbsil");
2336                 for (int8u Pos=0; Pos<=addbsil; Pos++) //addbsil+1 bytes
2337                     Skip_S1(8,                                      "addbsi");
2338             TEST_SB_END();
2339         Element_End0();
2340         Element_Begin1("audblk");
2341             for (int8u Pos=0; Pos<AC3_Channels[acmod]; Pos++)
2342                 Skip_SB(                                            "blksw - Block Switch Flag");
2343             for (int8u Pos=0; Pos<AC3_Channels[acmod]; Pos++)
2344                 Skip_SB(                                            "dithflag - Dither Flag");
2345             Get_SB (   dynrnge,                                     "dynrnge - Dynamic Range Gain Word Exists");
2346             if (dynrnge)
2347                 Get_S1 (8, dynrng,                                  "dynrng - Dynamic Range Gain Word");
2348             if (acmod==0) //1+1 mode
2349             {
2350                 Get_SB (   dynrng2e,                                "dynrng2e - Dynamic Range Gain Word Exists");
2351                 if (dynrng2e)
2352                     Get_S1 (8, dynrng2,                             "dynrng2 - Dynamic Range Gain Word");
2353             }
2354         Element_End0();
2355     }
2356     else if (bsid>0x0A && bsid<=0x10)
2357     {
2358         /* Not finished, for reference only
2359         static const size_t MAX_AUD_BLK = 6;
2360         static const size_t MAX_CHANNELS = 5;
2361         struct Aud_Blk
2362         {
2363             bool  cplstre;
2364             bool  cplinu;
2365             bool  lfeexpstr;
2366             int8u blkmixcfginfo;
2367             int8u cplexpstr;
2368 
2369             int8u chexpstr[MAX_CHANNELS];
2370         };
2371         Aud_Blk aud_blks[MAX_AUD_BLK];
2372 
2373         struct Aud_Chan_Blk
2374         {
2375             bool  blksw;
2376             bool  chahtinu;
2377             bool  chincpl;
2378             bool  chinspx;
2379             bool  cplcoe;
2380             bool  dithflag;
2381             bool  ecplparam1e;
2382             bool  firstspxcos;
2383             bool  firstcplcos;
2384             bool  rsvdfieldse;
2385             bool  spxcoe;
2386 
2387             int8u chactivegaqbins; //todo
2388             int8u chbwcod;
2389             int8u convexpstr;
2390             int8u deltbae;
2391             int8u endmant;
2392             int8u frmchexpstr;
2393             int8u mstrspxco;
2394             int8u spxblnd;
2395             int8u strtmant;
2396         };
2397         Aud_Chan_Blk aud_chan_blk[MAX_CHANNELS];
2398         bool firstcplleak = false;
2399         //*/
2400 
2401         Element_Begin1("synchinfo");
2402             Skip_B2(                                               "syncword");
2403         Element_End0();
2404         Element_Begin1("bsi");
2405             BS_Begin();
2406             size_t Bits_Begin=Data_BS_Remain();
2407             Get_S1 ( 2, strmtyp,                                    "strmtyp");
2408             Get_S1 ( 3, substreamid,                                "substreamid");
2409             Get_S2 (11, frmsiz,                                     "frmsiz");
2410             Get_S1 ( 2, fscod,                                      "fscod"); Param_Info2(AC3_SamplingRate[fscod], " Hz");
2411             if (fscod==3)
2412             {
2413                 Get_S1 ( 2, fscod2,                                 "fscod2"); Param_Info2(AC3_SamplingRate2[fscod2], " Hz");
2414                 numblkscod=3;
2415             }
2416             else
2417                 Get_S1 ( 2, numblkscod,                             "numblkscod");
2418             Get_S1 (3, acmod,                                       "acmod - Audio Coding Mode"); Param_Info1(AC3_ChannelPositions[acmod]);
2419             Get_SB (   lfeon,                                       "lfeon - Low Frequency Effects");
2420             Get_S1 (5, bsid,                                        "bsid - Bit Stream Identification");
2421             Get_S1 (5, dialnorm,                                    "dialnorm");
2422             TEST_SB_GET(compre,                                     "compre");
2423                 Get_S1 (8, compr,                                   "compr");
2424             TEST_SB_END();
2425             if (acmod==0) //1+1 mode
2426             {
2427                 Get_S1 (5, dialnorm2,                               "dialnorm2");
2428                 TEST_SB_GET(compr2e,                                "compr2e");
2429                     Get_S1 (8, compr2,                              "compr2");
2430                 TEST_SB_END();
2431             }
2432             if (strmtyp==1) //dependent stream
2433             {
2434                 TEST_SB_GET (chanmape,                              "chanmape");
2435                     Get_S2(16, chanmap,                             "chanmap"); Param_Info1(AC3_chanmap_ChannelPositions(chanmap));
2436                 TEST_SB_END();
2437             }
2438             TEST_SB_SKIP(                                           "mixmdate");
2439                 int8u dmixmod, ltrtcmixlev, lorocmixlev, ltrtsurmixlev, lorosurmixlev, mixdef;
2440                 if(acmod > 0x2)
2441                     Get_S1 (2, dmixmod,                             "dmixmod");
2442                 if((acmod&0x1) && (acmod>0x2))
2443                 {
2444                     Get_S1 (3, ltrtcmixlev,                         "ltrtcmixlev");
2445                     Get_S1 (3, lorocmixlev,                         "lorocmixlev");
2446                 }
2447                 if(acmod>0x4)
2448                 {
2449                     Get_S1 (3, ltrtsurmixlev,                       "ltrtsurmixlev");
2450                     Get_S1 (3, lorosurmixlev,                       "lorosurmixlev");
2451                 }
2452                 if(lfeon)
2453                 {
2454                     TEST_SB_SKIP(                                   "lfemixlevcode");
2455                         Skip_S1 (5,                                 "lfemixlevcod");
2456                     TEST_SB_END();
2457                 }
2458                 if(strmtyp == 0x0)
2459                 {
2460                     TEST_SB_SKIP(                                   "pgmscle");
2461                         Skip_S1 (6,                                 "pgmscl");
2462                     TEST_SB_END();
2463                     if (acmod == 0x0)
2464                     {
2465                         TEST_SB_SKIP(                               "pgmscle12e");
2466                             Skip_S1 (6,                             "pgmscl12e");
2467                         TEST_SB_END();
2468                     }
2469                     TEST_SB_SKIP(                                   "extpgmscle");
2470                         Skip_S1 (6,                                 "extpgmscl");
2471                     TEST_SB_END();
2472                     Get_S1 (2, mixdef,                              "mixdef");
2473                     if(mixdef == 0x1)
2474                     {
2475                         Skip_S1 (1,                                 "premixcmpsel");
2476                         Skip_S1 (1,                                 "drcsrc");
2477                         Skip_S1 (3,                                 "premixcmpscl");
2478                     }
2479                     else if(mixdef == 0x2) Skip_S2 (12,             "mixdata");
2480                     else if(mixdef == 0x3)
2481                     {
2482                         int8u mixdeflen;
2483                         Get_S1 (5, mixdeflen,                       "mixdeflen");
2484                         TEST_SB_SKIP(                               "mixdata2e");
2485                             Skip_S1 (6,                             "premixcmpsel");
2486                             Skip_S1 (1,                             "drcsrc");
2487                             Skip_S1 (3,                             "premixcmpscl");
2488                             TEST_SB_SKIP(                           "extpgmlscle");
2489                                 Skip_S1 (4,                         "extpgmlscl");
2490                             TEST_SB_END();
2491                             TEST_SB_SKIP(                           "extpgmcscle");
2492                                 Skip_S1 (4,                         "extpgmcscl");
2493                             TEST_SB_END();
2494                             TEST_SB_SKIP(                           "extpgmrscle");
2495                                 Skip_S1 (4,                         "extpgmrscl");
2496                             TEST_SB_END();
2497                             TEST_SB_SKIP(                           "extpgmlssle");
2498                                 Skip_S1 (4,                         "extpgmlssl");
2499                             TEST_SB_END();
2500                             TEST_SB_SKIP(                           "extpgmrssle");
2501                                 Skip_S1 (4,                         "extpgmrssl");
2502                             TEST_SB_END();
2503                             TEST_SB_SKIP(                           "extpgmlfescle");
2504                                 Skip_S1 (4,                         "extpgmlfescl");
2505                             TEST_SB_END();
2506                             TEST_SB_SKIP(                           "dmixscle");
2507                                 Skip_S1 (4,                         "dmixscl");
2508                             TEST_SB_END();
2509                             TEST_SB_SKIP(                           "addche");
2510                                 TEST_SB_SKIP(                       "extpgmaux1scle");
2511                                     Skip_S1 (4,                     "extpgmaux1scl");
2512                                 TEST_SB_END();
2513                                 TEST_SB_SKIP(                       "extpgmaux2scle");
2514                                     Skip_S1 (4,                     "extpgmaux2scl");
2515                                 TEST_SB_END();
2516                             TEST_SB_END();
2517                         TEST_SB_END();
2518                         TEST_SB_SKIP(                               "mixdata3e");
2519                             Skip_S1 (5,                             "spchdat");
2520                             TEST_SB_SKIP(                           "addspchdate");
2521                                 Skip_S1 (5,                         "spchdat1");
2522                                 Skip_S1 (2,                         "spchan1att");
2523                                 TEST_SB_SKIP(                       "addspdat1e");
2524                                     Skip_S1 (5,                     "spchdat2");
2525                                     Skip_S1 (2,                     "spchan2att");
2526                                 TEST_SB_END();
2527                             TEST_SB_END();
2528                         TEST_SB_END();
2529                         Skip_S2 (8*(mixdeflen+2),                   "mixdata");
2530                         //Skip_S1 (,                                 "mixdatafill");
2531                     }
2532                     if(acmod<0x2)
2533                     {
2534                         TEST_SB_SKIP(                               "paninfoe");
2535                             Skip_S1 (6,                             "panmean");
2536                             Skip_S1 (8,                             "paninfo");
2537                         TEST_SB_END();
2538                         if(acmod==0x0)
2539                         {
2540                             TEST_SB_SKIP(                           "paninfo2e");
2541                                Skip_S1 (6,                          "panmean2");
2542                                Skip_S1 (8,                          "paninfo2");
2543                             TEST_SB_END();
2544                         }
2545                     }
2546                     TEST_SB_SKIP(                                   "frmmixcfginfoe");
2547                         if(numblkscod==0x0)
2548                         {
2549                             int8u blkmixcfginfo;
2550                             Get_S1 (5, blkmixcfginfo,               "blkmixcfginfo[0]");
2551                             //aud_blks[0].blkmixcfginfo = blkmixcfginfo;
2552                         }
2553                         else
2554                         {
2555                             int8u nb_blocks_per_syncframe = numblkscod == 3 ? 6 : (numblkscod + 1);
2556                             for (int8u blk = 0; blk < nb_blocks_per_syncframe; ++blk)
2557                             {
2558                                 TEST_SB_SKIP(                       "blkmixcfginfoe");
2559                                     int8u blkmixcfginfo;
2560                                     Get_S1 (5, blkmixcfginfo,       "blkmixcfginfo[x]");
2561                                     //aud_blks[blk].blkmixcfginfo = blkmixcfginfo;
2562                                 TEST_SB_END();
2563                             }
2564                         }
2565                     TEST_SB_END();
2566                 }
2567             TEST_SB_END();
2568 
2569             TEST_SB_SKIP(                                           "infomdate");
2570                 Skip_S1(3,                                          "bsmod");
2571                 Skip_SB(                                            "copyrightb - Copyright Bit");
2572                 Skip_SB(                                            "origbs - Original Bit Stream");
2573                 if (acmod==0x2)
2574                 {
2575                     Get_S1 (2, dsurmod,                             "dsurmod");
2576                     Get_S1 (2, dheadphonmod,                        "dheadphonmod");
2577                 }
2578                 if (acmod>=0x6)
2579                     Get_S1 (2, dsurexmod,                           "dsurexmod");
2580                 TEST_SB_SKIP(                                       "audprodie");
2581                     Skip_S1(5,                                      "mixlevel");
2582                     Skip_S1(2,                                      "roomtyp");
2583                     Skip_S1(1,                                      "adconvtyp");
2584                 TEST_SB_END();
2585                 if (acmod==0x0)
2586                 {
2587                     TEST_SB_SKIP(                                   "audprodi2e");
2588                         Skip_S1(5,                                  "mixlevel2");
2589                         Skip_S1(2,                                  "roomtyp2");
2590                         Skip_S1(1,                                  "adconvtyp2");
2591                     TEST_SB_END();
2592                 }
2593                 if (fscod < 0x3)
2594                     Skip_S1(1,                                      "sourcefscod");
2595             TEST_SB_END();
2596 
2597             if (strmtyp==0x0 && numblkscod!=0x3)
2598                 Skip_S1(1,                                          "convsync");
2599 
2600             if (strmtyp == 0x2)
2601             {
2602                 int8u blkid = 0;
2603                 if (numblkscod==0x3)
2604                     blkid = 1;
2605                 else
2606                     Get_S1(1, blkid,                                "blkid");
2607                 if (blkid)
2608                     Get_S1(6, frmsizecod,                           "frmsizecod");
2609             }
2610 
2611             TEST_SB_GET (addbsie,                                   "addbsie");
2612                 int8u addbsil;
2613                 Get_S1 (6, addbsil,                                 "addbsil");
2614                 if (addbsil+1!=addbsi_Buffer_Size)
2615                 {
2616                     delete[] addbsi_Buffer;
2617                     addbsi_Buffer_Size=addbsil+1;
2618                     addbsi_Buffer=new int8u[addbsi_Buffer_Size];
2619                 }
2620                 for (int8u Pos=0; Pos<=addbsil; Pos++) //addbsil+1 bytes
2621                     Get_S1 (8, addbsi_Buffer[Pos],                  "addbsi");
2622             TEST_SB_END();
2623         Element_End0();
2624 
2625         /* Not finished, for reference only
2626         int8u numblks = numblkscod == 3 ? 6 : (numblkscod + 1);
2627 
2628         Element_Begin1("audfrm");
2629         int8u snroffststr, ncplblks = 0;
2630         bool expstre = true, ahte = false;
2631         bool transproce, blkswe, dithflage, bamode, frmfgaincode, dbaflde, skipflde, spxattene;
2632         if (numblkscod==0x3)
2633         {
2634             Get_SB(expstre,                                         "expstre");
2635             Get_SB(ahte,                                            "ahte");
2636         }
2637         Get_S1 (2, snroffststr,                                     "snroffststr");
2638         Get_SB (transproce,                                         "transproce");
2639         Get_SB (blkswe,                                             "blkswe");
2640         Get_SB (dithflage,                                          "dithflage");
2641         Get_SB (bamode,                                             "bamode");
2642         Get_SB (frmfgaincode,                                       "frmfgaincode");
2643         Get_SB (dbaflde,                                            "dbaflde");
2644         Get_SB (skipflde,                                           "skipflde");
2645         Get_SB (spxattene,                                          "spxattene");
2646 
2647         if (acmod>0x1)
2648         {
2649             aud_blks[0].cplstre = 1;
2650             aud_blks[0].cplinu = 0;
2651             for (int8u blk = 1; blk < numblks; ++blk)
2652             {
2653                 Get_SB (aud_blks[blk].cplstre,                      "cplstre[x]");
2654                 if (aud_blks[blk].cplstre==1)
2655                     Get_SB (aud_blks[blk].cplinu,                   "cplinu[x]");
2656                 else
2657                     aud_blks[blk].cplinu = aud_blks[blk - 1].cplinu;
2658             }
2659         }
2660         else
2661         {
2662             for(int8u blk = 0; blk < numblks; ++blk)
2663                 aud_blks[blk].cplinu = 0;
2664         }
2665 
2666         if (expstre)
2667         {
2668             for(int8u blk = 0; blk < numblks; ++blk)
2669             {
2670                 if (aud_blks[blk].cplinu==1)
2671                     Get_S1 (2, aud_blks[blk].cplexpstr,             "cplexpstr[x]");
2672                 for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
2673                     Get_S1(2, aud_blks[blk].chexpstr[Pos],          "chexpstr[blk][ch]");
2674             }
2675         }
2676         else
2677         {
2678             int8u frmcplexpstr = 0;
2679             ncplblks = 0;
2680             for (int8u blk = 0; blk < numblks; ++blk)
2681                 ncplblks += aud_blks[blk].cplinu;
2682             if (acmod > 0x1 && ncplblks > 0)
2683                 Get_S1(5, frmcplexpstr,                             "frmcplexpstr");
2684             for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
2685                 Get_S1(5, aud_chan_blk[Pos].frmchexpstr,            "frmchexpstr[ch]");
2686         }
2687         if (lfeon)
2688             for (int8u blk = 0; blk < numblks; ++blk)
2689                 Get_SB(aud_blks[blk].lfeexpstr,                     "lfeexpstr[blk]");
2690 
2691         if (strmtyp == 0x0)
2692         {
2693             bool convexpstre = true;
2694             if (numblkscod!=0x3)
2695                 Get_SB (convexpstre,                                "convexpstre");
2696             if (convexpstre)
2697                 for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
2698                     Get_S1(5, aud_chan_blk[Pos].convexpstr,         "convexpstr[ch]");
2699         }
2700 
2701         int8u cplahtinu = 0;
2702         int8u lfeahtinu = 0;
2703         int8u *hebap = NULL; //TODO in ahte
2704         if (ahte)
2705         {
2706             ncplblks = 0;
2707 
2708             int8u ncplregs = 0;
2709             for (int8u blk = 0; blk < numblks; ++blk)
2710             {
2711                 //reuse corresponds to 0
2712                 if (aud_blks[blk].cplstre == 1 || aud_blks[blk].cplexpstr != 0)
2713                     ++ncplregs;
2714             }
2715 
2716             if (ncplblks==6 && ncplregs==1)
2717             {
2718                 bool tmp;
2719                 Get_SB (tmp,                                        "cplahtinu");
2720                 if (tmp)
2721                     cplahtinu = 1;
2722             }
2723 
2724             for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
2725             {
2726                 int8u nchregs = 0;
2727                 for (int8u blk = 0; blk < numblks; ++blk)
2728                 {
2729                     if (aud_blks[blk].chexpstr[Pos]!=0)
2730                         ++nchregs;
2731                 }
2732 
2733                 aud_chan_blk[Pos].chahtinu = 0;
2734                 if (nchregs==1)
2735                 {
2736                     bool tmp;
2737                     Get_SB (tmp,                                    "chahtinu[ch]");
2738                     if (tmp)
2739                         aud_chan_blk[Pos].chahtinu = 1;
2740                 }
2741             }
2742 
2743             if (lfeon)
2744             {
2745                 int8u nlferegs = 0;
2746                 for (int8u blk = 0; blk < numblks; ++blk)
2747                 {
2748                     if (aud_blks[blk].lfeexpstr!=false)
2749                         ++nlferegs;
2750                 }
2751 
2752                 if (nlferegs==1)
2753                 {
2754                     bool tmp = false;
2755                     Get_SB (tmp,                                    "lfeahtinu");
2756                     if (tmp)
2757                         lfeahtinu = 1;
2758                 }
2759             }
2760         }
2761 
2762         if (snroffststr)
2763         {
2764             Skip_S1 (6,                                             "frmcsnroffst");
2765             Skip_S1 (4,                                             "frmfsnroffst");
2766         }
2767 
2768         if (transproce)
2769         {
2770             for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
2771             {
2772                 TEST_SB_SKIP(                                       "chintransproc[ch]");
2773                     Skip_S2(10,                                     "transprocloc[ch]");
2774                     Skip_S1(8,                                      "transproclen[ch]");
2775                 TEST_SB_END();
2776             }
2777         }
2778 
2779         if (spxattene)
2780         {
2781             for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
2782             {
2783                 TEST_SB_SKIP(                                       "chinspxatten[ch]");
2784                     Skip_S1(5,                                      "spxattencod[ch]");
2785                 TEST_SB_END();
2786             }
2787         }
2788 
2789         bool blkstrtinfoe = false;
2790         int8u blkstrtinfo = 0;
2791         if (numblkscod != 0x0)
2792             Get_SB (blkstrtinfoe,                                   "blkstrtinfoe");
2793         if (blkstrtinfoe)
2794             blkstrtinfo = (numblks - 1) * (4 + ceil(log2(frmsiz + 1)));
2795 
2796         // These fields for syntax state initialization
2797         for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
2798         {
2799             aud_chan_blk[Pos].firstspxcos = true;
2800             aud_chan_blk[Pos].firstcplcos = true;
2801         }
2802         firstcplleak = true;
2803         Element_End0();
2804 
2805         Element_Begin1("audblks");
2806             for (int8u blk = 0; blk < numblks; ++blk)
2807             {
2808                 Element_Begin1("audblk");
2809                     if (blkswe)
2810                         for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
2811                             Get_SB (aud_chan_blk[Pos].blksw,        "blksw[ch]");
2812                     else
2813                         for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
2814                             aud_chan_blk[Pos].blksw = false;
2815 
2816                     if (dithflage)
2817                         for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
2818                             Get_SB (aud_chan_blk[Pos].dithflag,     "dithflag[ch]");
2819                     else
2820                         for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
2821                             aud_chan_blk[Pos].dithflag = true;
2822 
2823                     int8u dynrng = 0;
2824                     int8u dynrng2 = 0;
2825                     TEST_SB_SKIP(                                   "dynrnge");
2826                         Get_S1 (8, dynrng,                          "dynrng");
2827                     TEST_SB_END();
2828 
2829                     if (acmod==0x0)
2830                     {
2831                         TEST_SB_SKIP(                               "dynrng2e");
2832                             Get_S1 (8, dynrng,                      "dynrng2");
2833                         TEST_SB_END();
2834                     }
2835 
2836                     int8u spx_begin_subbnd, spx_end_subbnd;
2837                     int8u spxbegf = 0;
2838                     bool spxbndstrc[256];
2839                     bool spxstre = true;
2840                     bool spxinu = false;
2841                     if (blk!=0)
2842                         Peek_SB(spxstre);
2843 
2844                     if (spxstre)
2845                     {
2846                         Element_Begin1("spxstr");
2847                         Skip_SB(                                    "spxstre");
2848                         Get_SB (spxinu,                             "spxinu");
2849                         if (spxinu)
2850                         {
2851                             if (acmod==0x1)
2852                                 aud_chan_blk[0].chinspx = true;
2853                             else
2854                             {
2855                                 for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
2856                                     Get_SB (aud_chan_blk[Pos].chinspx,"chinspx[ch]");
2857                             }
2858 
2859                             int8u spxstrtf, spxendf;
2860 
2861                             Get_S1 (2, spxstrtf,                    "spxstrtf");
2862                             Get_S1 (3, spxbegf,                     "spxbegf");
2863                             Get_S1 (3, spxendf,                     "spxendf");
2864 
2865                             if (spxbegf<6)
2866                                 spx_begin_subbnd = spxbegf + 2;
2867                             else
2868                                 spx_begin_subbnd = spxbegf * 2 - 3;
2869 
2870                             if (spxendf < 3)
2871                                 spx_end_subbnd = spxendf + 5;
2872                             else
2873                                 spx_end_subbnd = spxendf * 2 + 3;
2874 
2875                             TEST_SB_SKIP(                           "spxbndstrce");
2876                             for (int8u bnd = spx_begin_subbnd+1; bnd < spx_end_subbnd; ++bnd)
2877                                 Get_SB (spxbndstrc[bnd],            "spxbndstrc[bnd]");
2878                             TEST_SB_END();
2879                         }
2880                         else
2881                         {
2882                             for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
2883                             {
2884                                 aud_chan_blk[Pos].chinspx = false;
2885                                 aud_chan_blk[Pos].firstspxcos = true;
2886                             }
2887                         }
2888                         Element_End0();
2889                     }
2890 
2891                     if (spxinu)
2892                     {
2893                         Element_Begin1("spxin");
2894                         for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
2895                         {
2896                             Element_Begin1("Channel");
2897                             if (aud_chan_blk[Pos].chinspx)
2898                             {
2899                                 if (aud_chan_blk[Pos].firstspxcos)
2900                                 {
2901                                     aud_chan_blk[Pos].spxcoe = true;
2902                                     aud_chan_blk[Pos].firstspxcos = false;
2903                                 }
2904                                 else
2905                                     Get_SB (aud_chan_blk[Pos].spxcoe,   "spxcoe[ch]");
2906 
2907                                 if (aud_chan_blk[Pos].spxcoe)
2908                                 {
2909                                     Get_S1 (5, aud_chan_blk[Pos].spxblnd,"spxblnd[ch]");
2910                                     Get_S1 (2, aud_chan_blk[Pos].mstrspxco,"mstrspxco[ch]");
2911 
2912                                     int8u nspxbnds = 1;
2913                                     int8u spxbndsztab[256] = {0};
2914                                     spxbndsztab[0] = 12;
2915                                     for (int8u bnd = spx_begin_subbnd+1; bnd < spx_end_subbnd; ++bnd)
2916                                     {
2917                                         if (spxbndstrc[bnd] == false)
2918                                         {
2919                                             spxbndsztab[nspxbnds] = 12;
2920                                             ++nspxbnds;
2921                                         }
2922                                         else
2923                                             spxbndsztab[nspxbnds - 1] += 12;
2924                                     }
2925 
2926                                     for (int8u bnd = 0; bnd < nspxbnds; ++bnd)
2927                                     {
2928                                         Element_Begin1("Bnd");
2929                                         Skip_S1 (4,                     "spxcoexp[ch][bnd]");
2930                                         Skip_S1 (2,                     "spxcomant[ch][bnd]");
2931                                         Element_End0();
2932                                     }
2933                                 }
2934                             }
2935                             else
2936                                 aud_chan_blk[Pos].firstspxcos = true;
2937                             Element_End0();
2938                         }
2939                         Element_End0();
2940                     }
2941 
2942                     bool  ecplinu = false;
2943                     bool  phsflginu = false;
2944                     bool  cplbndstrce = false;
2945                     int8u ncplsubnd = 0;
2946                     bool *cplbndstrc = NULL;
2947                     int16u necplbnd = 0;
2948                     int8u ecplbegf, ecplendf = 0;
2949                     int8u cplbegf, cplendf = 0;
2950                     int16u ecpl_begin_subbnd = 0, ecpl_end_subbnd = 0;
2951                     size_t cplstrtmant = 0;
2952                     size_t lfeactivegaqbins = 0;
2953                     size_t cplendmant = 0;
2954 
2955                     if (aud_blks[blk].cplstre)
2956                     {
2957                         Element_Begin1("cplstr");
2958                         if (aud_blks[blk].cplinu)
2959                         {
2960                             Element_Begin1("cplin");
2961                             Get_SB (ecplinu,                            "ecplinu");
2962 
2963                             if (acmod==0x2)
2964                             {
2965                                 aud_chan_blk[0].chincpl = true;
2966                                 aud_chan_blk[1].chincpl = true;
2967                             }
2968                             else
2969                             {
2970                                 for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
2971                                     Get_SB (aud_chan_blk[1].chincpl,    "chincpl[ch]");
2972                             }
2973 
2974                             if (!ecplinu)
2975                             {
2976                                 if (acmod==0x2)
2977                                     Get_SB (phsflginu,                  "phsflginu");
2978                                 Get_S1 (4, cplbegf,                     "cplbegf");
2979                                 cplstrtmant = (cplbegf * 12) + 37;;
2980 
2981                                 if (!spxinu)
2982                                     Get_S1 (4, cplendf,                 "cplendf");
2983                                 else
2984                                 {
2985                                     if (spxbegf < 6)
2986                                         cplendf = spxbegf - 2;
2987                                     else
2988                                         cplendf = (spxbegf * 2) - 7;
2989                                 }
2990 
2991                                 ncplsubnd = 3 + cplendf - cplbegf;
2992                                 Get_SB (cplbndstrce,                    "cplbndstrce");
2993                                 if (cplbndstrce)
2994                                 {
2995                                     cplbndstrc = new bool [ncplsubnd];
2996                                     cplbndstrc[0] = false;
2997                                     for (int8u bnd = 1; bnd < ncplsubnd; ++bnd)
2998                                         Get_SB (cplbndstrc[bnd],        "cplbndstrc[bnd]");
2999                                 }
3000                             }
3001                             else
3002                             {
3003                                 Get_S1 (4, ecplbegf,                    "ecplbegf");
3004                                 cplstrtmant = (cplbegf * 12) + 37;;
3005 
3006                                 if (ecplbegf<3)
3007                                     ecpl_begin_subbnd = ecplbegf * 2;
3008                                 else if (ecplbegf<13)
3009                                     ecpl_begin_subbnd = ecplbegf + 2;
3010                                 else
3011                                     ecpl_begin_subbnd = ecplbegf * 2 - 10;
3012 
3013                                 if (!spxinu)
3014                                 {
3015                                     Get_S1 (4, ecplendf,                "ecplendf");
3016                                     ecpl_end_subbnd = ecplendf + 7;
3017                                 }
3018                                 else
3019                                 {
3020                                     if (spxbegf < 6)
3021                                         ecpl_end_subbnd = spxbegf + 5;
3022                                     else
3023                                         ecpl_end_subbnd = spxbegf * 2;
3024                                 }
3025 
3026                                 necplbnd = ecpl_end_subbnd - ecpl_begin_subbnd;
3027                                 TEST_SB_SKIP(                           "ecplbndstrce");
3028                                 int16u max = 9;
3029                                 if (max < ecpl_begin_subbnd+1)
3030                                     max = ecpl_begin_subbnd+1;
3031                                 ncplsubnd = ecpl_end_subbnd;
3032 
3033                                 cplbndstrc = new bool [ecpl_end_subbnd];
3034                                 for (size_t i = 0; i < max; ++i)
3035                                     cplbndstrc[i] = false;
3036 
3037                                 for (int16u sbnd = max; sbnd < ecpl_end_subbnd; ++sbnd)
3038                                     Get_SB (cplbndstrc[sbnd],           "cplbndstrc[bnd]");
3039 
3040                                 necplbnd = 0;
3041                                 for (int16u i = ecpl_begin_subbnd; i < ecpl_end_subbnd; ++i)
3042                                     necplbnd += cplbndstrc[i];
3043                                 TEST_SB_END();
3044                             }
3045                             Element_End0();
3046                         }
3047                         else
3048                         {
3049                             for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
3050                             {
3051                                 aud_chan_blk[Pos].chincpl = false;
3052                                 aud_chan_blk[Pos].firstcplcos = true;
3053                             }
3054                             firstcplleak = true;
3055                         }
3056                         Element_End0();
3057                     }
3058 
3059                     if (aud_blks[blk].cplinu)
3060                     {
3061                         if (!ecplinu)
3062                         {
3063                             int16u ncplbnd = ncplsubnd;
3064                             for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
3065                             {
3066                                 if (aud_chan_blk[Pos].chincpl)
3067                                 {
3068                                     if (aud_chan_blk[Pos].firstcplcos)
3069                                     {
3070                                         aud_chan_blk[Pos].cplcoe = true;
3071                                         aud_chan_blk[Pos].firstcplcos = false;
3072                                     }
3073                                     else
3074                                         Get_SB(aud_chan_blk[Pos].cplcoe,"cplcoe[ch]");
3075 
3076                                     if (aud_chan_blk[Pos].cplcoe)
3077                                     {
3078                                         Skip_S1 (2,                     "mstrcplco[ch]");
3079                                         ncplbnd = ncplsubnd;
3080                                         for (size_t i = 1; i < ncplsubnd; ++i)
3081                                             ncplbnd += cplbndstrc[i];
3082                                         for (int16u bnd = 0; bnd < ncplbnd; bnd++)
3083                                         {
3084                                             Skip_S1(4,                  "cplcoexp[ch][bnd]");
3085                                             Skip_S1(4,                  "cplcomant[ch][bnd]");
3086                                         }
3087                                     }
3088                                 }
3089                                 else
3090                                 {
3091                                     aud_chan_blk[Pos].firstcplcos = true;
3092                                 }
3093                             }
3094 
3095                             if (acmod==0x2 && phsflginu && (aud_chan_blk[0].cplcoe || aud_chan_blk[1].cplcoe))
3096                             {
3097                                 for (size_t bnd = 0; bnd < ncplbnd; ++bnd)
3098                                     Skip_SB(                            "phsflg[bnd]}");
3099                             }
3100                         }
3101                         else
3102                         {
3103                             int firstchincpl = -1;
3104                             Skip_SB(                                    "reserved");
3105                             for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
3106                             {
3107                                 if (aud_chan_blk[Pos].chincpl)
3108                                 {
3109                                     if (firstchincpl == -1)
3110                                         firstchincpl = Pos;
3111 
3112                                     if (aud_chan_blk[Pos].firstcplcos)
3113                                     {
3114                                         aud_chan_blk[Pos].ecplparam1e = true;
3115                                         if (Pos > firstchincpl)
3116                                             aud_chan_blk[Pos].rsvdfieldse = true;
3117                                         else
3118                                             aud_chan_blk[Pos].rsvdfieldse = false;
3119                                         aud_chan_blk[Pos].firstcplcos = false;
3120                                     }
3121                                     else
3122                                     {
3123                                         Get_SB (aud_chan_blk[Pos].ecplparam1e, "ecplparam1e");
3124                                         if (Pos > firstchincpl)
3125                                             Get_SB (aud_chan_blk[Pos].rsvdfieldse, "rsvdfieldse");
3126                                         else
3127                                             aud_chan_blk[Pos].rsvdfieldse = false;
3128                                     }
3129 
3130                                     if (aud_chan_blk[Pos].ecplparam1e)
3131                                     {
3132                                         if (aud_chan_blk[Pos].ecplparam1e)
3133                                         {
3134                                             for (size_t bnd = 0; bnd < necplbnd; bnd++)
3135                                                 Skip_S1(5,                  "ecplamp[ch][bnd]");
3136                                         }
3137 
3138                                         if (aud_chan_blk[Pos].rsvdfieldse)
3139                                             Skip_BS(9 * (necplbnd - 1),     "reserved");
3140                                         if (Pos > firstchincpl)
3141                                             Skip_SB(                        "reserved");
3142                                     }
3143                                 }
3144                                 else
3145                                     aud_chan_blk[Pos].firstcplcos = true;
3146                             }
3147                         }
3148                     }
3149 
3150                     //aud_chan_blk_init(acmod, cplbegf);
3151                     for (int8u Pos = 0; Pos<AC3_Channels[acmod]; ++Pos)
3152                     {
3153                         aud_chan_blk[Pos].strtmant = 0;
3154                         if (aud_chan_blk[Pos].chincpl)
3155                             aud_chan_blk[Pos].endmant = 37 + (12 * cplbegf);
3156                         else
3157                             aud_chan_blk[Pos].endmant = 37 + (3 * (aud_chan_blk[Pos].chbwcod + 12));
3158                     }
3159 
3160                     if (acmod==0x2)
3161                     {
3162                         bool rematstr = true;
3163                         if (blk!=0)
3164                             Get_SB(rematstr,                                "rematstr");
3165 
3166                         if (rematstr)
3167                         {
3168                             size_t nrematbd = 0;
3169                             if (aud_blks[blk].cplinu)
3170                             {
3171                                 if (ecplinu)
3172                                 {
3173                                     if (ecplbegf == 0)
3174                                         nrematbd = 0;
3175                                     else if (ecplbegf == 1)
3176                                         nrematbd = 1;
3177                                     else if (ecplbegf == 2)
3178                                         nrematbd = 2;
3179                                     else if (ecplbegf < 5)
3180                                         nrematbd = 3;
3181                                     else
3182                                         nrematbd = 4;
3183                                 }
3184                                 else
3185                                 {
3186                                     if (cplbegf == 0)
3187                                         nrematbd = 2;
3188                                     else if (cplbegf < 3)
3189                                         nrematbd = 3;
3190                                     else
3191                                         nrematbd = 4;
3192                                 }
3193                             }
3194                             else if (spxinu)
3195                             {
3196                                 if (spxbegf < 2)
3197                                     nrematbd = 3;
3198                                 else
3199                                     nrematbd = 4;
3200                             }
3201                             else
3202                             {
3203                                 nrematbd = 4;
3204                             }
3205 
3206                             for (size_t bnd = 0; bnd < nrematbd; ++bnd)
3207                                 Skip_SB(                                    "rematflg[bnd]");
3208                         }
3209                     }
3210 
3211                     for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
3212                     {
3213                         if (aud_blks[blk].chexpstr[Pos])
3214                         {
3215                             if (!aud_chan_blk[Pos].chincpl && !aud_chan_blk[Pos].chinspx)
3216                                 Get_S1 (6, aud_chan_blk[Pos].chbwcod,       "chbwcod[ch]");
3217                         }
3218                     }
3219 
3220                     if (aud_blks[blk].cplinu)
3221                     {
3222                         if (aud_blks[blk].cplexpstr!=0)
3223                         {
3224                             Skip_S1(4,                                      "cplabsexp");
3225 
3226                             size_t ncplgrps = 0;
3227                             if (ecplinu)
3228                             {
3229                                 int8u ecplstartmant = ecplsubbndtab[ecpl_begin_subbnd];
3230                                 int8u ecplendmant = ecplsubbndtab[ecpl_end_subbnd];
3231                                 if (aud_blks[blk].cplexpstr == 0x01)
3232                                     ncplgrps = (ecplendmant - ecplstartmant) / 3;
3233                                 else if (aud_blks[blk].cplexpstr == 0x02)
3234                                     ncplgrps = (ecplendmant - ecplstartmant) / 6;
3235                                 else if (aud_blks[blk].cplexpstr == 0x03)
3236                                     ncplgrps = (ecplendmant - ecplstartmant) / 12;
3237                             }
3238                             else
3239                             {
3240                                 cplendmant = ((cplendf + 3) * 12) + 37;
3241                                 if (aud_blks[blk].cplexpstr == 0x01)
3242                                     ncplgrps = (cplendmant - cplstrtmant) / 3;
3243                                 else if (aud_blks[blk].cplexpstr == 0x02)
3244                                     ncplgrps = (cplendmant - cplstrtmant) / 6;
3245                                 else if (aud_blks[blk].cplexpstr == 0x03)
3246                                     ncplgrps = (cplendmant - cplstrtmant) / 12;
3247                             }
3248 
3249                             for(size_t grp = 0; grp < ncplgrps; grp++)
3250                                 Skip_S1(7,                                  "cplexps[grp]");
3251                         }
3252                     }
3253 
3254                     for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
3255                     {
3256                         if (aud_blks[blk].chexpstr[Pos]!=0)
3257                         {
3258                             Skip_S1(4,                                      "exps[ch][0]");
3259                             size_t nchgrps = 0;
3260                             if (!aud_chan_blk[Pos].chincpl)
3261                                 aud_chan_blk[Pos].endmant = ((aud_chan_blk[Pos].chbwcod + 12) * 3) + 37;
3262                             else
3263                                 aud_chan_blk[Pos].endmant = cplstrtmant;
3264 
3265                             if (aud_blks[blk].cplexpstr==0x01)
3266                                 nchgrps = (aud_chan_blk[Pos].endmant - 1) / 3;
3267                             else if (aud_blks[blk].cplexpstr==0x02)
3268                                 nchgrps = (aud_chan_blk[Pos].endmant - 1) / 3;
3269                             else if (aud_blks[blk].cplexpstr==0x03)
3270                                 nchgrps = (aud_chan_blk[Pos].endmant - 1) / 3;
3271 
3272                             for (size_t grp = 1; grp <= nchgrps; grp++)
3273                                 Skip_S1(7,                                  "exps[ch][grp]");
3274                             Skip_S1(2,                                      "gainrng[ch]");
3275                         }
3276                     }
3277 
3278                     if (lfeon)
3279                     {
3280                         if (aud_blks[blk].lfeexpstr!=0)
3281                         {
3282                             Skip_S1(4,                                      "lfeexps[0]");
3283                             size_t nlfegrps = 2;
3284                             for (size_t grp = 1; grp <= nlfegrps; ++grp)
3285                                 Skip_S1(7,                                  "lfeexps[grp]");
3286                         }
3287                     }
3288 
3289                     int8u sdcycod = 0x2;
3290                     int8u fdcycod = 0x1;
3291                     int8u sgaincod = 0x1;
3292                     int8u dbpbcod = 0x2;
3293                     int8u floorcod = 0x7;
3294                     if (bamode)
3295                     {
3296                         bool baie = false;
3297                         Get_SB(baie,                                        "baie");
3298                         if (baie)
3299                         {
3300                             Get_S1(2, sdcycod,                              "sdcycod");
3301                             Get_S1(2, fdcycod,                              "fdcycod");
3302                             Get_S1(2, sgaincod,                             "sgaincod");
3303                             Get_S1(2, dbpbcod,                              "dbpbcod");
3304                             Get_S1(3, floorcod,                             "floorcod");
3305                         }
3306                     }
3307 
3308                     if (snroffststr!=0x0)
3309                     {
3310                         bool snroffste = true;
3311                         if (blk!=0)
3312                             Get_SB (snroffste,                              "snroffste");
3313 
3314                         if (snroffste)
3315                         {
3316                             Skip_S1(6,                                      "csnroffst");
3317                             if (snroffststr==0x1)
3318                                 Skip_S1(4,                                  "blkfsnroffst");
3319                             else if (snroffststr == 0x2)
3320                             {
3321                                 if (aud_blks[blk].cplinu)
3322                                     Skip_S1(4,                              "cplfsnroffst");
3323                                 for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
3324                                     Skip_S1(4,                              "fsnroffst[ch]");
3325                                 if (lfeon)
3326                                     Skip_S1(4,                              "lfefsnroffst");
3327                             }
3328                         }
3329                     }
3330 
3331                     bool fgaincode = false;
3332                     if (frmfgaincode)
3333                         Get_SB(fgaincode,                                   "fgaincode");
3334 
3335                     if (fgaincode)
3336                     {
3337                         if (aud_blks[blk].cplinu)
3338                             Skip_S1(3, "cplfgaincod");
3339                         for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
3340                             Skip_S1(3,                                      "fgaincod[ch]");
3341                         if (lfeon)
3342                             Skip_S1(3,                                      "lfefgaincod");
3343                     }
3344 
3345                     if (strmtyp == 0x0)
3346                     {
3347                         TEST_SB_SKIP(                                       "convsnroffste");
3348                         Skip_S2(10,                                         "convsnroffst");
3349                         TEST_SB_END();
3350                     }
3351 
3352                     if (aud_blks[blk].cplinu)
3353                     {
3354                         bool cplleake = true;
3355                         if (firstcplleak)
3356                             firstcplleak = false;
3357                         else
3358                             Get_SB (cplleake,                               "cplleake");
3359 
3360                         if (cplleake)
3361                         {
3362                             Skip_S1(3,                                      "cplfleak");
3363                             Skip_S1(3,                                      "cplsleak");
3364                         }
3365                     }
3366 
3367                     if (dbaflde)
3368                     {
3369                         TEST_SB_SKIP(                                       "deltbaie");
3370                         int8u cpldeltbae = 0;
3371                         if (aud_blks[blk].cplinu)
3372                             Get_S1 (2, cpldeltbae,                          "cpldeltbae");
3373                         for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
3374                             Get_S1 (2, aud_chan_blk[Pos].deltbae,        "deltbae[ch]");
3375 
3376                         if (aud_blks[blk].cplinu)
3377                         {
3378                             if (cpldeltbae==0x01)
3379                             {
3380                                 int8u cpldeltnseg;
3381                                 Get_S1 (3, cpldeltnseg,                 "cpldeltnseg");
3382                                 for (int8u seg = 0; seg <= cpldeltnseg; ++seg)
3383                                 {
3384                                     Skip_S1(5,                          "cpldeltoffst[seg]");
3385                                     Skip_S1(4,                          "cpldeltlen[seg]");
3386                                     Skip_S1(3,                          "cpldeltba[seg]");
3387                                 }
3388                             }
3389                         }
3390 
3391                         for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
3392                         {
3393                             if (aud_chan_blk[Pos].deltbae==0x01)
3394                             {
3395                                 int8u deltnseg;
3396                                 Get_S1 (3, deltnseg,                    "deltnseg[ch]");
3397                                 for (int8u seg = 0; seg <= deltnseg; ++seg)
3398                                 {
3399                                     Skip_S1(5,                          "deltoffst[ch][seg]");
3400                                     Skip_S1(4,                          "deltlen[ch][seg]");
3401                                     Skip_S1(3,                          "deltba[ch][seg]");
3402                                 }
3403                             }
3404                         }
3405                         TEST_SB_END();
3406                     }
3407 
3408                     if (skipflde)
3409                     {
3410                         TEST_SB_SKIP(                                   "skiple");
3411                         int16u skipl;
3412                         Get_S2 (9, skipl,                               "skipl");
3413                         Skip_BS(skipl * 8,                              "skipfld");
3414                         //TODO: EMDF();
3415                         TEST_SB_END();
3416                     }
3417 
3418                     bool   got_cplchan = false;
3419                     size_t cplactivegaqbins = 0;
3420                     int8u  lfegaqmod = 0;
3421                     int8u* lfegaqbin = NULL;
3422                     size_t lfeendmant = 7;
3423                     int8u  cplgaqmod = 0;
3424                     lfegaqbin = new int8u[lfeendmant];
3425 
3426                     int8u *cplgaqbin = NULL;
3427                     cplgaqbin = new int8u[cplendmant];
3428                     for (size_t bin = 0; bin < lfeendmant; ++bin)
3429                         lfegaqbin[bin] = 0;
3430 
3431                     for (int8u Pos=0; Pos<AC3_Channels[acmod]; ++Pos)
3432                     {
3433                         if (!aud_chan_blk[Pos].chahtinu)
3434                         {
3435                             aud_chan_blk[Pos].endmant = ((aud_chan_blk[Pos].chbwcod + 12) * 3) + 37;
3436                             for (size_t bin = 0; bin < aud_chan_blk[Pos].endmant; ++bin)
3437                             {
3438                                 //TODO
3439                                 // chmant[ch][bin];
3440                                 // (0-16);
3441                             }
3442                         }
3443 
3444                         else if (aud_chan_blk[Pos].chahtinu)
3445                         {
3446                             int8u chgaqmod = 0;
3447                             size_t chgaqsections = 0;
3448                             Get_S1 (2, chgaqmod,                        "chgaqmod[ch]");
3449                             switch (chgaqmod)
3450                             {
3451                                 case 0:
3452                                 {
3453                                     chgaqsections = 0;
3454                                     break;
3455                                 }
3456                                 case 1:
3457                                 case 2:
3458                                 {
3459                                     chgaqsections = aud_chan_blk[Pos].chactivegaqbins;
3460                                     break;
3461                                 }
3462                                 case 3:
3463                                 {
3464                                     chgaqsections = aud_chan_blk[Pos].chactivegaqbins / 3;
3465                                     if (aud_chan_blk[Pos].chactivegaqbins % 3)
3466                                         ++chgaqsections;
3467                                     break;
3468                                 }
3469                             };
3470 
3471                             if (chgaqmod>0x0 && chgaqmod<0x3)
3472                             {
3473                                 for (size_t n = 0; n < chgaqsections; ++n)
3474                                     Skip_SB(                        "chgaqgain[ch][n]");
3475                             }
3476                             else if (chgaqmod==0x3)
3477                             {
3478                                 for (size_t n = 0; n < chgaqsections; ++n)
3479                                     Skip_S1(5,                          "chgaqgain[ch][n]");
3480                             }
3481 
3482                             aud_chan_blk[Pos].endmant = cplstrtmant;
3483                             int8u* chgaqbin = new int8u [aud_chan_blk[Pos].endmant];
3484                             if (aud_chan_blk[Pos].chahtinu == 0)
3485                             {
3486                                 for (size_t i = 0; i < aud_chan_blk[Pos].endmant; ++i)
3487                                     chgaqbin[i] = 0;
3488                             }
3489                             else
3490                             {
3491                                 int8u endbap = 17;
3492                                 if (chgaqmod < 2)
3493                                     endbap = 12;
3494 
3495                                 aud_chan_blk[Pos].chactivegaqbins = 0;
3496                                 for (size_t i = 0; i < aud_chan_blk[Pos].endmant; ++i)
3497                                 {
3498                                     if (hebap[i] > 7 && hebap[i] < endbap)
3499                                     {
3500                                         chgaqbin[i] = 1;
3501                                         ++aud_chan_blk[Pos].chactivegaqbins;
3502                                     }
3503                                     else if (hebap[i] >= endbap)
3504                                         chgaqbin[i] = -1;
3505                                     else
3506                                         chgaqbin[i] = 0;
3507                                 }
3508                             }
3509 
3510                             for (size_t bin = 0; bin < aud_chan_blk[Pos].endmant; ++bin)
3511                             {
3512 
3513                                 if (!cplahtinu)
3514                                 {
3515                                     for (size_t i = cplstrtmant; i < cplendmant; ++i)
3516                                         cplgaqbin[i] = 0;
3517                                 }
3518                                 else
3519                                 {
3520                                     int8u endbap = 17;
3521                                     if (cplgaqmod < 2)
3522                                         endbap = 12;
3523 
3524                                     cplactivegaqbins = 0;
3525                                 }
3526 
3527                                 if (chgaqbin[bin])
3528                                 {
3529                                     for (size_t n = 0; n < 6; n++)
3530                                     {
3531                                         //TODO
3532                                         // {pre_chmant[n][ch][bin]} ...........................
3533                                         //     (0-16);
3534                                     }
3535                                 }
3536                                 else
3537                                 {
3538                                     //TODO
3539                                     // pre_chmant[0][ch][bin] .................................................;
3540                                     // (0-9);
3541                                 }
3542                             }
3543                             aud_chan_blk[Pos].chahtinu = -1;
3544                         }
3545 
3546                         if (aud_blks[blk].cplinu && aud_chan_blk[Pos].chincpl && !got_cplchan)
3547                         {
3548                             size_t ncplmant = 12 * ncplsubnd;
3549                             if (cplahtinu==0)
3550                             {
3551                                 for (size_t bin = 0; bin < ncplmant; ++bin)
3552                                 {
3553                                     //TODO
3554                                     // cplmant[bin] ...........................;
3555                                     // (0-16);
3556                                 }
3557                                 got_cplchan = true;
3558                             }
3559                             else if (cplahtinu==1)
3560                             {
3561                                 Get_S1 (2, cplgaqmod,                   "cplgaqmod");
3562 
3563                                 if (lfeahtinu == 0)
3564                                 {
3565                                     for (size_t bin = 0; bin < lfeendmant; bin++)
3566                                         lfegaqbin[bin] = 0;
3567                                 }
3568                                 else
3569                                 {
3570                                     int8u endbap = 17;
3571                                     if (lfegaqmod<2)
3572                                         endbap = 12;
3573 
3574                                     for (size_t bin = 0; bin < lfeendmant; bin++)
3575                                     {
3576                                         if (hebap[bin] > 7 && hebap[bin] < endbap)
3577                                         {
3578                                             lfegaqbin[bin] = 1;
3579                                             ++lfeactivegaqbins;
3580                                         }
3581                                         else if (hebap[bin] >= endbap)
3582                                             lfegaqbin[bin] = -1;
3583                                         else
3584                                             lfegaqbin[bin] = 0;
3585                                     }
3586                                 }
3587 
3588                                 if (cplgaqmod>0x0 && cplgaqmod<0x3)
3589                                 {
3590                                     size_t cplgaqsections = cplactivegaqbins;
3591                                     for (size_t n = 0; n < cplgaqsections; n++)
3592                                         Skip_SB(                        "cplgaqgain[n]");
3593                                 }
3594                                 else if (cplgaqmod == 0x3)
3595                                 {
3596                                     size_t cplgaqsections = cplactivegaqbins / 3;
3597                                     if (cplactivegaqbins % 3)
3598                                         ++cplgaqsections;
3599 
3600                                     for (size_t n = 0; n < cplgaqsections; n++)
3601                                         Skip_S1(5,                      "cplgaqgain[n]");
3602                                 }
3603 
3604                                 for (size_t bin = 0; bin < ncplmant; ++bin)
3605                                 {
3606                                     if (cplgaqbin[bin])
3607                                     {
3608                                         for (size_t n = 0; n < 6; ++n)
3609                                         {
3610                                             //TODO
3611                                             // pre_cplmant[n][bin] ...........................;
3612                                             // (0-16);
3613                                         }
3614                                     }
3615                                     else
3616                                     {
3617                                         //TODO
3618                                         // pre_cplmant[0][bin] .................................................;
3619                                         // (0-9);
3620                                     }
3621                                 }
3622                                 got_cplchan = true;
3623                                 cplahtinu = -1;
3624                             }
3625                             else
3626                                 got_cplchan = true;
3627                         }
3628                     }
3629 
3630                     if (lfeon)
3631                     {
3632                         int8u nlfemant = 7;
3633                         if (lfeahtinu == 0)
3634                         {
3635                             for (size_t bin = 0; bin < nlfemant; ++bin)
3636                             {
3637                                 //TODO
3638                                 // lfemant[bin]..............................;
3639                                 // (0-16);
3640                             }
3641                         }
3642                         else if (lfeahtinu == 1)
3643                         {
3644                             size_t lfegaqsections = 0;
3645                             Get_S1 (2, lfegaqmod,                        "lfegaqmod");
3646 
3647                             if (lfeahtinu!=0)
3648                             {
3649                                 size_t sumgaqbins = 0;
3650                                 for (size_t bin = 0; bin < lfeendmant; bin++)
3651                                     sumgaqbins += lfegaqbin[bin];
3652 
3653                                 switch (lfegaqmod)
3654                                 {
3655                                     case 0:
3656                                     {
3657                                         lfegaqsections = 0;
3658                                         break;
3659                                     }
3660                                     case 1:
3661                                     case 2:
3662                                     {
3663                                         lfegaqsections = lfeactivegaqbins;
3664                                         break;
3665                                     }
3666                                     case 3:
3667                                     {
3668                                         lfegaqsections = lfeactivegaqbins / 3;
3669                                         if (lfeactivegaqbins % 3)
3670                                             lfegaqsections++;
3671                                         break;
3672                                     }
3673                                 };
3674                             }
3675 
3676                             if (lfegaqmod>0x0 && lfegaqmod<0x3)
3677                             {
3678                                 for (size_t n = 0; n < lfegaqsections; ++n)
3679                                     Skip_SB(                             "lfegaqgain[n]");
3680                             }
3681                             else if (lfegaqmod==0x3)
3682                             {
3683                                 for (size_t n = 0; n < lfegaqsections; ++n)
3684                                     Skip_S1(5,                           "lfegaqgain[n]");
3685                             }
3686 
3687                             for (size_t bin = 0; bin < nlfemant; ++bin)
3688                             {
3689                                 if (lfegaqbin[bin])
3690                                 {
3691                                     for (size_t n = 0; n < 6; ++n)
3692                                     {
3693                                         //TODO
3694                                         // pre_lfemant[n][bin] ..............................;
3695                                         // (0-16);
3696                                     }
3697                                 }
3698                                 else
3699                                 {
3700                                     //TODO
3701                                     // pre_lfemant[0][bin] ....................................................;
3702                                     // (0-9);
3703                                 }
3704                             }
3705 
3706                             lfeahtinu = (int8u)-1;
3707                         }
3708                     }
3709 
3710                 Element_End0();
3711             }
3712             //*/
3713     }
3714     else
3715         Skip_XX(Element_Size-Element_Offset,                        "Unknown");
3716 
3717     if (bsid<=0x10)
3718     {
3719         size_t BitsAtEnd=18; //auxdatae+errorcheck
3720         if (auxdatal!=(int16u)-1)
3721             BitsAtEnd+=auxdatal+14; //auxbits+auxdatal
3722         if (Data_BS_Remain()>=BitsAtEnd)
3723         {
3724             if (EMDF_RemainPos!=(size_t)-1 && BitsAtEnd<EMDF_RemainPos)
3725             {
3726                 Skip_BS(Data_BS_Remain()-EMDF_RemainPos,            bsid<=0x0A?"(Unparsed audblk(continue)+5*audblk+padding)":"(Unparsed bsi+6*audblk+padding)");
3727                 emdf();
3728                 Skip_BS(Data_BS_Remain()-BitsAtEnd,                 bsid<=0x0A?"(Unparsed audblk(continue)+5*audblk+padding)":"(Unparsed bsi+6*audblk+padding)");
3729             }
3730             else if (Data_BS_Remain()>BitsAtEnd)
3731                 Skip_BS(Data_BS_Remain()-BitsAtEnd,                 bsid<=0x0A?"(Unparsed audblk(continue)+5*audblk+padding)":"(Unparsed bsi+6*audblk+padding)");
3732             Element_Begin1("auxdata");
3733                 if (auxdatal!=(int16u)-1)
3734                 {
3735                     Skip_BS(auxdatal,                               "auxbits");
3736                     Skip_S2(14,                                     "auxdatal");
3737                 }
3738                 Skip_SB(                                            "auxdatae");
3739             Element_End0();
3740             Element_Begin1("errorcheck");
3741                 Skip_SB(                                            "encinfo");
3742                 BS_End();
3743                 Skip_B2(                                            "crc2");
3744             Element_End0();
3745         }
3746         else
3747             BS_End();
3748 
3749         if (Element_Offset<Element_Size)
3750             Skip_XX(Element_Size-Element_Offset,                    "Unknown");
3751         Element_Size=Element_Size_Save;
3752     }
3753 
3754     FILLING_BEGIN();
3755         if (bsid>0x10)
3756             return; //Not supported
3757 
3758         Formats[bsid<=0x09?0:1]++;
3759 
3760         // addbsi
3761         if (!joc_num_objects_map.empty() && addbsie && addbsi_Buffer_Size >= 2 && (addbsi_Buffer[0]&0x01))
3762         {
3763             joc_complexity_index_Stream = addbsi_Buffer[1];
3764         }
3765 
3766         //Information
3767         if (strmtyp>1)
3768             strmtyp=0; //TODO: check a file with strmtyp==2
3769         if (strmtyp==0)
3770             substreamid_Independant_Current=substreamid;
3771         if (bsid_Max==(int8u)-1 || bsid>bsid_Max)
3772             bsid_Max=bsid;
3773 
3774         //Specific to first frame
3775         if (!frmsizplus1_Max[substreamid_Independant_Current][strmtyp+substreamid])
3776         {
3777             frmsizplus1_Max[substreamid_Independant_Current][strmtyp+substreamid]=((bsid<=0x09)?(frmsizecod/2<19?AC3_BitRate[frmsizecod/2]*4:0):((frmsiz+1)*2));
3778             acmod_Max[substreamid_Independant_Current][strmtyp+substreamid]=acmod;
3779             lfeon_Max[substreamid_Independant_Current][strmtyp+substreamid]=lfeon;
3780             bsmod_Max[substreamid_Independant_Current][strmtyp+substreamid]=bsmod;
3781             dsurmod_Max[substreamid_Independant_Current][strmtyp+substreamid]=dsurmod;
3782             chanmape_Max[substreamid_Independant_Current][strmtyp+substreamid]=chanmape;
3783             chanmap_Max[substreamid_Independant_Current][strmtyp+substreamid]=chanmap;
3784 
3785             FirstFrame_Dolby.dialnorm=dialnorm;
3786             if (compre)
3787                 FirstFrame_Dolby.compr=compr;
3788             if (dynrnge)
3789                 FirstFrame_Dolby.dynrng=dynrng;
3790             FirstFrame_Dolby.compre=compre;
3791             FirstFrame_Dolby.dynrnge=dynrnge;
3792         }
3793 
3794         //Stats
3795         if (dialnorms.empty())
3796             dialnorms.resize(32);
3797         if (dialnorm!=(int8u)-1)
3798             dialnorms[dialnorm]++;
3799         if (compre)
3800         {
3801             if (comprs.empty())
3802                 comprs.resize(256);
3803             if (compr!=(int8u)-1)
3804                 comprs[compr]++;
3805         }
3806         if (dynrnge)
3807         {
3808             //Saving new value
3809             dynrnge_Exists=true;
3810         }
3811         if (!dynrnge)
3812             dynrng=0;
3813         if (dynrngs.empty())
3814             dynrngs.resize(256);
3815         if (dynrng!=(int8u)-1)
3816             dynrngs[dynrng]++;
3817     FILLING_END();
3818 }
3819 
3820 //---------------------------------------------------------------------------
emdf()3821 void File_Ac3::emdf()
3822 {
3823     //JOC reinit
3824     joc_complexity_index_Stream=(int8u)-1;
3825     num_dynamic_objects=(int8u)-1;
3826     nonstd_bed_channel_assignment_mask=(int32u)-1;
3827 
3828     Element_Begin1("emdf");
3829     emdf_sync();
3830     emdf_container();
3831     Element_End0();
3832 }
3833 
3834 //---------------------------------------------------------------------------
emdf_sync()3835 void File_Ac3::emdf_sync()
3836 {
3837     int16u emdf_container_length;
3838     Element_Begin1("emdf_sync");
3839     Skip_S2(16,                                                 "syncword");
3840     Get_S2 (16, emdf_container_length,                          "emdf_container_length");
3841     Element_End0();
3842 
3843     RemainAfterEMDF=Data_BS_Remain()-emdf_container_length*8; //emdf_container_length coherency was already tested in sync layer
3844 }
3845 
3846 //---------------------------------------------------------------------------
emdf_container()3847 void File_Ac3::emdf_container()
3848 {
3849     size_t Start = Data_BS_Remain();
3850     int32u version, key_id;
3851     Element_Begin1("emdf_container");
3852     Get_S4 (2, version,                                         "emdf_version");
3853     if (version == 3)
3854     {
3855         int32u add;
3856         Get_V4(2, add,                                          "emdf_version addition");
3857         version += add;
3858     }
3859     if (version)
3860     {
3861         Skip_BS(Data_BS_Remain()-RemainAfterEMDF,               "(Unparsed emdf_container data)");
3862         Element_End0();
3863         return;
3864     }
3865 
3866     Get_S4 (3, key_id,                                          "key_id");
3867     if (key_id == 7)
3868     {
3869         int32u add;
3870         Get_V4 (2, add,                                         "key_id addition");
3871         key_id += add;
3872     }
3873 
3874     int32u emdf_payload_id = 0;
3875 
3876     for(;;)
3877     {
3878         Element_Begin1("emdf_payload");
3879         Get_S4 (5, emdf_payload_id,                             "emdf_payload_id");
3880         if (emdf_payload_id==0x1F)
3881         {
3882             int32u add;
3883             Get_V4 (5, add,                                     "emdf_payload_id addition");
3884             emdf_payload_id += add;
3885         }
3886 
3887         if (emdf_payload_id<16)
3888             Element_Info1(Ac3_emdf_payload_id[emdf_payload_id]);
3889         if (emdf_payload_id == 0x00)
3890         {
3891             Element_End0();
3892             break;
3893         }
3894 
3895         emdf_payload_config();
3896 
3897         int32u emdf_payload_size = 0;
3898         Get_V4 (8, emdf_payload_size,                           "emdf_payload_size");
3899         size_t emdf_payload_End=Data_BS_Remain()-emdf_payload_size*8; //emdf_payload_size coherency was already tested in sync layer
3900 
3901         Element_Begin1("emdf_payload_bytes");
3902             switch (emdf_payload_id)
3903             {
3904                 case 11: object_audio_metadata_payload(); break;
3905                 case 14: joc(); break;
3906                 default: Skip_BS(emdf_payload_size*8,           "(Unknown)");
3907             }
3908             if (Data_BS_Remain() - emdf_payload_End < 8)
3909             {
3910                 int8u padding;
3911                 Peek_S1(Data_BS_Remain() - emdf_payload_End, padding);
3912                 if (!padding)
3913                     Skip_S1(Data_BS_Remain() - emdf_payload_End, "padding");
3914             }
3915             if (Data_BS_Remain() > emdf_payload_End)
3916             {
3917                 Skip_BS(Data_BS_Remain() - emdf_payload_End,    "(Unparsed emdf_payload bytes)");
3918             }
3919             else if (Data_BS_Remain() < emdf_payload_End)
3920             {
3921                 //There is a problem, too many bits were consumed by the parser. //TODO: prevent the parser to consume more bits than count of bits in this element
3922                 if (Data_BS_Remain() >= RemainAfterEMDF)
3923                     Skip_BS(Data_BS_Remain() - RemainAfterEMDF, "(Problem during emdf_payload parsing)");
3924                 else
3925                     Skip_BS(Data_BS_Remain(),                   "(Problem during emdf_payload parsing, going to end directly)");
3926                 Element_End0();
3927                 Element_End0();
3928                 break;
3929             }
3930         Element_End0();
3931 
3932         Element_End0();
3933     }
3934 
3935     emdf_protection();
3936     Element_End0();
3937 }
3938 
3939 //---------------------------------------------------------------------------
emdf_payload_config()3940 void File_Ac3::emdf_payload_config()
3941 {
3942     Element_Begin1("emdf_payload_config");
3943     bool smploffste = false;
3944     Get_SB (smploffste,                                         "smploffste");
3945     if (smploffste)
3946     {
3947         Skip_S2(11,                                             "smploffst");
3948         Skip_SB(                                                "reserved");
3949     }
3950 
3951     TEST_SB_SKIP(                                               "duratione");
3952         Skip_V4(11,                                             "duration");
3953     TEST_SB_END();
3954     TEST_SB_SKIP(                                               "groupide");
3955         Skip_V4(2,                                              "groupid");
3956     TEST_SB_END();
3957     TEST_SB_SKIP(                                               "codecdatae");
3958         Skip_S1(8,                                              "reserved");
3959     TEST_SB_END();
3960 
3961     bool discard_unknown_payload = false;
3962     Get_SB(discard_unknown_payload,                             "discard_unknown_payload");
3963     if (!discard_unknown_payload)
3964     {
3965         bool payload_frame_aligned = false;
3966         if (!smploffste)
3967         {
3968             Get_SB (payload_frame_aligned,                      "payload_frame_aligned");
3969             if (payload_frame_aligned)
3970             {
3971                 Skip_SB(                                        "create_duplicate");
3972                 Skip_SB(                                        "remove_duplicate");
3973             }
3974         }
3975 
3976         if (smploffste || payload_frame_aligned)
3977         {
3978             Skip_S1(5,                                          "priority");
3979             Skip_S1(2,                                          "proc_allowed");
3980         }
3981     }
3982     Element_End0();
3983 }
3984 
3985 //---------------------------------------------------------------------------
emdf_protection()3986 void File_Ac3::emdf_protection()
3987 {
3988     int8u len_primary = 0, len_second = 0;
3989     Element_Begin1("emdf_protection");
3990     Get_S1(2, len_primary,                                      "protection_length_primary");
3991     Get_S1(2, len_second,                                       "protection_length_secondary");
3992 
3993     switch (len_primary)
3994     {
3995         //case 0: break; //protection_length_primary coherency was already tested in sync layer
3996         case 1: len_primary = 8; break;
3997         case 2: len_primary = 32; break;
3998         case 3: len_primary = 128; break;
3999         default:; //Cannot append, read only 2 bits
4000     };
4001     switch (len_second)
4002     {
4003         case 0: len_second = 0; break;
4004         case 1: len_second = 8; break;
4005         case 2: len_second = 32; break;
4006         case 3: len_second = 128; break;
4007         default:; //Cannot append, read only 2 bits
4008     };
4009     Skip_BS(len_primary,                                        "protection_bits_primary");
4010     if (len_second)
4011         Skip_BS(len_primary,                                    "protection_bits_secondary");
4012 
4013     Element_End0();
4014 }
4015 
4016 //---------------------------------------------------------------------------
object_audio_metadata_payload()4017 void File_Ac3::object_audio_metadata_payload()
4018 {
4019     Element_Begin1("object_audio_metadata_payload");
4020     int8u oa_md_version_bits;
4021     Get_S1 (2, oa_md_version_bits,                              "oa_md_version_bits");
4022     if (oa_md_version_bits == 0x3)
4023     {
4024         int8u oa_md_version_bits_ext;
4025         Get_S1 (3, oa_md_version_bits_ext,                      "oa_md_version_bits_ext");
4026         oa_md_version_bits += oa_md_version_bits_ext;
4027     }
4028 
4029     int8u object_count_bits;
4030     Get_S1 (5, object_count_bits,                               "object_count_bits");
4031     num_dynamic_objects = object_count_bits + 1;
4032     if (object_count_bits == 0x1F)
4033     {
4034         int8u object_count_bits_ext;
4035         Get_S1 (7, object_count_bits_ext,                       "object_count_bits_ext");
4036         num_dynamic_objects += object_count_bits_ext;
4037     }
4038 
4039     program_assignment();
4040 
4041     //TODO: next
4042 
4043     Element_End0();
4044 }
4045 
4046 //---------------------------------------------------------------------------
program_assignment()4047 void File_Ac3::program_assignment()
4048 {
4049     Element_Begin1("program_assignment");
4050     bool b_dyn_object_only_program = false;
4051     Get_SB (b_dyn_object_only_program,                          "b_dyn_object_only_program");
4052     if (b_dyn_object_only_program)
4053     {
4054         bool b_lfe_present;
4055         Get_SB (b_lfe_present,                                  "b_lfe_present");
4056         if (b_lfe_present)
4057         {
4058             nonstd_bed_channel_assignment_mask=(1<<3);
4059             if (num_dynamic_objects!=(int8u)-1)
4060                 num_dynamic_objects--;
4061         }
4062     }
4063     else
4064     {
4065         int8u content_description_mask;
4066         Get_S1 (4, content_description_mask,                    "content_description_mask");
4067         if (content_description_mask & 0x1)
4068         {
4069             bool b_bed_object_chan_distribute, b_multiple_bed_instances_present;
4070 
4071             Get_SB (b_bed_object_chan_distribute,               "b_bed_object_chan_distribute");
4072             Get_SB (b_multiple_bed_instances_present,           "b_multiple_bed_instances_present");
4073             int32u num_bed_instances = 1;
4074             if (b_multiple_bed_instances_present)
4075             {
4076                 int8u num_bed_instances_bits = 0;
4077                 Get_S1 (3, num_bed_instances_bits,              "num_bed_instances_bits");
4078                 num_bed_instances = num_bed_instances_bits + 2;
4079             }
4080 
4081             for (int32u bed = 0; bed < num_bed_instances; ++bed)
4082             {
4083                 Element_Begin1("Bed");
4084                 bool b_lfe_only = true;
4085                 Get_SB (b_lfe_only,                             "b_lfe_only");
4086                 if (!b_lfe_only)
4087                 {
4088                     bool b_standard_chan_assign;
4089                     Get_SB (b_standard_chan_assign,             "b_standard_chan_assign");
4090                     if (b_standard_chan_assign)
4091                     {
4092                         int16u bed_channel_assignment_mask;
4093                         Get_S2 (10, bed_channel_assignment_mask, "bed_channel_assignment_mask");
4094                         nonstd_bed_channel_assignment_mask=AC3_bed_channel_assignment_mask_2_nonstd(bed_channel_assignment_mask);
4095                     }
4096                     else
4097                         Get_S3 (17, nonstd_bed_channel_assignment_mask, "nonstd_bed_channel_assignment_mask");
4098                 }
4099                 Element_End0();
4100             }
4101         }
4102 
4103         if (content_description_mask & 0x2)
4104             Skip_S1(3,                                          "intermediate_spatial_format_idx");
4105 
4106         if (content_description_mask & 0x4)
4107         {
4108             int8u num_dynamic_objects_bits;
4109             Get_S1(5, num_dynamic_objects_bits,                 "num_dynamic_objects_bits");
4110             if (num_dynamic_objects_bits == 0x1F)
4111             {
4112                 int8u num_dynamic_objects_bits_ext = 0;
4113                 Get_S1 (7, num_dynamic_objects_bits_ext,        "num_dynamic_objects_bits_ext");
4114                 num_dynamic_objects_bits += num_dynamic_objects_bits_ext;
4115             }
4116             num_dynamic_objects = num_dynamic_objects_bits + 1;
4117         }
4118         else
4119             num_dynamic_objects = 0;
4120 
4121         if (content_description_mask & 0x8)
4122         {
4123             int8u reserved_data_size_bits;
4124             Get_S1 (4, reserved_data_size_bits,                 "reserved_data_size_bits");
4125             int8u padding = 8 - (reserved_data_size_bits % 8);
4126             Skip_S1(reserved_data_size_bits,                    "reserved_data()");
4127             Skip_S1(padding,                                    "padding");
4128         }
4129     }
4130 
4131     Element_End0();
4132 }
4133 
4134 //---------------------------------------------------------------------------
joc()4135 void File_Ac3::joc()
4136 {
4137     Element_Begin1("joc");
4138     joc_header();
4139     joc_info();
4140     joc_data();
4141     if (joc_ext_config_idx > 0)
4142         joc_ext_data();
4143     Element_End0();
4144 }
4145 
4146 //---------------------------------------------------------------------------
joc_header()4147 void File_Ac3::joc_header()
4148 {
4149     Element_Begin1("joc_header");
4150         Skip_S1(3,                                              "joc_dmx_config_idx");
4151         int8u joc_num_objects_bits = 0;
4152         Get_S1 (6, joc_num_objects_bits,                        "joc_num_objects_bits");
4153         joc_num_objects = joc_num_objects_bits + 1;
4154         joc_num_objects_map[joc_num_objects] ++;
4155         Get_S1 (3, joc_ext_config_idx,                          "joc_ext_config_idx");
4156     Element_End0();
4157 }
4158 
4159 //---------------------------------------------------------------------------
joc_info()4160 void File_Ac3::joc_info()
4161 {
4162     Element_Begin1("joc_info");
4163     int8u joc_clipgain_x_bits, joc_clipgain_y_bits;
4164     int16u joc_seq_count_bits;
4165     Get_S1 (3, joc_clipgain_x_bits,                                 "joc_clipgain_x_bits");
4166     Get_S1 (5, joc_clipgain_y_bits,                                 "joc_clipgain_y_bits");
4167     Get_S2 (10, joc_seq_count_bits,                                 "joc_seq_count_bits");
4168     for (int8u obj = 0; obj < joc_num_objects; obj++)
4169     {
4170         TEST_SB_SKIP("b_joc_obj_present[obj]");
4171             //TODO
4172         TEST_SB_END();
4173     }
4174     Element_End0();
4175 }
4176 
4177 //---------------------------------------------------------------------------
joc_data_point_info()4178 void File_Ac3::joc_data_point_info()
4179 {
4180     Element_Begin1("joc_data_point_info");
4181     //TODO
4182     Element_End0();
4183 }
4184 
4185 //---------------------------------------------------------------------------
joc_data()4186 void File_Ac3::joc_data()
4187 {
4188     Element_Begin1("joc_data");
4189     //TODO
4190     Element_End0();
4191 }
4192 
4193 //---------------------------------------------------------------------------
joc_ext_data()4194 void File_Ac3::joc_ext_data()
4195 {
4196     Element_Begin1("joc_ext_data");
4197     //TODO
4198     Element_End0();
4199 }
4200 
4201 //---------------------------------------------------------------------------
HD()4202 void File_Ac3::HD()
4203 {
4204     //Parsing
4205     int32u Synch;
4206     Peek_B3(Synch);
4207     if (Synch==0xF8726F)
4208     {
4209         if (Buffer_Offset+28>Buffer_Size)
4210         {
4211             Trusted_IsNot("Not enough data");
4212             return; //Need more data
4213         }
4214 
4215         //Testing
4216         /* Not working
4217         int16u CRC_16_Table_HD[256];
4218         CRC16_Init(CRC_16_Table_HD, 0x002D);
4219 
4220         int16u CRC_16=0x0000;
4221         const int8u* CRC_16_Buffer=Buffer+Buffer_Offset;
4222         while(CRC_16_Buffer<Buffer+Buffer_Offset+24)
4223         {
4224             CRC_16=(CRC_16<<8) ^ CRC_16_Table_HD[(CRC_16>>8)^(*CRC_16_Buffer)];
4225             CRC_16_Buffer++;
4226         }
4227         CRC_16^=LittleEndian2int16u(Buffer+Buffer_Offset+24);
4228         */
4229 
4230         Element_Info1("major_sync");
4231         Element_Begin1("major_sync_info");
4232         int32u format_sync;
4233         Get_B4(format_sync,                                     "major_sync");
4234         HD_StreamType=(int8u)format_sync; Param_Info1(AC3_HD_StreamType(HD_StreamType));
4235 
4236         if ((HD_StreamType&0xFE)!=0xBA)
4237         {
4238             Skip_XX(Element_Size-Element_Offset,                "Data");
4239             return;
4240         }
4241         HD_format_info();
4242         Skip_B2(                                                "signature");
4243         Get_B2 (HD_flags,                                       "flags");
4244         Skip_B2(                                                "reserved");
4245         BS_Begin();
4246         Get_SB (    HD_IsVBR,                                   "variable_rate");
4247         Get_S2 (15, HD_BitRate_Max,                             "peak_data_rate"); Param_Info2((HD_BitRate_Max*(AC3_HD_SamplingRate(HD_SamplingRate2)?AC3_HD_SamplingRate(HD_SamplingRate2):AC3_HD_SamplingRate(HD_SamplingRate1))+8)>>4, " bps");
4248         Get_S1 ( 4, HD_SubStreams_Count,                        "substreams");
4249         Skip_S1( 2,                                             "reserved");
4250         Skip_S1( 2,                                             "extended_substream_info");
4251         if (HD_StreamType==0xBA)
4252         {
4253             Element_Begin1("substream_info");
4254                 Get_SB (    HD_HasAtmos,                        "16-channel presentation is present");
4255                 Skip_S1(3,                                      "8-ch presentation");
4256                 Skip_S1(2,                                      "6-ch presentation");
4257                 Skip_S1(2,                                      "reserved");
4258             Element_End0();
4259         }
4260         else
4261             Skip_S1(8,                                          "Unknown");
4262         BS_End();
4263         Element_Begin1("channel_meaning");
4264             Skip_B1(                                            "Unknown");
4265             Skip_B1(                                            "Unknown");
4266             Skip_B1(                                            "Unknown");
4267             Skip_B1(                                            "Unknown");
4268             Skip_B1(                                            "Unknown");
4269             Skip_B1(                                            "Unknown");
4270             Skip_B1(                                            "Unknown");
4271             if (HD_StreamType==0xBA)
4272             {
4273                 BS_Begin();
4274                 Skip_S1( 7,                                     "Unknown");
4275                 bool HasExtend;
4276                 Get_SB (    HasExtend,                          "extra_channel_meaning_present");
4277                 BS_End();
4278                 if (HasExtend)
4279                 {
4280                     unsigned char Extend = 0;
4281                     unsigned char Unknown = 0;
4282                     bool HasContent = false;
4283                     BS_Begin();
4284                     Get_S1( 4, Extend,                          "extra_channel_meaning_length");
4285                     size_t After=(((size_t)Extend)+1)*16-4;
4286                     if (After>=Data_BS_Remain())
4287                         After=0;
4288                     else
4289                         After=Data_BS_Remain()-After;
4290                     if (HD_HasAtmos)
4291                     {
4292                         Element_Begin1("16ch_channel_meaning");
4293                         Skip_S1(5,                              "16ch_dialogue_norm");
4294                         Skip_S1(6,                              "16ch_mix_level");
4295                         Get_S1 (5, num_dynamic_objects,         "16ch_channel_count");
4296                         num_dynamic_objects++;
4297                         program_assignment();
4298                         Element_End0();
4299                     }
4300                     int16u padding;
4301                     Peek_S2(Data_BS_Remain()%16, padding);
4302                     if (Data_BS_Remain()-Data_BS_Remain()%16==After && !padding)
4303                         Skip_BS(Data_BS_Remain()%16,            "padding");
4304                     if (Data_BS_Remain()>After)
4305                         Skip_BS(Data_BS_Remain()-After,         "reserved");
4306                     BS_End();
4307                 }
4308             }
4309             else
4310                 Skip_B1(                                        "Unknown");
4311         Element_End0();
4312         Skip_B2(                                                "major_sync_info_CRC");
4313         Element_End0();
4314     }
4315     else if (!HD_MajorSync_Parsed)
4316     {
4317         return; // Wait for major sync
4318     }
4319 
4320     int64u PosBeforeDirectory=Element_Offset;
4321     BS_Begin();
4322     for (int8u i=0; i<HD_SubStreams_Count; i++)
4323     {
4324         Element_Begin1("substream_directory");
4325         bool extra_substream_word, restart_nonexistent;
4326         Get_SB (extra_substream_word,                           "extra_substream_word");
4327         Get_SB (restart_nonexistent,                            "restart_nonexistent");
4328         if ((!restart_nonexistent && Synch!=0xF8726F) || (restart_nonexistent && Synch==0xF8726F))
4329         {
4330             Element_End0();
4331             return;
4332         }
4333         Skip_SB(                                                "crc_present");
4334         Skip_SB(                                                "reserved");
4335         Skip_S2(12,                                             "substream_end_ptr");
4336         if (extra_substream_word)
4337         {
4338             Skip_S2(9,                                          "drc_gain_update");
4339             Skip_S1(3,                                          "drc_time_update");
4340             Skip_S1(4,                                          "reserved");
4341         }
4342         Element_End0();
4343     }
4344     BS_End();
4345 
4346     FILLING_BEGIN();
4347         //CRC compute
4348         size_t Size=(size_t)(Element_Offset-PosBeforeDirectory);
4349         int8u crc=0;
4350         for (int8u i=0; i<4; i++)
4351         {
4352             int8u Value=Buffer[Buffer_Offset-4+i];
4353             crc^=(Value&0xF);
4354             Value>>=4;
4355             crc^=Value;
4356         }
4357         for (int8u i=0; i<Size; i++)
4358         {
4359             int8u Value=Buffer[Buffer_Offset+(size_t)(Element_Offset-Size+i)];
4360             crc^=(Value&0xF);
4361             Value>>=4;
4362             crc^=Value;
4363         }
4364         if (crc!=0xF)
4365         {
4366             return;
4367         }
4368         HD_MajorSync_Parsed=true;
4369 
4370         if (HD_SubStreams_Count==1 && HD_StreamType==0xBB) //MLP with only 1 stream
4371         {
4372             HD_Resolution2=HD_Resolution1;
4373             HD_SamplingRate2=HD_SamplingRate1;
4374         }
4375     FILLING_END();
4376 
4377 
4378     /*
4379     if (HD_MajorSync_Parsed)
4380     {
4381         Element_Begin1("Sizes");
4382         std::vector<int16u> Sizes;
4383         for (int8u Pos=0; Pos<HD_SubStreams_Count; Pos++)
4384         {
4385             Element_Begin1("Size");
4386             int16u Size;
4387             bool HD_Unknown1_Present, HD_NoRestart, HD_ExtraParity;
4388             BS_Begin();
4389             Get_SB (    HD_Unknown1_Present,                    "Unknown present"); //Only TrueHD
4390             Get_SB (    HD_NoRestart,                           "No restart"); //Not present if MajorSync, present if no MajorSync
4391             Get_SB (    HD_ExtraParity,                         "Extra parity information");
4392             Skip_SB(                                            "Unknown");
4393             Get_S2 (12, Size,                                   "Size");
4394             BS_End();
4395             if (HD_Unknown1_Present)
4396                 Skip_B2(                                        "Unknown");
4397             Sizes.push_back(Size);
4398             Element_End0();
4399         }
4400         Element_End0();
4401 
4402         int64u Element_Offset_Begin=Element_Offset;
4403         for (int8u Pos=0; Pos<HD_SubStreams_Count; Pos++)
4404         {
4405             Element_Begin1("Block");
4406             bool DecodingParameterBlockPresent;
4407             BS_Begin();
4408             Get_SB (DecodingParameterBlockPresent,              "Decoding parameter block is present");
4409             if (DecodingParameterBlockPresent)
4410             {
4411                 TEST_SB_SKIP(                                   "Restart header");
4412                     int16u SyncWord;
4413                     int8u max_matrix_channel;
4414                     Get_S2(13, SyncWord,                        "SyncWord");
4415                     if (SyncWord==0x18F5)
4416                     {
4417                         Skip_SB(                                "noise_type"); //Only for TrueHD
4418                         Skip_S2(16,                             "Output timestamp");
4419                         Skip_S1( 4,                             "min_channel");
4420                         Skip_S1( 4,                             "max_channel");
4421                         Get_S1 ( 4, max_matrix_channel,         "max_matrix_channel");
4422                         Skip_S1( 4,                             "noise_shift");
4423                         Skip_S3(23,                             "noisegen_seed");
4424                         Skip_S3(19,                             "unknown");
4425                         Skip_SB(                                "data_check_present");
4426                         Skip_S1( 8,                             "lossless_check");
4427                         Skip_S2(16,                             "unknown");
4428                         for (int8u matrix_channel=0; matrix_channel<max_matrix_channel; matrix_channel++)
4429                             Skip_S1(6,                          "ch_assign");
4430                         Skip_S1( 8,                             "checksum");
4431                     }
4432                 TEST_SB_END();
4433             }
4434             BS_End();
4435             Skip_XX(Element_Offset_Begin+Sizes[Pos]*2-Element_Offset, "Data");
4436             Element_End0();
4437         }
4438     }
4439     else
4440         Skip_XX(Element_Size-Element_Offset,                    "Waiting for MajorSync...");
4441     */
4442         Skip_XX(Element_Size-Element_Offset,                    "(Data)");
4443 
4444     FILLING_BEGIN_PRECISE();
4445         if (Frame_Count==0)
4446             PTS_Begin=FrameInfo.PTS;
4447         Frame_Count++;
4448         Frame_Count_InThisBlock++;
4449         if (Frame_Count_NotParsedIncluded!=(int64u)-1)
4450             Frame_Count_NotParsedIncluded++;
4451         FrameInfo.DUR=833333;
4452         int64u HD_SamplingRate=AC3_HD_SamplingRate(HD_SamplingRate1);
4453         if (HD_SamplingRate && HD_SamplingRate!=48000)
4454         {
4455             FrameInfo.DUR*=48000;
4456             FrameInfo.DUR/=HD_SamplingRate;
4457         }
4458         if (FrameInfo.DTS!=(int64u)-1)
4459             FrameInfo.DTS+=FrameInfo.DUR;
4460         if (FrameInfo.PTS!=(int64u)-1)
4461             FrameInfo.PTS+=FrameInfo.DUR;
4462 
4463         //Filling
4464         if (!Status[IsAccepted])
4465         {
4466             Accept("AC-3");
4467             if (Frame_Count_Valid>1 && Frame_Count_Valid<10000)
4468                 Frame_Count_Valid*=32;
4469         }
4470         if (!Status[IsFilled] && !Core_IsPresent && Frame_Count>=Frame_Count_Valid)
4471         {
4472             Fill("AC-3");
4473 
4474             //No more need data
4475             if (!IsSub && Config->ParseSpeed<1.0)
4476                 Finish("AC-3");
4477         }
4478     FILLING_END();
4479 }
4480 
HD_format_info()4481 void File_Ac3::HD_format_info()
4482 {
4483     if (HD_StreamType==0xBA)
4484     {
4485         Element_Begin1("format_info");
4486         BS_Begin();
4487         Get_S1 ( 4, HD_SamplingRate1,                           "audio_sampling_frequency"); Param_Info2(AC3_HD_SamplingRate(HD_SamplingRate1), " Hz");
4488         Skip_SB(                                                "6ch_multichannel_type");
4489         Skip_SB(                                                "8ch_multichannel_typ");
4490         Skip_S1( 2,                                             "reserved");
4491         Skip_S1( 2,                                             "2ch_presentation_channel_modifier");
4492         Skip_S1( 2,                                             "6ch_presentation_channel_modifier");
4493         Get_S1 ( 5, HD_Channels1,                               "6ch_presentation_channel_assignment"); Param_Info1(AC3_TrueHD_Channels(HD_Channels1)); Param_Info1(Ztring().From_UTF8(AC3_TrueHD_Channels_Positions(HD_Channels1)));
4494         Skip_S1( 2,                                             "8ch_presentation_channel_modifier");
4495         Get_S2 (13, HD_Channels2,                               "8ch_presentation_channel_assignment"); Param_Info1(AC3_TrueHD_Channels(HD_Channels2)); Param_Info1(Ztring().From_UTF8(AC3_TrueHD_Channels_Positions(HD_Channels2)));
4496         BS_End();
4497         HD_Resolution2=HD_Resolution1=24; //Not sure
4498         HD_SamplingRate2=HD_SamplingRate1;
4499         Element_End0();
4500     }
4501     if (HD_StreamType==0xBB)
4502     {
4503         BS_Begin();
4504         Get_S1 ( 4, HD_Resolution1,                             "Resolution1"); Param_Info2(AC3_MLP_Resolution[HD_Resolution1], " bits");
4505         Get_S1 ( 4, HD_Resolution2,                             "Resolution2"); Param_Info2(AC3_MLP_Resolution[HD_Resolution2], " bits");
4506         Get_S1 ( 4, HD_SamplingRate1,                           "Sampling rate"); Param_Info2(AC3_HD_SamplingRate(HD_SamplingRate1), " Hz");
4507         Get_S1 ( 4, HD_SamplingRate2,                           "Sampling rate"); Param_Info2(AC3_HD_SamplingRate(HD_SamplingRate2), " Hz");
4508         Skip_S1(11,                                             "Unknown");
4509         Get_S1 ( 5, HD_Channels1,                               "Channels"); Param_Info1(AC3_MLP_Channels[HD_Channels1]);
4510         BS_End();
4511         HD_Channels2=HD_Channels1;
4512     }
4513 }
4514 
4515 //---------------------------------------------------------------------------
TimeStamp()4516 void File_Ac3::TimeStamp()
4517 {
4518     // Format looks like a Sync word 0x0110 then SMPTE ST 339 Time stamp
4519 
4520     //Parsing
4521     int16u SampleNumber;
4522     int8u H1, H2, M1, M2, S1, S2, F1, F2, FrameRate;
4523     bool DropFrame;
4524     Skip_B2(                                                    "Sync word");
4525     BS_Begin();
4526     Skip_S2(10,                                                 "H");
4527     Get_S1 ( 2, H1,                                             "H");
4528     Get_S1 ( 4, H2,                                             "H");
4529     Skip_S2( 9,                                                 "M");
4530     Get_S1 ( 3, M1,                                             "M");
4531     Get_S1 ( 4, M2,                                             "M");
4532     Skip_S2( 9,                                                 "S");
4533     Get_S1 ( 3, S1,                                             "S");
4534     Get_S1 ( 4, S2,                                             "S");
4535     Skip_S2( 9,                                                 "F");
4536     Get_SB (    DropFrame,                                      "Drop frame");
4537     Get_S1 ( 2, F1,                                             "F");
4538     Get_S1 ( 4, F2,                                             "F");
4539     Get_S2 (16, SampleNumber,                                   "Sample number");
4540     Skip_S2( 9,                                                 "Unknown");
4541     Skip_SB(                                                    "Status");
4542     Get_S1 ( 4, FrameRate,                                      "Frame rate"); Param_Info1(Mpegv_frame_rate[FrameRate]);
4543     Skip_SB(                                                    "Status");
4544     Skip_SB(                                                    "Drop frame");
4545     BS_End();
4546     Skip_B2(                                                    "User private");
4547 
4548     FILLING_BEGIN();
4549         TimeCode Temp(H1*10+H2, M1*10+M2, S1*10+S2, F1*10+F2, (int8u)float64_int64s(Mpegv_frame_rate[FrameRate]), DropFrame);
4550         if (float64_int64s(Mpegv_frame_rate[FrameRate])!=Mpegv_frame_rate[FrameRate])
4551             Temp.FramesPerSecond_Is1001=true;
4552         Temp.MoreSamples=SampleNumber;
4553         #ifdef MEDIAINFO_TRACE
4554            Element_Info1(Temp.ToString());
4555         #endif //MEDIAINFO_TRACE
4556         if (TimeStamp_Count==0)
4557         {
4558             TimeStamp_FirstFrame=Temp;
4559         }
4560         TimeStamp_IsParsing=false;
4561         TimeStamp_Parsed=true;
4562         TimeStamp_Count++;
4563     FILLING_END();
4564 }
4565 
4566 //---------------------------------------------------------------------------
dac3()4567 void File_Ac3::dac3()
4568 {
4569     BS_Begin();
4570     Get_S1 (2, fscod,                                           "fscod");
4571     Get_S1 (5, bsid,                                            "bsid");
4572     Get_S1 (3, bsmod_Max[0][0],                                 "bsmod");
4573     Get_S1 (3, acmod_Max[0][0],                                 "acmod");
4574     Get_SB (   lfeon_Max[0][0],                                 "lfeon");
4575     Get_S1 (5, frmsizecod,                                      "bit_rate_code"); frmsizecod*=2;
4576     Skip_S1(5,                                                  "reserved");
4577     BS_End();
4578 
4579     MustParse_dac3=false;
4580     dxc3_Parsed=true;
4581 }
4582 
4583 //---------------------------------------------------------------------------
dec3()4584 void File_Ac3::dec3()
4585 {
4586     //Parsing
4587     BS_Begin();
4588     int8u num_ind_sub;
4589     Skip_S2(13,                                                 "data_rate");
4590     Get_S1 ( 3, num_ind_sub,                                    "num_ind_sub");
4591     for (int8u Pos=0; Pos<=num_ind_sub; Pos++)
4592     {
4593         Element_Begin1("independent substream");
4594         int8u num_dep_sub;
4595         Get_S1 (2, fscod,                                       "fscod");
4596         Get_S1 (5, bsid,                                        "bsid");
4597         Skip_SB(                                                "reserved");
4598         Skip_SB(                                                "asvc");
4599         Get_S1 (3, bsmod_Max[Pos][0],                           "bsmod");
4600         Get_S1 (3, acmod_Max[Pos][0],                           "acmod");
4601         Get_SB (   lfeon_Max[Pos][0],                           "lfeon");
4602         Skip_S1(3,                                              "reserved");
4603         Get_S1 (4, num_dep_sub,                                 "num_dep_sub");
4604         if (num_dep_sub>0)
4605             Skip_S2(9,                                          "chan_loc");
4606         else
4607             Skip_SB(                                            "reserved");
4608         Element_End0();
4609     }
4610     if (Data_BS_Remain())
4611     {
4612         Skip_S1( 7,                                             "reserved");
4613         TEST_SB_SKIP(                                           "flag_ec3_extension_type_joc");
4614             Get_S1 ( 8, joc_complexity_index_Container,         "joc_complexity_index");
4615         TEST_SB_END();
4616     }
4617     BS_End();
4618     if (Element_Offset<Element_Size)
4619         Skip_XX(Element_Size-Element_Offset,                    "reserved");
4620 
4621     MustParse_dec3=false;
4622     dxc3_Parsed=true;
4623 }
4624 
4625 //---------------------------------------------------------------------------
dmlp()4626 void File_Ac3::dmlp()
4627 {
4628     //Parsing
4629     HD_StreamType=0xBA;
4630     HD_format_info();
4631     BS_Begin();
4632     Get_S2 (15, HD_BitRate_Max,                                 "peak_data_rate"); Param_Info2((HD_BitRate_Max*(AC3_HD_SamplingRate(HD_SamplingRate2)?AC3_HD_SamplingRate(HD_SamplingRate2):AC3_HD_SamplingRate(HD_SamplingRate1))+8)>>4, " bps");
4633     Skip_S8(33,                                                 "reserved");
4634     BS_End();
4635     if (Element_Offset<Element_Size)
4636         Skip_XX(Element_Size-Element_Offset,                    "unknown");
4637 
4638     FILLING_BEGIN()
4639         //Configure
4640         MustParse_dmlp=false;
4641         MustSynchronize=true;
4642         Frame_Count_Valid=1;
4643     FILLING_ELSE()
4644         Reject();
4645     FILLING_END()
4646 }
4647 
4648 //---------------------------------------------------------------------------
FrameSynchPoint_Test()4649 bool File_Ac3::FrameSynchPoint_Test()
4650 {
4651     if (Save_Buffer)
4652         return true; //Test already made by Synchronize()
4653 
4654     if (Buffer[Buffer_Offset  ]==0x0B
4655      && Buffer[Buffer_Offset+1]==0x77) //AC-3
4656     {
4657         bsid=CC1(Buffer+Buffer_Offset+5)>>3;
4658         int16u  Size=0;
4659         if (bsid<=0x09)
4660         {
4661             int8u fscod     =(CC1(Buffer+Buffer_Offset+4)>>6)&0x03;
4662             int8u frmsizecod=(CC1(Buffer+Buffer_Offset+4)   )&0x3F;
4663             Size=AC3_FrameSize_Get(frmsizecod, fscod);
4664         }
4665         else if (bsid>0x0A && bsid<=0x10)
4666         {
4667             int16u frmsiz=CC2(Buffer+Buffer_Offset+2)&0x07FF;
4668             Size=2+frmsiz*2;
4669         }
4670         if (Size>=6)
4671         {
4672             if (Buffer_Offset+Size>Buffer_Size)
4673                 return false; //Need more data
4674             if (CRC_Compute(Size))
4675             {
4676                 Synched=true;
4677                 return true;
4678             }
4679         }
4680     }
4681 
4682     if (Buffer[Buffer_Offset+0]==0x77
4683      && Buffer[Buffer_Offset+1]==0x0B) //AC-3 LE
4684     {
4685         bsid=CC1(Buffer+Buffer_Offset+4)>>3;
4686         int16u  Size=0;
4687         if (bsid<=0x09)
4688         {
4689             int8u fscod     =(CC1(Buffer+Buffer_Offset+5)>>6)&0x03;
4690             int8u frmsizecod=(CC1(Buffer+Buffer_Offset+5)   )&0x3F;
4691             Size=AC3_FrameSize_Get(frmsizecod, fscod);
4692         }
4693         else if (bsid>0x0A && bsid<=0x10)
4694         {
4695             int16u frmsiz=LittleEndian2int16u(Buffer+Buffer_Offset+2)&0x07FF;
4696             Size=2+frmsiz*2;
4697 
4698             //TODO: case with multiple substreams
4699         }
4700         if (Size>=6)
4701         {
4702             size_t Size_Total=Core_Size_Get();
4703             if (Element_IsWaitingForMoreData())
4704                 return false; //Need more data
4705 
4706             Save_Buffer=Buffer;
4707             Save_Buffer_Offset=Buffer_Offset;
4708             Save_Buffer_Size=Buffer_Size;
4709 
4710             {
4711                 int8u* Buffer_Little=new int8u[Size_Total];
4712                 for (size_t Pos=0; Pos+1<Size_Total; Pos+=2)
4713                 {
4714                     Buffer_Little[Pos+1]=Save_Buffer[Buffer_Offset+Pos  ];
4715                     Buffer_Little[Pos  ]=Save_Buffer[Buffer_Offset+Pos+1];
4716                 }
4717                 Buffer=Buffer_Little;
4718                 Buffer_Offset=0;
4719                 Buffer_Size=Size_Total;
4720 
4721                 Synched=CRC_Compute(Size);
4722 
4723                 if (Synched)
4724                 {
4725                     BigEndian=false;
4726 
4727                     swap(Buffer, Save_Buffer);
4728                     swap(Buffer_Offset, Save_Buffer_Offset);
4729                     swap(Buffer_Size, Save_Buffer_Size);
4730 
4731                     return true;
4732                 }
4733 
4734                 delete[] Buffer_Little;
4735             }
4736             Buffer=Save_Buffer; Save_Buffer=NULL;
4737             Buffer_Offset=Save_Buffer_Offset;
4738             Buffer_Size=Save_Buffer_Size;
4739         }
4740     }
4741 
4742     if (HD_MajorSync_Parsed
4743      || (Buffer[Buffer_Offset+4]==0xF8
4744       && Buffer[Buffer_Offset+5]==0x72
4745       && Buffer[Buffer_Offset+6]==0x6F
4746       && (Buffer[Buffer_Offset+7]&0xFE)==0xBA)) //TrueHD or MLP
4747     {
4748         HD_IsPresent=true;
4749         Synched=true;
4750         return true;
4751     }
4752 
4753     Synched=false;
4754     return true;
4755 }
4756 
4757 //---------------------------------------------------------------------------
CRC_Compute(size_t Size)4758 bool File_Ac3::CRC_Compute(size_t Size)
4759 {
4760     //Config
4761     if (!IgnoreCrc_Done)
4762     {
4763         IgnoreCrc=Config->File_Ac3_IgnoreCrc_Get();
4764         IgnoreCrc_Done=true;
4765     }
4766     if (IgnoreCrc && !Status[IsAccepted]) //Else there are some wrong synchronizations
4767     {
4768         MediaInfo_Internal MI;
4769         Ztring ParseSpeed_Save=MI.Option(__T("ParseSpeed_Get"), __T(""));
4770         Ztring Demux_Save=MI.Option(__T("Demux_Get"), __T(""));
4771         MI.Option(__T("ParseSpeed"), __T("0"));
4772         MI.Option(__T("Demux"), Ztring());
4773         size_t MiOpenResult=MI.Open(File_Name);
4774         MI.Option(__T("ParseSpeed"), ParseSpeed_Save); //This is a global value, need to reset it. TODO: local value
4775         MI.Option(__T("Demux"), Demux_Save); //This is a global value, need to reset it. TODO: local value
4776         if (MiOpenResult)
4777         {
4778             Ztring Format=MI.Get(Stream_General, 0, General_Format);
4779             if (Format!=__T("AC-3") && Format!=__T("E-AC-3"))
4780                 IgnoreCrc=false;
4781         }
4782         else
4783             IgnoreCrc=false; // Problem
4784     }
4785     if (IgnoreCrc)
4786         return true;
4787 
4788     int16u CRC_16=0x0000;
4789     const int8u* CRC_16_Buffer=Buffer+Buffer_Offset+2; //After syncword
4790     const int8u* CRC_16_Buffer_5_8=Buffer+Buffer_Offset+(((Size>>2)+(Size>>4))<<1); //Magic formula to meet 5/8 frame size from Dolby
4791     const int8u* CRC_16_Buffer_EndMinus3=Buffer+Buffer_Offset+Size-3; //End of frame minus 3
4792     const int8u* CRC_16_Buffer_End=Buffer+Buffer_Offset+Size; //End of frame
4793     while(CRC_16_Buffer<CRC_16_Buffer_End)
4794     {
4795         CRC_16=(CRC_16<<8) ^ CRC_16_Table[(CRC_16>>8)^(*CRC_16_Buffer)];
4796 
4797         //CRC bytes inversion
4798         if (CRC_16_Buffer==CRC_16_Buffer_EndMinus3 && bsid<=0x09 && ((*CRC_16_Buffer)&0x01)) //CRC inversion bit
4799         {
4800             CRC_16_Buffer++;
4801             CRC_16=(CRC_16<<8) ^ CRC_16_Table[(CRC_16>>8)^((int8u)(~(*CRC_16_Buffer)))];
4802             CRC_16_Buffer++;
4803             CRC_16=(CRC_16<<8) ^ CRC_16_Table[(CRC_16>>8)^((int8u)(~(*CRC_16_Buffer)))];
4804         }
4805 
4806         CRC_16_Buffer++;
4807 
4808         //5/8 intermediate test
4809         if (CRC_16_Buffer==CRC_16_Buffer_5_8 && bsid<=0x09 && CRC_16!=0x0000)
4810             break;
4811     }
4812 
4813     return (CRC_16==0x0000);
4814 }
4815 
4816 //---------------------------------------------------------------------------
Core_Size_Get()4817 size_t File_Ac3::Core_Size_Get()
4818 {
4819     bool IsLE=(Buffer[Buffer_Offset+0]==0x77);
4820 
4821     int16u Size=1;
4822     bsid=(Buffer[(size_t)(Buffer_Offset+5-IsLE)]&0xF8)>>3;
4823     if (bsid<=0x09)
4824     {
4825         fscod     =(Buffer[(size_t)(Buffer_Offset+4+IsLE)]&0xC0)>>6;
4826         frmsizecod= Buffer[(size_t)(Buffer_Offset+4+IsLE)]&0x3F;
4827 
4828         //Filling
4829         fscods[fscod]++;
4830         frmsizecods[frmsizecod]++;
4831         Size=AC3_FrameSize_Get(frmsizecod, fscod);
4832     }
4833     else if (bsid>0x0A && bsid<=0x10)
4834     {
4835         int16u frmsiz    =((int16u)(Buffer[(size_t)(Buffer_Offset+2+IsLE)]&0x07)<<8)
4836                         | (         Buffer[(size_t)(Buffer_Offset+3-IsLE)]         );
4837 
4838         //Filling
4839         Size=2+frmsiz*2;
4840     }
4841 
4842         substreams_Count=0;
4843         int8u substreams_Count_Independant=0;
4844         int8u substreams_Count_Dependant=0;
4845 
4846         for (;;)
4847         {
4848             if (Buffer_Offset+Size+6>Buffer_Size)
4849             {
4850                 if (!IsSub && !Save_Buffer && File_Offset+Buffer_Offset+Size<File_Size)
4851                     Element_WaitForMoreData();
4852                 break;
4853             }
4854 
4855             int8u bsid=Buffer[Buffer_Offset+Size+5-IsLE]>>3;
4856             if (bsid<=0x09 || bsid>0x10)
4857                 break; //Not E-AC-3
4858 
4859             int8u substreamid=(Buffer[Buffer_Offset+Size+2+IsLE]>>3)&0x07;
4860             if (substreamid!=substreams_Count_Independant)
4861                 break; //Problem
4862             if (substreamid!=substreams_Count_Dependant)
4863                 break; //Problem
4864 
4865             int8u strmtyp = Buffer[Buffer_Offset+Size+2+IsLE]>>6;
4866             if (substreamid==0 && strmtyp==0)
4867                 break; //Next block
4868 
4869             int16u frmsiz =((int16u)(Buffer[(size_t)(Buffer_Offset+Size+2+IsLE)]&0x07)<<8)
4870                           | (         Buffer[(size_t)(Buffer_Offset+Size+3-IsLE)]         );
4871 
4872             //Filling
4873             Size+=2+frmsiz*2;
4874 
4875             if (strmtyp == 0)
4876             {
4877                 substreams_Count_Independant++;
4878                 substreams_Count_Dependant=0;
4879             }
4880             else
4881                 substreams_Count_Dependant++;
4882             substreams_Count++;
4883         }
4884 
4885     return Size;
4886 }
4887 
4888 //---------------------------------------------------------------------------
HD_Size_Get()4889 size_t File_Ac3::HD_Size_Get()
4890 {
4891     size_t Size=BigEndian2int16u(Buffer+Buffer_Offset)&0x0FFF;
4892     Size*=2;
4893 
4894     return Size;
4895 }
4896 
4897 //---------------------------------------------------------------------------
Get_V4(int8u Bits,int32u & Info,const char * Name)4898 void File_Ac3::Get_V4(int8u  Bits, int32u  &Info, const char* Name)
4899 {
4900     Info = 0;
4901 
4902     #if MEDIAINFO_TRACE
4903         if (Trace_Activated)
4904         {
4905             int8u Count = 0;
4906             do
4907             {
4908                 Info += BS->Get4(Bits);
4909                 Count += Bits;
4910             }
4911             while (BS->GetB());
4912             Param(Name, Info, Count);
4913             Param_Info(__T("(")+Ztring::ToZtring(Count)+__T(" bits)"));
4914         }
4915         else
4916     #endif //MEDIAINFO_TRACE
4917         {
4918             do
4919                 Info += BS->Get4(Bits);
4920             while (BS->GetB());
4921         }
4922 }
4923 
4924 //---------------------------------------------------------------------------
Skip_V4(int8u Bits,const char * Name)4925 void File_Ac3::Skip_V4(int8u  Bits, const char* Name)
4926 {
4927     #if MEDIAINFO_TRACE
4928         if (Trace_Activated)
4929         {
4930             int8u Info = 0;
4931             int8u Count = 0;
4932             do
4933             {
4934                 Info += BS->Get4(Bits);
4935                 Count += Bits;
4936             }
4937             while (BS->GetB());
4938             Param(Name, Info, Count);
4939             Param_Info(__T("(")+Ztring::ToZtring(Count)+__T(" bits)"));
4940         }
4941         else
4942     #endif //MEDIAINFO_TRACE
4943         {
4944             do
4945                 BS->Skip(Bits);
4946             while (BS->GetB());
4947         }
4948 }
4949 
4950 } //NameSpace
4951 
4952 #endif //MEDIAINFO_AC3_YES
4953