Debian Codegraph @

components/decoder/fdkaac/fdkaac.cpp

raw symbols SCIP
1 /* BoCA - BonkEnc Component Architecture
2 * Copyright (C) 2007-2026 Robert Kausch <[email protected]>
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation, either version 2 of
7 * the License, or (at your option) any later version.
8 *
9 * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
10 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
11 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */
12
13 #include <smooth.h>
14 #include <smooth/dll.h>
15
16 #include "fdkaac.h"
17
18 #ifndef CAPF_AAC_USAC
19 # define CAPF_AAC_USAC 0x00200000
20 #endif
21
22 using namespace smooth::IO;
23
24 const String &BoCA::DecoderFDKAAC::GetComponentSpecs()
25 {
26 static String componentSpecs;
27
28 if (fdkaacdll != NIL)
29 {
30 componentSpecs = " \
31 \
32 <?xml version=\"1.0\" encoding=\"UTF-8\"?> \
33 <component> \
34 <name>FDK-AAC Decoder %VERSION%</name> \
35 <version>1.0</version> \
36 <id>fdkaac-dec</id> \
37 <type>decoder</type> \
38 <precede>faad2-dec</precede> \
39 \
40 ";
41
42 if (mp4v2dll != NIL)
43 {
44 componentSpecs.Append(" \
45 \
46 <format> \
47 <name>MPEG-4 AAC Files</name> \
48 <extension>m4a</extension> \
49 <extension>m4b</extension> \
50 <extension>m4r</extension> \
51 <extension>mp4</extension> \
52 <extension>3gp</extension> \
53 <extension>3gpp</extension> \
54 <tag id=\"mp4-tag\" mode=\"other\">MP4 Metadata</tag> \
55 </format> \
56 \
57 ");
58 }
59
60 componentSpecs.Append(" \
61 \
62 <format> \
63 <name>Raw AAC Files</name> \
64 <extension>aac</extension> \
65 <tag id=\"id3v2-tag\" mode=\"prepend\">ID3v2</tag> \
66 </format> \
67 </component> \
68 \
69 ");
70
71 UnsignedInt32 version = GetDecoderVersion();
72
73 componentSpecs.Replace("%VERSION%", String("v").Append(String::FromInt((version >> 24) & 0xff)).Append(".")
74 .Append(String::FromInt((version >> 16) & 0xff)).Append(".")
75 .Append(String::FromInt((version >> 8) & 0xff)));
76 }
77
78 return componentSpecs;
79 }
80
81 Void smooth::AttachDLL(Void *instance)
82 {
83 LoadFDKAACDLL();
84 LoadMP4v2DLL();
85 }
86
87 Void smooth::DetachDLL()
88 {
89 FreeFDKAACDLL();
90 FreeMP4v2DLL();
91 }
92
93 namespace BoCA
94 {
95 int64_t MP4IO_size(void *);
96 int MP4IO_seek(void *, int64_t);
97 int MP4IO_read(void *, void *, int64_t, int64_t *);
98
99 static MP4IOCallbacks mp4Callbacks = { MP4IO_size, MP4IO_seek, MP4IO_read, NIL, NIL };
100 };
101
102 Bool BoCA::DecoderFDKAAC::CanOpenStream(const String &streamURI)
103 {
104 Bool isValidFile = False;
105 InStream in(STREAM_FILE, streamURI, IS_READ);
106
107 if (mp4v2dll != NIL && (in.InputNumberRaw(8) & 0xFFFFFFFF) == 'ftyp')
108 {
109 MP4FileHandle mp4File = ex_MP4Read(streamURI.ConvertTo("UTF-8"));
110 MP4TrackId mp4Track = ex_MP4FindTrackId(mp4File, 0, MP4_AUDIO_TRACK_TYPE, 0);
111
112 if (mp4Track != MP4_INVALID_TRACK_ID && ex_MP4GetSampleSize(mp4File, mp4Track, 1) > 0)
113 {
114 LIB_INFO info[FDK_MODULE_LAST];
115
116 FDKinitLibInfo(info);
117 ex_aacDecoder_GetLibInfo(info);
118
119 UINT aacFlags = FDKlibInfo_getCapabilities(info, FDK_AACDEC);
120 UINT sbrFlags = FDKlibInfo_getCapabilities(info, FDK_SBRDEC);
121
122 Int type = ex_MP4GetTrackAudioMpeg4Type(mp4File, mp4Track);
123
124 if ((type == AOT_AAC_LC && aacFlags & CAPF_AAC_LC ) ||
125 (type == AOT_SBR && sbrFlags ) ||
126 (type == AOT_PS && sbrFlags & CAPF_SBR_PS_MPEG) ||
127 (type == AOT_USAC && aacFlags & CAPF_AAC_USAC ) ||
128
129 (type == AOT_ER_AAC_LC && aacFlags & CAPF_ER_AAC_LC ) ||
130 (type == AOT_ER_AAC_LD && aacFlags & CAPF_ER_AAC_LD ) ||
131 (type == AOT_ER_AAC_ELD && aacFlags & CAPF_ER_AAC_ELD ) ||
132 (type == AOT_ER_AAC_SCAL && aacFlags & CAPF_ER_AAC_SCAL) ||
133 (type == AOT_ER_BSAC && aacFlags & CAPF_ER_AAC_BSAC)) isValidFile = True;
134 }
135
136 ex_MP4Close(mp4File, 0);
137 }
138 else
139 {
140 Track track;
141
142 if (GetStreamInfo(streamURI, track) == Success()) isValidFile = True;
143 }
144
145 return isValidFile;
146 }
147
148 Error BoCA::DecoderFDKAAC::GetStreamInfo(const String &streamURI, Track &track)
149 {
150 Format format = track.GetFormat();
151 InStream in(STREAM_FILE, streamURI, IS_READ);
152
153 if ((in.InputNumberRaw(8) & 0xFFFFFFFF) == 'ftyp')
154 {
155 track.fileSize = File(streamURI).GetFileSize();
156 track.length = -1;
157
158 MP4FileHandle mp4File = ex_MP4Read(streamURI.ConvertTo("UTF-8"));
159 MP4TrackId mp4Track = ex_MP4FindTrackId(mp4File, 0, MP4_AUDIO_TRACK_TYPE, 0);
160
161 if (mp4Track != MP4_INVALID_TRACK_ID && ex_MP4GetSampleSize(mp4File, mp4Track, 1) > 0)
162 {
163 HANDLE_AACDECODER handle = ex_aacDecoder_Open(TT_MP4_RAW, 1);
164
165 /* Get codec configuration.
166 */
167 unsigned char *escBuffer = NIL;
168 unsigned int escBufferSize = 0;
169
170 ex_MP4GetTrackESConfiguration(mp4File, mp4Track, (uint8_t **) &escBuffer, (uint32_t *) &escBufferSize);
171
172 /* The FDK bitstream reader reads up to 4 bytes behind the buffer,
173 * so allocate a larger buffer to prevent access violations.
174 */
175 unsigned char *escBuffer2 = new unsigned char [escBufferSize + 4];
176
177 memcpy(escBuffer2, escBuffer, escBufferSize);
178
179 ex_aacDecoder_ConfigRaw(handle, &escBuffer2, &escBufferSize);
180
181 delete [] escBuffer2;
182
183 ex_MP4Free(escBuffer);
184
185 /* Decode one frame to initialize decoder.
186 */
187 unsigned int bufferSize = ex_MP4GetSampleSize(mp4File, mp4Track, 1);
188 unsigned char *buffer = new unsigned char [bufferSize + 4];
189
190 ex_MP4ReadSample(mp4File, mp4Track, 1, (uint8_t **) &buffer, (uint32_t *) &bufferSize, NIL, NIL, NIL, NIL);
191
192 unsigned int bytesValid = bufferSize;
193
194 ex_aacDecoder_Fill(handle, &buffer, &bufferSize, &bytesValid);
195
196 short *outputBuffer = new short [16384];
197
198 if (ex_aacDecoder_DecodeFrame(handle, outputBuffer, 16384, 0) != AAC_DEC_OK)
199 {
200 errorState = True;
201 errorString = "Unsupported audio format";
202 }
203
204 delete [] outputBuffer;
205 delete [] buffer;
206
207 /* Get sample rate and number of channels.
208 */
209 if (!errorState)
210 {
211 CStreamInfo *streamInfo = ex_aacDecoder_GetStreamInfo(handle);
212
213 frameSize = streamInfo->frameSize;
214 sbrRatio = streamInfo->frameSize / streamInfo->aacSamplesPerFrame;
215
216 format.rate = streamInfo->sampleRate;
217 format.channels = streamInfo->numChannels;
218
219 if (format.channels == 2 && ex_MP4GetTrackAudioChannels(mp4File, mp4Track) == 1) format.channels = 1;
220
221 track.length = Int64(ex_MP4GetTrackNumberOfSamples(mp4File, mp4Track)) * streamInfo->frameSize;
222 track.length -= streamInfo->frameSize; // To account for encoder delay.
223
224 format.bits = 16;
225 }
226
227 ex_aacDecoder_Close(handle);
228
229 track.SetFormat(format);
230
231 /* Read gapless information.
232 */
233 Int delay = 0, padding = 0;
234 Int64 length = 0;
235
236 if (ReadGaplessInfo(mp4File, delay, padding, length) && (delay + padding + length) * sbrRatio == Int64(ex_MP4GetTrackNumberOfSamples(mp4File, mp4Track)) * frameSize)
237 {
238 track.length = length * sbrRatio;
239 }
240 }
241
242 ex_MP4Close(mp4File, 0);
243
244 /* Read MP4 metadata.
245 */
246 if (!errorState)
247 {
248 AS::Registry &boca = AS::Registry::Get();
249 AS::TaggerComponent *tagger = (AS::TaggerComponent *) boca.CreateComponentByID("mp4-tag");
250
251 if (tagger != NIL)
252 {
253 tagger->SetConfiguration(GetConfiguration());
254 tagger->ParseStreamInfo(streamURI, track);
255
256 boca.DeleteComponent(tagger);
257 }
258 }
259 }
260 else
261 {
262 in.Seek(0);
263
264 format.bits = 16;
265
266 track.fileSize = in.Size();
267 track.length = -1;
268
269 SkipID3v2Tag(in);
270
271 if (!SyncOnAACHeader(in))
272 {
273 errorState = True;
274 errorString = "Invalid file format";
275
276 return Error();
277 }
278
279 HANDLE_AACDECODER handle = ex_aacDecoder_Open( adifFound ? TT_MP4_ADIF :
280 (adtsFound ? TT_MP4_ADTS : TT_MP4_LOAS), 1);
281
282 /* Decode one frame to initialize decoder.
283 */
284 unsigned int size = Math::Min((Int64) 32768, track.fileSize - in.GetPos());
285 unsigned char *data = new unsigned char [size];
286
287 in.InputData((void *) data, size);
288
289 unsigned int bytesValid = size;
290
291 ex_aacDecoder_Fill(handle, &data, &size, &bytesValid);
292
293 short *outputBuffer = new short [16384];
294
295 if (ex_aacDecoder_DecodeFrame(handle, outputBuffer, 16384, 0) == AAC_DEC_OK)
296 {
297 /* Get sample rate and number of channels.
298 */
299 CStreamInfo *streamInfo = ex_aacDecoder_GetStreamInfo(handle);
300
301 format.rate = streamInfo->sampleRate;
302 format.channels = streamInfo->numChannels;
303
304 /* Compute approximate length of stream.
305 */
306 Int samplesRead = streamInfo->frameSize;
307
308 while (True)
309 {
310 if (bytesValid > 0)
311 {
312 unsigned char *inputBuffer = data + size - bytesValid;
313 unsigned int inputBufferSize = bytesValid;
314
315 ex_aacDecoder_Fill(handle, &inputBuffer, &inputBufferSize, &bytesValid);
316 }
317
318 if (ex_aacDecoder_DecodeFrame(handle, outputBuffer, 16384, 0) != AAC_DEC_OK) break;
319
320 samplesRead += streamInfo->frameSize;
321 }
322
323 if (samplesRead > 0) track.approxLength = samplesRead * (track.fileSize / size);
324 }
325 else
326 {
327 errorState = True;
328 errorString = "Unsupported audio format";
329 }
330
331 /* Close handles.
332 */
333 delete [] outputBuffer;
334 delete [] data;
335
336 ex_aacDecoder_Close(handle);
337
338 /* Read ID3v2 tag if any.
339 */
340 if (!errorState)
341 {
342 Bool foundTag = False;
343
344 AS::Registry &boca = AS::Registry::Get();
345 AS::TaggerComponent *tagger = (AS::TaggerComponent *) boca.CreateComponentByID("id3v2-tag");
346
347 if (tagger != NIL)
348 {
349 tagger->SetConfiguration(GetConfiguration());
350
351 if (tagger->ParseStreamInfo(streamURI, track) == Success()) foundTag = True;
352
353 boca.DeleteComponent(tagger);
354 }
355
356 if (!foundTag)
357 {
358 tagger = (AS::TaggerComponent *) boca.CreateComponentByID("id3v1-tag");
359
360 if (tagger != NIL)
361 {
362 tagger->SetConfiguration(GetConfiguration());
363 tagger->ParseStreamInfo(streamURI, track);
364
365 boca.DeleteComponent(tagger);
366 }
367 }
368 }
369 }
370
371 track.SetFormat(format);
372
373 if (!errorState) return Success();
374 else return Error();
375 }
376
377 BoCA::DecoderFDKAAC::DecoderFDKAAC()
378 {
379 mp4File = NIL;
380 handle = NIL;
381
382 mp4Track = MP4_INVALID_TRACK_ID;
383 sampleId = 1;
384
385 finished = False;
386
387 adifFound = False;
388 adtsFound = False;
389 loasFound = False;
390
391 frameSize = 0;
392 sbrRatio = 1;
393
394 delaySamples = 0;
395 delaySamplesLeft = 0;
396 }
397
398 BoCA::DecoderFDKAAC::~DecoderFDKAAC()
399 {
400 }
401
402 UnsignedInt32 BoCA::DecoderFDKAAC::GetDecoderVersion()
403 {
404 LIB_INFO info[FDK_MODULE_LAST];
405
406 FDKinitLibInfo(info);
407 ex_aacDecoder_GetLibInfo(info);
408
409 for (Int i = 0; i < FDK_MODULE_LAST; i++)
410 {
411 if (info[i].module_id != FDK_AACDEC) continue;
412
413 return info[i].version;
414 }
415
416 return 0;
417 }
418
419 Bool BoCA::DecoderFDKAAC::Activate()
420 {
421 InStream in(STREAM_DRIVER, driver);
422
423 if ((in.InputNumberRaw(8) & 0xFFFFFFFF) == 'ftyp')
424 {
425 mp4File = ex_MP4ReadCallbacks(&mp4Callbacks, driver);
426 mp4Track = ex_MP4FindTrackId(mp4File, 0, MP4_AUDIO_TRACK_TYPE, 0);
427
428 if (mp4Track == MP4_INVALID_TRACK_ID)
429 {
430 ex_MP4Close(mp4File, 0);
431
432 return False;
433 }
434
435 handle = ex_aacDecoder_Open(TT_MP4_RAW, 1);
436
437 /* Get codec configuration.
438 */
439 unsigned char *escBuffer = NIL;
440 unsigned int escBufferSize = 0;
441
442 ex_MP4GetTrackESConfiguration(mp4File, mp4Track, (uint8_t **) &escBuffer, (uint32_t *) &escBufferSize);
443
444 /* The FDK bitstream reader reads up to 4 bytes behind the buffer,
445 * so allocate a larger buffer to prevent access violations.
446 */
447 unsigned char *escBuffer2 = new unsigned char [escBufferSize + 4];
448
449 memcpy(escBuffer2, escBuffer, escBufferSize);
450
451 ex_aacDecoder_ConfigRaw(handle, &escBuffer2, &escBufferSize);
452
453 delete [] escBuffer2;
454
455 ex_MP4Free(escBuffer);
456 }
457 else
458 {
459 in.Seek(0);
460
461 SkipID3v2Tag(in);
462 SyncOnAACHeader(in);
463
464 driver->Seek(in.GetPos());
465
466 handle = ex_aacDecoder_Open( adifFound ? TT_MP4_ADIF :
467 (adtsFound ? TT_MP4_ADTS : TT_MP4_LOAS), 1);
468 }
469
470 return True;
471 }
472
473 Bool BoCA::DecoderFDKAAC::Deactivate()
474 {
475 /* Close decoder.
476 */
477 ex_aacDecoder_Close(handle);
478
479 if (mp4File == NIL) return True;
480
481 /* Close MP4 file.
482 */
483 ex_MP4Close(mp4File, 0);
484
485 return True;
486 }
487
488 Bool BoCA::DecoderFDKAAC::Seek(Int64 samplePosition)
489 {
490 if (mp4File == NIL) return False;
491
492 MP4Timestamp time = Math::Round(Float(samplePosition) / track.GetFormat().rate * ex_MP4GetTrackTimeScale(mp4File, mp4Track));
493
494 sampleId = ex_MP4GetSampleIdFromTime(mp4File, mp4Track, time, true);
495 delaySamplesLeft = delaySamples + time - ex_MP4GetSampleTime(mp4File, mp4Track, sampleId);
496
497 return True;
498 }
499
500 Int BoCA::DecoderFDKAAC::ReadData(Buffer<UnsignedByte> &data)
501 {
502 static Int maxFrameSize = 2048;
503
504 if (finished) return -1;
505
506 const Format &format = track.GetFormat();
507
508 Int samplesRead = 0;
509
510 samplesBuffer.Resize(0);
511
512 if (mp4File != NIL)
513 {
514 MP4SampleId numberOfSamples = ex_MP4GetTrackNumberOfSamples(mp4File, mp4Track);
515
516 if (sampleId <= numberOfSamples)
517 {
518 unsigned int bufferSize = ex_MP4GetSampleSize(mp4File, mp4Track, sampleId);
519
520 dataBuffer.Resize(bufferSize + 4); // + 4 to account for FDK bitstream implementation overreading.
521
522 unsigned char *buffer = dataBuffer;
523
524 if (!ex_MP4ReadSample(mp4File, mp4Track, sampleId++, (uint8_t **) &buffer, (uint32_t *) &bufferSize, NIL, NIL, NIL, NIL)) return -1;
525
526 unsigned int bytesValid = bufferSize;
527
528 if (bytesValid > 0)
529 {
530 unsigned char *inputBuffer = buffer + bufferSize - bytesValid;
531 unsigned int inputBufferSize = bytesValid;
532
533 ex_aacDecoder_Fill(handle, &inputBuffer, &inputBufferSize, &bytesValid);
534 }
535
536 Int bufferChannels = Math::Max(2, format.channels);
537
538 if (frameSize == 0) samplesBuffer.Resize(samplesRead * format.channels + maxFrameSize * bufferChannels);
539 else samplesBuffer.Resize(samplesRead * format.channels + frameSize * bufferChannels);
540
541 short *outputBuffer = samplesBuffer + samplesRead * format.channels;
542
543 if (ex_aacDecoder_DecodeFrame(handle, outputBuffer, samplesBuffer.Size() - samplesRead * format.channels, 0) == AAC_DEC_OK)
544 {
545 CStreamInfo *streamInfo = ex_aacDecoder_GetStreamInfo(handle);
546
547 if (frameSize == 0)
548 {
549 frameSize = streamInfo->frameSize;
550 sbrRatio = streamInfo->frameSize / streamInfo->aacSamplesPerFrame;
551
552 /* Get delay from gapless information.
553 */
554 Int delay = 0, padding = 0;
555 Int64 length = 0;
556
557 if (ReadGaplessInfo(mp4File, delay, padding, length) && (delay + padding + length) * sbrRatio == Int64(numberOfSamples) * frameSize)
558 {
559 delaySamples = delay * sbrRatio;
560 delaySamplesLeft = delaySamples;
561 }
562
563 /* Set delay samples to minimum encoder delay.
564 */
565 if (delaySamples == 0)
566 {
567 delaySamples = frameSize;
568 delaySamplesLeft = delaySamples;
569 }
570
571 /* Add FDK decoder delay.
572 */
573 delaySamplesLeft += streamInfo->outputDelay;
574 }
575
576 if (format.channels == 1 && streamInfo->numChannels == 2)
577 {
578 for (Int i = 0; i < frameSize; i++) samplesBuffer[samplesRead + i] = samplesBuffer[samplesRead + i * 2];
579 }
580
581 samplesBuffer.Resize((samplesRead + frameSize) * format.channels);
582
583 samplesRead += frameSize;
584 }
585 }
586 else
587 {
588 /* Flush the decoder reading up to two more frames (some decoders
589 * keep returning AAC_DEC_OK even after the end is reached, so we
590 * have to limit the number of read attempts).
591 */
592 for (Int i = 0; i < 2; i++)
593 {
594 Int bufferChannels = Math::Max(2, format.channels);
595
596 samplesBuffer.Resize(samplesRead * format.channels + frameSize * bufferChannels);
597
598 short *outputBuffer = samplesBuffer + samplesRead * format.channels;
599
600 if (ex_aacDecoder_DecodeFrame(handle, outputBuffer, samplesBuffer.Size() - samplesRead * format.channels, AACDEC_FLUSH) != AAC_DEC_OK) break;
601
602 CStreamInfo *streamInfo = ex_aacDecoder_GetStreamInfo(handle);
603
604 if (format.channels == 1 && streamInfo->numChannels == 2)
605 {
606 for (Int i = 0; i < frameSize; i++) samplesBuffer[samplesRead + i] = samplesBuffer[samplesRead + i * 2];
607 }
608
609 samplesBuffer.Resize((samplesRead + frameSize) * format.channels);
610
611 samplesRead += frameSize;
612 }
613
614 finished = True;
615 }
616 }
617 else
618 {
619 dataBuffer.Resize(data.Size() + 4); // + 4 to account for FDK bitstream implementation overreading.
620
621 Int size = driver->ReadData(dataBuffer, data.Size());
622
623 if (size <= 0) return -1;
624
625 inBytes += size;
626
627 UnsignedInt bytesValid = size;
628
629 while (bytesValid || driver->GetPos() == driver->GetSize())
630 {
631 if (bytesValid > 0)
632 {
633 unsigned char *inputBuffer = dataBuffer + size - bytesValid;
634 unsigned int inputBufferSize = bytesValid;
635
636 ex_aacDecoder_Fill(handle, &inputBuffer, &inputBufferSize, &bytesValid);
637 }
638
639 if (frameSize == 0) samplesBuffer.Resize((samplesRead + maxFrameSize) * format.channels);
640 else samplesBuffer.Resize((samplesRead + frameSize) * format.channels);
641
642 short *outputBuffer = samplesBuffer + samplesRead * format.channels;
643
644 if (ex_aacDecoder_DecodeFrame(handle, outputBuffer, samplesBuffer.Size() - samplesRead * format.channels, 0) != AAC_DEC_OK) break;
645
646 if (frameSize == 0)
647 {
648 CStreamInfo *streamInfo = ex_aacDecoder_GetStreamInfo(handle);
649
650 frameSize = streamInfo->frameSize;
651
652 /* Set delay samples to minimum encoder delay.
653 */
654 delaySamples = frameSize;
655 delaySamplesLeft = delaySamples;
656
657 /* Add FDK decoder delay.
658 */
659 delaySamplesLeft += streamInfo->outputDelay;
660
661 samplesBuffer.Resize((samplesRead + frameSize) * format.channels);
662 }
663
664 samplesRead += frameSize;
665 }
666
667 if (driver->GetPos() == driver->GetSize())
668 {
669 /* Flush the decoder reading up to two more frames (some decoders
670 * keep returning AAC_DEC_OK even after the end is reached, so we
671 * have to limit the number of read attempts).
672 */
673 for (Int i = 0; i < 2; i++)
674 {
675 samplesBuffer.Resize((samplesRead + frameSize) * format.channels);
676
677 short *outputBuffer = samplesBuffer + samplesRead * format.channels;
678
679 if (ex_aacDecoder_DecodeFrame(handle, outputBuffer, samplesBuffer.Size() - samplesRead * format.channels, AACDEC_FLUSH) != AAC_DEC_OK) break;
680
681 samplesRead += frameSize;
682 }
683
684 finished = True;
685 }
686 }
687
688 data.Resize(0);
689
690 if (samplesRead > delaySamplesLeft)
691 {
692 data.Resize((samplesRead - delaySamplesLeft) * format.channels * (format.bits / 8));
693
694 memcpy(data, samplesBuffer + delaySamplesLeft * format.channels, data.Size());
695 }
696
697 delaySamplesLeft = Math::Max(0, delaySamplesLeft - samplesRead);
698
699 return data.Size();
700 }
701
702 Bool BoCA::DecoderFDKAAC::ReadGaplessInfo(MP4FileHandle mp4File, Int &delay, Int &padding, Int64 &length) const
703 {
704 Bool result = False;
705
706 /* Look for iTunes metadata with gapless information.
707 */
708 MP4ItmfItemList *items = ex_MP4ItmfGetItemsByMeaning(mp4File, "com.apple.iTunes", "iTunSMPB");
709
710 if (items != NIL)
711 {
712 if (items->size == 1)
713 {
714 /* Read value as string.
715 */
716 Buffer<char> value(items->elements[0].dataList.elements[0].valueSize + 1);
717
718 memset(value, 0, items->elements[0].dataList.elements[0].valueSize + 1);
719 memcpy(value, items->elements[0].dataList.elements[0].value, items->elements[0].dataList.elements[0].valueSize);
720
721 /* Parse value string.
722 */
723 const Array<String> &values = String(value).Trim().Explode(" ");
724
725 delay = (Int64) Number::FromHexString(values.GetNth(1));
726 padding = (Int64) Number::FromHexString(values.GetNth(2));
727 length = (Int64) Number::FromHexString(values.GetNth(3));
728
729 result = True;
730 }
731
732 ex_MP4ItmfItemListFree(items);
733 }
734
735 return result;
736 }
737
738 Bool BoCA::DecoderFDKAAC::SkipID3v2Tag(InStream &in)
739 {
740 /* Check for an ID3v2 tag at the beginning
741 * of the file and skip it if it exists.
742 */
743 if (in.InputString(3) == "ID3")
744 {
745 in.InputNumber(2); // ID3 version
746 in.InputNumber(1); // Flags
747
748 /* Read tag size as a 4 byte unsynchronized integer.
749 */
750 Int tagSize = (in.InputNumber(1) << 21) +
751 (in.InputNumber(1) << 14) +
752 (in.InputNumber(1) << 7) +
753 (in.InputNumber(1) );
754
755 in.RelSeek(tagSize);
756
757 inBytes += (tagSize + 10);
758 }
759 else
760 {
761 in.Seek(0);
762 }
763
764 return True;
765 }
766
767 Bool BoCA::DecoderFDKAAC::SyncOnAACHeader(InStream &in)
768 {
769 const Int startPos = in.GetPos();
770 const Int maxFrameSize = 8192;
771
772 /* Try to sync on ADIF header.
773 */
774 for (Int n = 0; n < maxFrameSize; n++)
775 {
776 if (in.InputNumber(1) != 'A') continue;
777 if (in.InputNumber(1) != 'D') continue;
778 if (in.InputNumber(1) != 'I') continue;
779 if (in.InputNumber(1) != 'F') continue;
780
781 /* ADIF magic word found.
782 */
783 in.RelSeek(-4);
784
785 inBytes += n;
786
787 adifFound = True;
788
789 return True;
790 }
791
792 in.Seek(startPos);
793
794 /* Try to sync on ADTS header.
795 */
796 for (Int n = 0; n < maxFrameSize; n++)
797 {
798 if ( in.InputNumber(1) != 0xFF) continue;
799 if ( (in.InputNumber(1) & 0xF6) != 0xF0) continue;
800 if (((in.InputNumber(1) & 0x3C) >> 2) >= 12) continue;
801
802 /* ADTS sync found.
803 */
804 in.RelSeek(-3);
805
806 inBytes += n;
807
808 adtsFound = True;
809
810 return True;
811 }
812
813 in.Seek(startPos);
814
815 /* Try to sync on LOAS/LATM header.
816 */
817 for (Int n = 0; n < maxFrameSize; n++)
818 {
819 if ( in.InputNumber(1) != 0x56) continue;
820 if ( (in.InputNumber(1) & 0xE0) != 0xE0) continue;
821
822 /* LOAS sync.
823 */
824 in.RelSeek(-2);
825
826 inBytes += n;
827
828 loasFound = True;
829
830 return True;
831 }
832
833 /* No sync. Probably not an AAC file.
834 */
835 return False;
836 }
837
838 int64_t BoCA::MP4IO_size(void *handle)
839 {
840 Driver *driver = (Driver *) handle;
841
842 return driver->GetSize();
843 }
844
845 int BoCA::MP4IO_seek(void *handle, int64_t pos)
846 {
847 Driver *driver = (Driver *) handle;
848
849 if (driver->Seek(pos) == -1) return 1;
850
851 return 0;
852 }
853
854 int BoCA::MP4IO_read(void *handle, void *buffer, int64_t size, int64_t *nout)
855 {
856 Driver *driver = (Driver *) handle;
857
858 *nout = driver->ReadData((UnsignedByte *) buffer, size);
859
860 if (*nout == 0) return 1;
861
862 return 0;
863 }