Debian Codegraph @

components/encoder/voaacenc/voaacenc.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 "voaacenc.h"
17 #include "config.h"
18
19 using namespace smooth::IO;
20
21 const String &BoCA::EncoderVOAAC::GetComponentSpecs()
22 {
23 static String componentSpecs;
24
25 if (voaacencdll != NIL)
26 {
27 componentSpecs = " \
28 \
29 <?xml version=\"1.0\" encoding=\"UTF-8\"?> \
30 <component> \
31 <name>VisualOn AAC Encoder</name> \
32 <version>1.0</version> \
33 <id>voaacenc-enc</id> \
34 <type>encoder</type> \
35 \
36 ";
37
38 if (mp4v2dll != NIL)
39 {
40 componentSpecs.Append(" \
41 \
42 <format> \
43 <name>MPEG-4 AAC Files</name> \
44 <extension>m4a</extension> \
45 <extension>m4b</extension> \
46 <extension>m4r</extension> \
47 <extension>mp4</extension> \
48 <tag id=\"mp4-tag\" mode=\"other\">MP4 Metadata</tag> \
49 </format> \
50 \
51 ");
52 }
53
54 componentSpecs.Append(" \
55 \
56 <format> \
57 <name>Raw AAC Files</name> \
58 <extension>aac</extension> \
59 <tag id=\"id3v2-tag\" mode=\"prepend\">ID3v2</tag> \
60 </format> \
61 <input bits=\"16\" channels=\"1-2\" \
62 rate=\"8000,11025,12000,16000,22050,24000,32000,44100,48000,64000,88200,96000\"/> \
63 <parameters> \
64 <range name=\"Bitrate per channel\" argument=\"-b %VALUE\" default=\"96\"> \
65 <min alias=\"min\">8</min> \
66 <max alias=\"max\">128</max> \
67 </range> \
68 \
69 ");
70
71 if (mp4v2dll != NIL)
72 {
73 componentSpecs.Append(" \
74 \
75 <switch name=\"Create ADTS AAC files (no MP4 container)\" argument=\"--adts\"/> \
76 \
77 ");
78 }
79
80 componentSpecs.Append(" \
81 \
82 </parameters> \
83 </component> \
84 \
85 ");
86 }
87
88 return componentSpecs;
89 }
90
91 Void smooth::AttachDLL(Void *instance)
92 {
93 LoadVOAACEncDLL();
94 LoadMP4v2DLL();
95 }
96
97 Void smooth::DetachDLL()
98 {
99 FreeVOAACEncDLL();
100 FreeMP4v2DLL();
101 }
102
103 namespace BoCA
104 {
105 int64_t MP4IO_size(void *);
106 int MP4IO_seek(void *, int64_t);
107 int MP4IO_write(void *, const void *, int64_t, int64_t *);
108
109 static MP4IOCallbacks mp4Callbacks = { MP4IO_size, MP4IO_seek, NIL, MP4IO_write, NIL };
110 };
111
112 BoCA::EncoderVOAAC::EncoderVOAAC()
113 {
114 configLayer = NIL;
115 config = NIL;
116
117 mp4File = NIL;
118 mp4Track = MP4_INVALID_TRACK_ID;
119
120 handle = NIL;
121
122 frameSize = 0;
123
124 totalSamples = 0;
125 delaySamples = 0;
126
127 memset(&memOperator, 0, sizeof(memOperator));
128 memset(&userData, 0, sizeof(userData));
129
130 ex_voGetAACEncAPI(&api);
131 }
132
133 BoCA::EncoderVOAAC::~EncoderVOAAC()
134 {
135 if (config != NIL) Config::Free(config);
136
137 if (configLayer != NIL) Object::DeleteObject(configLayer);
138 }
139
140 Bool BoCA::EncoderVOAAC::Activate()
141 {
142 const Format &format = track.GetFormat();
143 const Info &info = track.GetInfo();
144
145 /* Get configuration.
146 */
147 config = Config::Copy(GetConfiguration());
148
149 ConvertArguments(config);
150
151 if (mp4v2dll == NIL) config->SetIntValue(ConfigureVOAAC::ConfigID, "MP4Container", False);
152
153 Bool mp4Container = config->GetIntValue(ConfigureVOAAC::ConfigID, "MP4Container", True);
154 Int bitrate = config->GetIntValue(ConfigureVOAAC::ConfigID, "Bitrate", 96);
155
156 if (mp4v2dll == NIL) mp4Container = False;
157
158 /* Create VO AAC encoder.
159 */
160 unsigned long samplesSize = 1024 * format.channels;
161 unsigned long bufferSize = samplesSize * 4;
162
163 outBuffer.Resize(bufferSize);
164
165 memOperator.Alloc = ex_cmnMemAlloc;
166 memOperator.Copy = ex_cmnMemCopy;
167 memOperator.Free = ex_cmnMemFree;
168 memOperator.Set = ex_cmnMemSet;
169 memOperator.Check = ex_cmnMemCheck;
170
171 userData.memflag = VO_IMF_USERMEMOPERATOR;
172 userData.memData = &memOperator;
173
174 api.Init(&handle, VO_AUDIO_CodingAAC, &userData);
175
176 /* Set encoder parameters.
177 */
178 AACENC_PARAM params;
179
180 params.sampleRate = format.rate;
181 params.nChannels = format.channels;
182 params.bitRate = bitrate * 1000 * format.channels;
183 params.adtsUsed = !mp4Container;
184
185 api.SetParam(handle, VO_PID_AAC_ENCPARAM, &params);
186
187 frameSize = samplesSize / format.channels;
188 delaySamples = frameSize + 576;
189
190 /* Check whether to use MP4 container.
191 */
192 if (mp4Container)
193 {
194 /* Create MP4 file.
195 */
196 uint32_t flags = (track.length >= 0xFFFF0000 ||
197 track.approxLength >= 0xFFFF0000) ? MP4_CREATE_64BIT_DATA | MP4_CREATE_64BIT_TIME : 0;
198
199 mp4File = ex_MP4CreateCallbacks(&mp4Callbacks, driver, flags);
200 mp4Track = ex_MP4AddAudioTrack(mp4File, format.rate, MP4_INVALID_DURATION, MP4_MPEG4_AUDIO_TYPE);
201
202 ex_MP4SetAudioProfileLevel(mp4File, 0x0F);
203 ex_MP4SetTrackIntegerProperty(mp4File, mp4Track, "mdia.minf.stbl.stsd.mp4a.channels", format.channels);
204
205 int sampleRateIndex = GetSampleRateIndex(format.rate);
206 uint8_t esConfig[2] = { uint8_t( 2 << 3 | sampleRateIndex >> 1),
207 uint8_t((sampleRateIndex & 1) << 7 | format.channels << 3) };
208
209 ex_MP4SetTrackESConfiguration(mp4File, mp4Track, esConfig, 2);
210
211 totalSamples = 0;
212 }
213
214 /* Write ID3v2 tag if requested.
215 */
216 if (mp4File == NIL && config->GetIntValue("Tags", "EnableID3v2", True) && config->GetIntValue(ConfigureVOAAC::ConfigID, "AllowID3v2", False))
217 {
218 if (info.HasBasicInfo() || (track.tracks.Length() > 0 && config->GetIntValue("Tags", "WriteChapters", True)))
219 {
220 AS::Registry &boca = AS::Registry::Get();
221 AS::TaggerComponent *tagger = (AS::TaggerComponent *) boca.CreateComponentByID("id3v2-tag");
222
223 if (tagger != NIL)
224 {
225 Buffer<unsigned char> id3Buffer;
226
227 tagger->SetConfiguration(config);
228 tagger->RenderBuffer(id3Buffer, track);
229
230 driver->WriteData(id3Buffer, id3Buffer.Size());
231
232 boca.DeleteComponent(tagger);
233 }
234 }
235 }
236
237 return True;
238 }
239
240 Bool BoCA::EncoderVOAAC::Deactivate()
241 {
242 /* Output remaining samples to encoder.
243 */
244 EncodeFrames(True);
245
246 api.Uninit(handle);
247
248 /* Finish MP4 writing.
249 */
250 if (mp4File != NIL)
251 {
252 /* Write iTunes metadata with gapless information.
253 */
254 MP4ItmfItem *item = ex_MP4ItmfItemAlloc("----", 1);
255 String value = String().Append(" 00000000")
256 .Append(" ").Append(Number((Int64) delaySamples).ToHexString(8).ToUpper())
257 .Append(" ").Append(Number((Int64) frameSize - (delaySamples + totalSamples) % frameSize).ToHexString(8).ToUpper())
258 .Append(" ").Append(Number((Int64) totalSamples).ToHexString(16).ToUpper())
259 .Append(" 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000");
260
261 item->mean = (char *) "com.apple.iTunes";
262 item->name = (char *) "iTunSMPB";
263
264 item->dataList.elements[0].typeCode = MP4_ITMF_BT_UTF8;
265 item->dataList.elements[0].value = (uint8_t *) value.ConvertTo("UTF-8");
266 item->dataList.elements[0].valueSize = value.Length();
267
268 ex_MP4ItmfAddItem(mp4File, item);
269
270 item->mean = NIL;
271 item->name = NIL;
272
273 item->dataList.elements[0].typeCode = MP4_ITMF_BT_IMPLICIT;
274 item->dataList.elements[0].value = NIL;
275 item->dataList.elements[0].valueSize = 0;
276
277 ex_MP4ItmfItemFree(item);
278
279 ex_MP4Close(mp4File, 0);
280
281 /* Close output file as tagger needs to modify it.
282 */
283 driver->Close();
284
285 /* Write metadata to file.
286 */
287 const Info &info = track.GetInfo();
288
289 if (config->GetIntValue("Tags", "EnableMP4Metadata", True) && (info.HasBasicInfo() || (track.tracks.Length() > 0 && config->GetIntValue("Tags", "WriteChapters", True))))
290 {
291 AS::Registry &boca = AS::Registry::Get();
292 AS::TaggerComponent *tagger = (AS::TaggerComponent *) boca.CreateComponentByID("mp4-tag");
293
294 if (tagger != NIL)
295 {
296 tagger->SetConfiguration(config);
297 tagger->RenderStreamInfo(track.outputFile, track);
298
299 boca.DeleteComponent(tagger);
300 }
301 }
302 else
303 {
304 /* Optimize file even when no tags are written.
305 */
306 String tempFile = String(track.outputFile).Append(".temp");
307
308 ex_MP4Optimize(track.outputFile.ConvertTo("UTF-8"), tempFile.ConvertTo("UTF-8"));
309
310 File(track.outputFile).Delete();
311 File(tempFile).Move(track.outputFile);
312 }
313 }
314
315 /* Write ID3v1 tag if requested.
316 */
317 if (mp4File == NIL && config->GetIntValue("Tags", "EnableID3v1", False))
318 {
319 const Info &info = track.GetInfo();
320
321 if (info.HasBasicInfo())
322 {
323 AS::Registry &boca = AS::Registry::Get();
324 AS::TaggerComponent *tagger = (AS::TaggerComponent *) boca.CreateComponentByID("id3v1-tag");
325
326 if (tagger != NIL)
327 {
328 Buffer<unsigned char> id3Buffer;
329
330 tagger->SetConfiguration(config);
331 tagger->RenderBuffer(id3Buffer, track);
332
333 driver->WriteData(id3Buffer, id3Buffer.Size());
334
335 boca.DeleteComponent(tagger);
336 }
337 }
338 }
339
340 /* Update ID3v2 tag with correct chapter marks.
341 */
342 if (mp4File == NIL && config->GetIntValue("Tags", "EnableID3v2", True) && config->GetIntValue(ConfigureVOAAC::ConfigID, "AllowID3v2", False))
343 {
344 if (track.tracks.Length() > 0 && config->GetIntValue("Tags", "WriteChapters", True))
345 {
346 AS::Registry &boca = AS::Registry::Get();
347 AS::TaggerComponent *tagger = (AS::TaggerComponent *) boca.CreateComponentByID("id3v2-tag");
348
349 if (tagger != NIL)
350 {
351 Buffer<unsigned char> id3Buffer;
352
353 tagger->SetConfiguration(config);
354 tagger->RenderBuffer(id3Buffer, track);
355
356 driver->Seek(0);
357 driver->WriteData(id3Buffer, id3Buffer.Size());
358
359 boca.DeleteComponent(tagger);
360 }
361 }
362 }
363
364 return True;
365 }
366
367 Int BoCA::EncoderVOAAC::WriteData(Buffer<UnsignedByte> &data)
368 {
369 const Format &format = track.GetFormat();
370
371 /* Copy data to samples buffer.
372 */
373 Int samples = data.Size() / 2;
374
375 samplesBuffer.Resize(samplesBuffer.Size() + samples);
376
377 memcpy(samplesBuffer + samplesBuffer.Size() - samples, data, data.Size());
378
379 /* Output samples to encoder.
380 */
381 totalSamples += data.Size() / format.channels / (format.bits / 8);
382
383 return EncodeFrames(False);
384 }
385
386 Int BoCA::EncoderVOAAC::EncodeFrames(Bool flush)
387 {
388 const Format &format = track.GetFormat();
389
390 /* Pad end of stream with empty samples.
391 */
392 if (flush)
393 {
394 Int nullSamples = delaySamples;
395
396 if ((samplesBuffer.Size() / format.channels + delaySamples) % frameSize > 0) nullSamples += frameSize - (samplesBuffer.Size() / format.channels + delaySamples) % frameSize;
397
398 samplesBuffer.Resize(samplesBuffer.Size() + nullSamples * format.channels);
399
400 memset(samplesBuffer + samplesBuffer.Size() - nullSamples * format.channels, 0, sizeof(int16_t) * nullSamples * format.channels);
401 }
402
403 /* Encode samples.
404 */
405 Int dataLength = 0;
406 Int framesProcessed = 0;
407
408 Int samplesPerFrame = frameSize * format.channels;
409
410 while (samplesBuffer.Size() - framesProcessed * samplesPerFrame >= samplesPerFrame)
411 {
412 /* Prepare buffer information.
413 */
414 VO_CODECBUFFER input = { 0 };
415 VO_CODECBUFFER output = { 0 };
416 VO_AUDIO_OUTPUTINFO outputInfo = { 0 };
417
418 input.Buffer = (uint8_t *) ((int16_t *) samplesBuffer + framesProcessed * samplesPerFrame);
419 input.Length = samplesPerFrame * sizeof(int16_t);
420
421 /* Hand input data to encoder and retrieve output.
422 */
423 api.SetInputData(handle, &input);
424
425 output.Buffer = outBuffer;
426 output.Length = outBuffer.Size();
427
428 if (api.GetOutputData(handle, &output, &outputInfo) == VO_ERR_NONE)
429 {
430 dataLength += output.Length;
431
432 if (mp4File != NIL) ex_MP4WriteSample(mp4File, mp4Track, (uint8_t *) (unsigned char *) outBuffer, output.Length, frameSize, 0, true);
433 else driver->WriteData(outBuffer, output.Length);
434 }
435
436 framesProcessed++;
437 }
438
439 memmove(samplesBuffer, samplesBuffer + framesProcessed * samplesPerFrame, sizeof(int16_t) * (samplesBuffer.Size() - framesProcessed * samplesPerFrame));
440
441 samplesBuffer.Resize(samplesBuffer.Size() - framesProcessed * samplesPerFrame);
442
443 return dataLength;
444 }
445
446 Int BoCA::EncoderVOAAC::GetSampleRateIndex(Int sampleRate) const
447 {
448 Int sampleRates[12] = { 96000, 88200, 64000, 48000, 44100, 32000,
449 24000, 22050, 16000, 12000, 11025, 8000 };
450
451 for (Int i = 0; i < 12; i++)
452 {
453 if (sampleRate == sampleRates[i]) return i;
454 }
455
456 return -1;
457 }
458
459 Bool BoCA::EncoderVOAAC::SetOutputFormat(Int n)
460 {
461 Config *config = Config::Get();
462
463 if (n == 0 && mp4v2dll != NIL) config->SetIntValue(ConfigureVOAAC::ConfigID, "MP4Container", True);
464 else config->SetIntValue(ConfigureVOAAC::ConfigID, "MP4Container", False);
465
466 return True;
467 }
468
469 String BoCA::EncoderVOAAC::GetOutputFileExtension() const
470 {
471 const Config *config = GetConfiguration();
472
473 if (config->GetIntValue(ConfigureVOAAC::ConfigID, "MP4Container", True))
474 {
475 switch (config->GetIntValue(ConfigureVOAAC::ConfigID, "MP4FileExtension", 0))
476 {
477 default:
478 case 0: return "m4a";
479 case 1: return "m4b";
480 case 2: return "m4r";
481 case 3: return "mp4";
482 }
483 }
484
485 return "aac";
486 }
487
488 Bool BoCA::EncoderVOAAC::ConvertArguments(Config *config)
489 {
490 if (!config->GetIntValue("Settings", "EnableConsole", False)) return False;
491
492 static const String encoderID = "voaacenc-enc";
493
494 /* Set default values.
495 */
496 if (!config->GetIntValue("Settings", "UserSpecifiedConfig", False))
497 {
498 config->SetIntValue(ConfigureVOAAC::ConfigID, "MP4Container", True);
499
500 config->SetIntValue(ConfigureVOAAC::ConfigID, "Bitrate", 96);
501 }
502
503 /* Get command line settings.
504 */
505 Bool rawAAC = config->GetIntValue(encoderID, "Create ADTS AAC files (no MP4 container)", !config->GetIntValue(ConfigureVOAAC::ConfigID, "MP4Container", True));
506
507 Int bitrate = config->GetIntValue(ConfigureVOAAC::ConfigID, "Bitrate", 96);
508
509 if (config->GetIntValue(encoderID, "Set Bitrate per channel", False)) bitrate = config->GetIntValue(encoderID, "Bitrate per channel", bitrate);
510
511 /* Set configuration values.
512 */
513 config->SetIntValue(ConfigureVOAAC::ConfigID, "MP4Container", !rawAAC);
514
515 config->SetIntValue(ConfigureVOAAC::ConfigID, "Bitrate", Math::Max(8, Math::Min(128, bitrate)));
516
517 return True;
518 }
519
520 ConfigLayer *BoCA::EncoderVOAAC::GetConfigurationLayer()
521 {
522 if (configLayer == NIL) configLayer = new ConfigureVOAAC();
523
524 return configLayer;
525 }
526
527 int64_t BoCA::MP4IO_size(void *handle)
528 {
529 Driver *driver = (Driver *) handle;
530
531 return driver->GetSize();
532 }
533
534 int BoCA::MP4IO_seek(void *handle, int64_t pos)
535 {
536 Driver *driver = (Driver *) handle;
537
538 if (driver->Seek(pos) == -1) return 1;
539
540 return 0;
541 }
542
543 int BoCA::MP4IO_write(void *handle, const void *buffer, int64_t size, int64_t *nout)
544 {
545 Driver *driver = (Driver *) handle;
546
547 *nout = driver->WriteData((const UnsignedByte *) buffer, size);
548
549 if (*nout == 0) return 1;
550
551 return 0;
552 }