| 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 "coreaudio.h" |
| 17 | #include "config.h" |
| 18 | |
| 19 | using namespace smooth::IO; |
| 20 | |
| 21 | const String &BoCA::EncoderCoreAudio::GetComponentSpecs() |
| 22 | { |
| 23 | static String componentSpecs; |
| 24 | |
| 25 | #ifndef __APPLE__ |
| 26 | if (coreaudiodll != NIL) |
| 27 | #endif |
| 28 | { |
| 29 | componentSpecs = " \ |
| 30 | \ |
| 31 | <?xml version=\"1.0\" encoding=\"UTF-8\"?> \ |
| 32 | <component> \ |
| 33 | <name>Core Audio AAC/ALAC Encoder</name> \ |
| 34 | <version>1.0</version> \ |
| 35 | <id>coreaudio-enc</id> \ |
| 36 | <type>encoder</type> \ |
| 37 | <replace>faac-enc</replace> \ |
| 38 | <replace>voaacenc-enc</replace> \ |
| 39 | <replace>ffmpeg-alac-enc</replace> \ |
| 40 | <format> \ |
| 41 | <name>MPEG-4 AAC Files</name> \ |
| 42 | <extension>m4a</extension> \ |
| 43 | <extension>m4b</extension> \ |
| 44 | <extension>m4r</extension> \ |
| 45 | <extension>mp4</extension> \ |
| 46 | <tag id=\"mp4-tag\" mode=\"other\">MP4 Metadata</tag> \ |
| 47 | </format> \ |
| 48 | <format> \ |
| 49 | <name>Raw AAC Files</name> \ |
| 50 | <extension>aac</extension> \ |
| 51 | <tag id=\"id3v2-tag\" mode=\"prepend\">ID3v2</tag> \ |
| 52 | </format> \ |
| 53 | <format> \ |
| 54 | <name>Apple Lossless Files</name> \ |
| 55 | <lossless>true</lossless> \ |
| 56 | <extension>m4a</extension> \ |
| 57 | <extension>m4b</extension> \ |
| 58 | <extension>mp4</extension> \ |
| 59 | <tag id=\"mp4-tag\" mode=\"other\">MP4 Metadata</tag> \ |
| 60 | </format> \ |
| 61 | <parameters> \ |
| 62 | <selection name=\"Output format\" argument=\"-f %VALUE\" default=\"AAC\"> \ |
| 63 | <option alias=\"Advanced Audio Coding\">AAC</option> \ |
| 64 | <option alias=\"Apple Lossless Audio Codec\">ALAC</option> \ |
| 65 | </selection> \ |
| 66 | <range name=\"Bitrate per channel\" argument=\"-b %VALUE\" default=\"64\"> \ |
| 67 | <min alias=\"min\">8</min> \ |
| 68 | <max alias=\"max\">192</max> \ |
| 69 | </range> \ |
| 70 | <switch name=\"Create ADTS AAC files (no MP4 container)\" argument=\"--adts\"/> \ |
| 71 | </parameters> \ |
| 72 | </component> \ |
| 73 | \ |
| 74 | "; |
| 75 | } |
| 76 | |
| 77 | return componentSpecs; |
| 78 | } |
| 79 | |
| 80 | Void smooth::AttachDLL(Void *instance) |
| 81 | { |
| 82 | LoadCoreAudioDLL(); |
| 83 | LoadMP4v2DLL(); |
| 84 | } |
| 85 | |
| 86 | Void smooth::DetachDLL() |
| 87 | { |
| 88 | FreeCoreAudioDLL(); |
| 89 | FreeMP4v2DLL(); |
| 90 | } |
| 91 | |
| 92 | namespace BoCA |
| 93 | { |
| 94 | CA::OSStatus AudioFileReadProc(void *, CA::SInt64, CA::UInt32, void *, CA::UInt32 *); |
| 95 | CA::OSStatus AudioFileWriteProc(void *, CA::SInt64, CA::UInt32, const void *, CA::UInt32 *); |
| 96 | CA::SInt64 AudioFileGetSizeProc(void *); |
| 97 | CA::OSStatus AudioFileSetSizeProc(void *, CA::SInt64); |
| 98 | }; |
| 99 | |
| 100 | BoCA::EncoderCoreAudio::EncoderCoreAudio() |
| 101 | { |
| 102 | configLayer = NIL; |
| 103 | config = NIL; |
| 104 | |
| 105 | audioFile = NIL; |
| 106 | |
| 107 | fileType = 0; |
| 108 | |
| 109 | dataOffset = 0; |
| 110 | |
| 111 | frameSize = 0; |
| 112 | |
| 113 | blockSize = 256; |
| 114 | overlap = 24; |
| 115 | |
| 116 | nextWorker = 0; |
| 117 | |
| 118 | packetsWritten = 0; |
| 119 | packetsMissing = 0; |
| 120 | |
| 121 | totalSamples = 0; |
| 122 | } |
| 123 | |
| 124 | BoCA::EncoderCoreAudio::~EncoderCoreAudio() |
| 125 | { |
| 126 | if (config != NIL) Config::Free(config); |
| 127 | |
| 128 | if (configLayer != NIL) Object::DeleteObject(configLayer); |
| 129 | } |
| 130 | |
| 131 | Bool BoCA::EncoderCoreAudio::IsLossless() const |
| 132 | { |
| 133 | /* Get configuration. |
| 134 | */ |
| 135 | const Config *config = GetConfiguration(); |
| 136 | |
| 137 | CA::UInt32 codec = config->GetIntValue(ConfigureCoreAudio::ConfigID, "Codec", CA::kAudioFormatMPEG4AAC); |
| 138 | |
| 139 | /* Signal lossless for ALAC. |
| 140 | */ |
| 141 | if (codec == CA::kAudioFormatAppleLossless) return True; |
| 142 | |
| 143 | return False; |
| 144 | } |
| 145 | |
| 146 | Bool BoCA::EncoderCoreAudio::Activate() |
| 147 | { |
| 148 | static Endianness endianness = CPU().GetEndianness(); |
| 149 | |
| 150 | const Format &format = track.GetFormat(); |
| 151 | |
| 152 | /* Get configuration. |
| 153 | */ |
| 154 | config = Config::Copy(GetConfiguration()); |
| 155 | |
| 156 | ConvertArguments(config); |
| 157 | |
| 158 | CA::UInt32 codec = config->GetIntValue(ConfigureCoreAudio::ConfigID, "Codec", CA::kAudioFormatMPEG4AAC); |
| 159 | Int kbps = config->GetIntValue(ConfigureCoreAudio::ConfigID, "Bitrate", 64); |
| 160 | Bool mp4Container = config->GetIntValue(ConfigureCoreAudio::ConfigID, "MP4Container", True); |
| 161 | |
| 162 | /* Fall back to HE/ELD-SBR if HEv2/ELDv2 is selected for non-stereo input. |
| 163 | */ |
| 164 | if (codec == CA::kAudioFormatMPEG4AAC_HE_V2 && format.channels != 2) codec = CA::kAudioFormatMPEG4AAC_HE; |
| 165 | if (codec == CA::kOptionalAudioFormatMPEG4AAC_ELD_V2 && format.channels != 2) codec = CA::kOptionalAudioFormatMPEG4AAC_ELD_SBR; |
| 166 | |
| 167 | /* Fill out source format description. |
| 168 | */ |
| 169 | CA::AudioStreamBasicDescription sourceFormat = { 0 }; |
| 170 | |
| 171 | sourceFormat.mFormatID = CA::kAudioFormatLinearPCM; |
| 172 | sourceFormat.mFormatFlags = CA::kLinearPCMFormatFlagIsPacked; |
| 173 | sourceFormat.mFormatFlags |= format.fp ? CA::kLinearPCMFormatFlagIsFloat : 0; |
| 174 | sourceFormat.mFormatFlags |= format.sign && !format.fp ? CA::kLinearPCMFormatFlagIsSignedInteger : 0; |
| 175 | sourceFormat.mFormatFlags |= endianness == EndianBig ? CA::kLinearPCMFormatFlagIsBigEndian : 0; |
| 176 | sourceFormat.mSampleRate = format.rate; |
| 177 | sourceFormat.mChannelsPerFrame = format.channels; |
| 178 | sourceFormat.mBitsPerChannel = format.bits; |
| 179 | sourceFormat.mFramesPerPacket = 1; |
| 180 | sourceFormat.mBytesPerFrame = sourceFormat.mChannelsPerFrame * sourceFormat.mBitsPerChannel / 8; |
| 181 | sourceFormat.mBytesPerPacket = sourceFormat.mFramesPerPacket * sourceFormat.mBytesPerFrame; |
| 182 | |
| 183 | /* Fill out destination format description. |
| 184 | */ |
| 185 | CA::AudioStreamBasicDescription destinationFormat = { 0 }; |
| 186 | |
| 187 | destinationFormat.mFormatID = codec; |
| 188 | destinationFormat.mSampleRate = SuperWorker::GetOutputSampleRate(destinationFormat.mFormatID, format.rate); |
| 189 | destinationFormat.mChannelsPerFrame = format.channels; |
| 190 | |
| 191 | CA::UInt32 formatSize = sizeof(destinationFormat); |
| 192 | |
| 193 | CA::AudioFormatGetProperty(CA::kAudioFormatProperty_FormatInfo, 0, NIL, &formatSize, &destinationFormat); |
| 194 | |
| 195 | /* Create audio converter object. |
| 196 | */ |
| 197 | CA::AudioConverterRef converter = NIL; |
| 198 | |
| 199 | if (CA::AudioConverterNew(&sourceFormat, &destinationFormat, &converter) != 0) |
| 200 | { |
| 201 | errorString = "Could not create converter component!"; |
| 202 | errorState = True; |
| 203 | |
| 204 | return False; |
| 205 | } |
| 206 | |
| 207 | frameSize = destinationFormat.mFramesPerPacket; |
| 208 | |
| 209 | /* Set bitrate if format does support bitrates. |
| 210 | */ |
| 211 | CA::UInt32 size = 0; |
| 212 | |
| 213 | if (CA::AudioConverterGetPropertyInfo(converter, CA::kAudioConverterApplicableEncodeBitRates, &size, NIL) == 0) |
| 214 | { |
| 215 | /* Get applicable bitrate values. |
| 216 | */ |
| 217 | CA::UInt32 bitrate = kbps * 1000 * format.channels; |
| 218 | CA::AudioValueRange *bitrateValues = new CA::AudioValueRange [size / sizeof(CA::AudioValueRange)]; |
| 219 | |
| 220 | CA::AudioConverterGetProperty(converter, CA::kAudioConverterApplicableEncodeBitRates, &size, bitrateValues); |
| 221 | |
| 222 | /* Find best supported bitrate. |
| 223 | */ |
| 224 | CA::Float64 nearest = 0xFFFFFFFF; |
| 225 | |
| 226 | for (UnsignedInt i = 0; i < size / sizeof(CA::AudioValueRange); i++) |
| 227 | { |
| 228 | if (bitrate >= bitrateValues[i].mMinimum && bitrate <= bitrateValues[i].mMaximum) nearest = bitrate; |
| 229 | |
| 230 | if (Math::Abs(bitrate - bitrateValues[i].mMinimum) < Math::Abs(bitrate - nearest)) nearest = bitrateValues[i].mMinimum; |
| 231 | if (Math::Abs(bitrate - bitrateValues[i].mMaximum) < Math::Abs(bitrate - nearest)) nearest = bitrateValues[i].mMaximum; |
| 232 | } |
| 233 | |
| 234 | bitrate = nearest; |
| 235 | |
| 236 | delete [] bitrateValues; |
| 237 | |
| 238 | /* Set bitrate on converter. |
| 239 | */ |
| 240 | CA::AudioConverterSetProperty(converter, CA::kAudioConverterEncodeBitRate, sizeof(CA::UInt32), &bitrate); |
| 241 | } |
| 242 | |
| 243 | /* Get file type of output file. |
| 244 | */ |
| 245 | fileType = mp4Container ? CA::kAudioFileM4AType : CA::kAudioFileAAC_ADTSType; |
| 246 | |
| 247 | /* Write ID3v2 tag if requested. |
| 248 | */ |
| 249 | if (fileType == CA::kAudioFileAAC_ADTSType && config->GetIntValue("Tags", "EnableID3v2", True) && config->GetIntValue(ConfigureCoreAudio::ConfigID, "AllowID3v2", False)) |
| 250 | { |
| 251 | const Info &info = track.GetInfo(); |
| 252 | |
| 253 | if (info.HasBasicInfo() || (track.tracks.Length() > 0 && config->GetIntValue("Tags", "WriteChapters", True))) |
| 254 | { |
| 255 | AS::Registry &boca = AS::Registry::Get(); |
| 256 | AS::TaggerComponent *tagger = (AS::TaggerComponent *) boca.CreateComponentByID("id3v2-tag"); |
| 257 | |
| 258 | if (tagger != NIL) |
| 259 | { |
| 260 | Buffer<unsigned char> id3Buffer; |
| 261 | |
| 262 | tagger->SetConfiguration(config); |
| 263 | tagger->RenderBuffer(id3Buffer, track); |
| 264 | |
| 265 | driver->WriteData(id3Buffer, id3Buffer.Size()); |
| 266 | |
| 267 | dataOffset = id3Buffer.Size(); |
| 268 | |
| 269 | boca.DeleteComponent(tagger); |
| 270 | } |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | /* Create audio file object for output file. |
| 275 | */ |
| 276 | CA::AudioFileInitializeWithCallbacks(this, AudioFileReadProc, AudioFileWriteProc, AudioFileGetSizeProc, AudioFileSetSizeProc, fileType, &destinationFormat, 0, &audioFile); |
| 277 | |
| 278 | /* Get magic cookie and supply it to audio file. |
| 279 | */ |
| 280 | CA::UInt32 cookieSize = 0; |
| 281 | |
| 282 | if (CA::AudioConverterGetPropertyInfo(converter, CA::kAudioConverterCompressionMagicCookie, &cookieSize, NIL) == 0) |
| 283 | { |
| 284 | unsigned char *cookie = new unsigned char [cookieSize]; |
| 285 | |
| 286 | CA::AudioConverterGetProperty(converter, CA::kAudioConverterCompressionMagicCookie, &cookieSize, cookie); |
| 287 | CA::AudioFileSetProperty(audioFile, CA::kAudioFilePropertyMagicCookieData, cookieSize, cookie); |
| 288 | |
| 289 | delete [] cookie; |
| 290 | } |
| 291 | |
| 292 | CA::AudioConverterDispose(converter); |
| 293 | |
| 294 | packetsWritten = 0; |
| 295 | packetsMissing = 0; |
| 296 | |
| 297 | totalSamples = 0; |
| 298 | |
| 299 | /* Get number of threads to use. |
| 300 | */ |
| 301 | Bool enableParallel = config->GetIntValue("Resources", "EnableParallelConversions", True); |
| 302 | Bool enableSuperFast = config->GetIntValue("Resources", "EnableSuperFastMode", True) && format.rate == destinationFormat.mSampleRate; |
| 303 | Int numberOfThreads = enableParallel && enableSuperFast ? config->GetIntValue("Resources", "NumberOfConversionThreads", 0) : 1; |
| 304 | |
| 305 | if (enableParallel && enableSuperFast && numberOfThreads <= 1) numberOfThreads = CPU().GetNumCores() + (CPU().GetNumLogicalCPUs() - CPU().GetNumCores()) / 2; |
| 306 | |
| 307 | /* Disable overlap if we use only one thread. |
| 308 | */ |
| 309 | if (numberOfThreads == 1) overlap = 0; |
| 310 | else overlap = 24; |
| 311 | |
| 312 | /* Start up worker threads. |
| 313 | */ |
| 314 | for (Int i = 0; i < numberOfThreads; i++) workers.Add(new SuperWorker(config, format)); |
| 315 | |
| 316 | foreach (SuperWorker *worker, workers) worker->Start(); |
| 317 | |
| 318 | return True; |
| 319 | } |
| 320 | |
| 321 | Bool BoCA::EncoderCoreAudio::Deactivate() |
| 322 | { |
| 323 | /* Get configuration. |
| 324 | */ |
| 325 | CA::UInt32 codec = config->GetIntValue(ConfigureCoreAudio::ConfigID, "Codec", CA::kAudioFormatMPEG4AAC); |
| 326 | |
| 327 | /* Convert final frames. |
| 328 | */ |
| 329 | EncodeFrames(True); |
| 330 | |
| 331 | /* Calculate frame size divider. |
| 332 | */ |
| 333 | const Format &format = track.GetFormat(); |
| 334 | |
| 335 | Int rate = SuperWorker::GetOutputSampleRate(codec, format.rate); |
| 336 | |
| 337 | if (rate == 0) rate = format.rate; |
| 338 | |
| 339 | Float divider = Float(format.rate) / rate; |
| 340 | |
| 341 | if (codec == CA::kAudioFormatMPEG4AAC_HE || |
| 342 | codec == CA::kAudioFormatMPEG4AAC_HE_V2) divider *= 2.0; |
| 343 | |
| 344 | /* Write priming and remainder info. |
| 345 | */ |
| 346 | CA::AudioConverterPrimeInfo initialInfo = workers.GetNth(0 )->GetPrimeInfo(); |
| 347 | CA::AudioConverterPrimeInfo finalInfo = workers.GetNth((nextWorker - 1) % workers.Length())->GetPrimeInfo(); |
| 348 | |
| 349 | if (initialInfo.leadingFrames != 0xFFFFFFFF && finalInfo.trailingFrames != 0xFFFFFFFF) |
| 350 | { |
| 351 | CA::AudioFilePacketTableInfo pti; |
| 352 | |
| 353 | pti.mPrimingFrames = initialInfo.leadingFrames; |
| 354 | pti.mRemainderFrames = finalInfo.trailingFrames; |
| 355 | pti.mNumberValidFrames = Math::Ceil(totalSamples / divider); |
| 356 | |
| 357 | CA::AudioFileSetProperty(audioFile, CA::kAudioFilePropertyPacketTableInfo, sizeof(pti), &pti); |
| 358 | } |
| 359 | |
| 360 | /* Get and set magic cookie again as some |
| 361 | * encoders may change it during encoding. |
| 362 | */ |
| 363 | CA::UInt32 cookieSize = 4; |
| 364 | unsigned char *cookie = workers.GetFirst()->GetMagicCookie(&cookieSize); |
| 365 | |
| 366 | if (cookie != NIL) |
| 367 | { |
| 368 | CA::AudioFileSetProperty(audioFile, CA::kAudioFilePropertyMagicCookieData, cookieSize, cookie); |
| 369 | |
| 370 | delete [] cookie; |
| 371 | } |
| 372 | |
| 373 | /* Tear down worker threads. |
| 374 | */ |
| 375 | foreach (SuperWorker *worker, workers) worker->Quit(); |
| 376 | foreach (SuperWorker *worker, workers) worker->Wait(); |
| 377 | foreach (SuperWorker *worker, workers) delete worker; |
| 378 | |
| 379 | workers.RemoveAll(); |
| 380 | |
| 381 | /* Close audio file. |
| 382 | */ |
| 383 | CA::AudioFileClose(audioFile); |
| 384 | |
| 385 | /* Finish MP4 writing. |
| 386 | */ |
| 387 | if (fileType == CA::kAudioFileM4AType) |
| 388 | { |
| 389 | driver->Close(); |
| 390 | |
| 391 | /* Fix mhdr atom for long running tracks. |
| 392 | */ |
| 393 | Int64 duration = Int64(packetsWritten) * frameSize / divider; |
| 394 | |
| 395 | if (duration > 0xFFFFFFFF) |
| 396 | { |
| 397 | String tempFile = String(track.outputFile).Append(".temp"); |
| 398 | |
| 399 | InStream in(STREAM_FILE, track.outputFile, IS_READ); |
| 400 | OutStream out(STREAM_FILE, tempFile, OS_REPLACE); |
| 401 | |
| 402 | Bool result = FixupDurationAtoms(duration, in, out, in.Size()); |
| 403 | |
| 404 | in.Close(); |
| 405 | out.Close(); |
| 406 | |
| 407 | if (result) |
| 408 | { |
| 409 | File(track.outputFile).Delete(); |
| 410 | File(tempFile).Move(track.outputFile); |
| 411 | } |
| 412 | |
| 413 | File(tempFile).Delete(); |
| 414 | } |
| 415 | |
| 416 | /* Fix number of channels in sound atom. |
| 417 | */ |
| 418 | if (mp4v2dll != NIL) |
| 419 | { |
| 420 | MP4FileHandle mp4File = ex_MP4Modify(track.outputFile, 0); |
| 421 | MP4TrackId mp4Track = ex_MP4FindTrackId(mp4File, 0, MP4_AUDIO_TRACK_TYPE, 0); |
| 422 | |
| 423 | ex_MP4SetTrackIntegerProperty(mp4File, mp4Track, "mdia.minf.stbl.stsd.*[0].channels", format.channels); |
| 424 | ex_MP4Close(mp4File, 0); |
| 425 | } |
| 426 | |
| 427 | /* Write metadata to file. |
| 428 | */ |
| 429 | const Info &info = track.GetInfo(); |
| 430 | |
| 431 | if (config->GetIntValue("Tags", "EnableMP4Metadata", True) && (info.HasBasicInfo() || (track.tracks.Length() > 0 && config->GetIntValue("Tags", "WriteChapters", True)))) |
| 432 | { |
| 433 | AS::Registry &boca = AS::Registry::Get(); |
| 434 | AS::TaggerComponent *tagger = (AS::TaggerComponent *) boca.CreateComponentByID("mp4-tag"); |
| 435 | |
| 436 | if (tagger != NIL) |
| 437 | { |
| 438 | tagger->SetConfiguration(config); |
| 439 | tagger->RenderStreamInfo(track.outputFile, track); |
| 440 | |
| 441 | boca.DeleteComponent(tagger); |
| 442 | } |
| 443 | } |
| 444 | else if (mp4v2dll != NIL) |
| 445 | { |
| 446 | /* Optimize file even when no tags are written. |
| 447 | */ |
| 448 | String tempFile = String(track.outputFile).Append(".temp"); |
| 449 | |
| 450 | ex_MP4Optimize(track.outputFile.ConvertTo("UTF-8"), tempFile.ConvertTo("UTF-8")); |
| 451 | |
| 452 | File(track.outputFile).Delete(); |
| 453 | File(tempFile).Move(track.outputFile); |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | /* Write ID3v1 tag if requested. |
| 458 | */ |
| 459 | if (fileType == CA::kAudioFileAAC_ADTSType && config->GetIntValue("Tags", "EnableID3v1", False)) |
| 460 | { |
| 461 | const Info &info = track.GetInfo(); |
| 462 | |
| 463 | if (info.HasBasicInfo()) |
| 464 | { |
| 465 | AS::Registry &boca = AS::Registry::Get(); |
| 466 | AS::TaggerComponent *tagger = (AS::TaggerComponent *) boca.CreateComponentByID("id3v1-tag"); |
| 467 | |
| 468 | if (tagger != NIL) |
| 469 | { |
| 470 | Buffer<unsigned char> id3Buffer; |
| 471 | |
| 472 | tagger->SetConfiguration(config); |
| 473 | tagger->RenderBuffer(id3Buffer, track); |
| 474 | |
| 475 | driver->WriteData(id3Buffer, id3Buffer.Size()); |
| 476 | |
| 477 | boca.DeleteComponent(tagger); |
| 478 | } |
| 479 | } |
| 480 | } |
| 481 | |
| 482 | /* Update ID3v2 tag with correct chapter marks. |
| 483 | */ |
| 484 | if (fileType == CA::kAudioFileAAC_ADTSType && config->GetIntValue("Tags", "EnableID3v2", True) && config->GetIntValue(ConfigureCoreAudio::ConfigID, "AllowID3v2", False)) |
| 485 | { |
| 486 | if (track.tracks.Length() > 0 && config->GetIntValue("Tags", "WriteChapters", True)) |
| 487 | { |
| 488 | AS::Registry &boca = AS::Registry::Get(); |
| 489 | AS::TaggerComponent *tagger = (AS::TaggerComponent *) boca.CreateComponentByID("id3v2-tag"); |
| 490 | |
| 491 | if (tagger != NIL) |
| 492 | { |
| 493 | Buffer<unsigned char> id3Buffer; |
| 494 | |
| 495 | tagger->SetConfiguration(config); |
| 496 | tagger->RenderBuffer(id3Buffer, track); |
| 497 | |
| 498 | driver->Seek(0); |
| 499 | driver->WriteData(id3Buffer, id3Buffer.Size()); |
| 500 | |
| 501 | boca.DeleteComponent(tagger); |
| 502 | } |
| 503 | } |
| 504 | } |
| 505 | |
| 506 | return True; |
| 507 | } |
| 508 | |
| 509 | Int BoCA::EncoderCoreAudio::WriteData(Buffer<UnsignedByte> &data) |
| 510 | { |
| 511 | const Format &format = track.GetFormat(); |
| 512 | |
| 513 | /* Change to AAC channel order. |
| 514 | */ |
| 515 | if (format.channels == 3) Utilities::ChangeChannelOrder(data, format, Channel::Default_3_0, Channel::AAC_3_0); |
| 516 | else if (format.channels == 5) Utilities::ChangeChannelOrder(data, format, Channel::Default_5_0, Channel::AAC_5_0); |
| 517 | else if (format.channels == 6) Utilities::ChangeChannelOrder(data, format, Channel::Default_5_1, Channel::AAC_5_1); |
| 518 | else if (format.channels == 7) Utilities::ChangeChannelOrder(data, format, Channel::Default_6_1, Channel::AAC_6_1); |
| 519 | else if (format.channels == 8) Utilities::ChangeChannelOrder(data, format, Channel::Default_7_1, Channel::AAC_7_1); |
| 520 | |
| 521 | /* Copy data to samples buffer. |
| 522 | */ |
| 523 | samplesBuffer.Resize(samplesBuffer.Size() + data.Size()); |
| 524 | |
| 525 | memcpy(samplesBuffer + samplesBuffer.Size() - data.Size(), data, data.Size()); |
| 526 | |
| 527 | /* Output samples to encoder. |
| 528 | */ |
| 529 | totalSamples += data.Size() / format.channels / (format.bits / 8); |
| 530 | |
| 531 | return EncodeFrames(False); |
| 532 | } |
| 533 | |
| 534 | Int BoCA::EncoderCoreAudio::EncodeFrames(Bool flush) |
| 535 | { |
| 536 | const Format &format = track.GetFormat(); |
| 537 | |
| 538 | /* Pass samples to workers. |
| 539 | */ |
| 540 | Int framesToProcess = blockSize; |
| 541 | Int framesProcessed = 0; |
| 542 | Int dataLength = 0; |
| 543 | |
| 544 | Int bytesPerFrame = frameSize * format.channels * (format.bits / 8); |
| 545 | |
| 546 | if (flush) framesToProcess = Math::Floor(samplesBuffer.Size() / bytesPerFrame); |
| 547 | |
| 548 | while (samplesBuffer.Size() - framesProcessed * bytesPerFrame >= bytesPerFrame * framesToProcess) |
| 549 | { |
| 550 | SuperWorker *workerToUse = workers.GetNth(nextWorker % workers.Length()); |
| 551 | |
| 552 | workerToUse->WaitUntilReady(); |
| 553 | |
| 554 | /* See if the worker has some packets for us. |
| 555 | */ |
| 556 | if (workerToUse->GetPacketSizes().Length() != 0) dataLength += ProcessPackets(workerToUse->GetPackets(), workerToUse->GetPacketSizes(), workerToUse->GetPacketInfos(), nextWorker == workers.Length(), nextWorker >= 2 * workers.Length()); |
| 557 | |
| 558 | /* Pass new frames to worker. |
| 559 | */ |
| 560 | workerToUse->Encode(samplesBuffer, framesProcessed * bytesPerFrame, flush ? samplesBuffer.Size() : bytesPerFrame * framesToProcess, flush); |
| 561 | |
| 562 | framesProcessed += framesToProcess - (flush ? 0 : overlap); |
| 563 | |
| 564 | nextWorker++; |
| 565 | |
| 566 | if (flush) break; |
| 567 | } |
| 568 | |
| 569 | memmove(samplesBuffer, samplesBuffer + framesProcessed * bytesPerFrame, samplesBuffer.Size() - framesProcessed * bytesPerFrame); |
| 570 | |
| 571 | samplesBuffer.Resize(samplesBuffer.Size() - framesProcessed * bytesPerFrame); |
| 572 | |
| 573 | if (!flush) return dataLength; |
| 574 | |
| 575 | /* Wait for workers to finish and process packets. |
| 576 | */ |
| 577 | for (Int i = 0; i < workers.Length(); i++) |
| 578 | { |
| 579 | SuperWorker *workerToUse = workers.GetNth(nextWorker % workers.Length()); |
| 580 | |
| 581 | workerToUse->WaitUntilReady(); |
| 582 | |
| 583 | /* See if the worker has some packets for us. |
| 584 | */ |
| 585 | if (workerToUse->GetPacketSizes().Length() != 0) dataLength += ProcessPackets(workerToUse->GetPackets(), workerToUse->GetPacketSizes(), workerToUse->GetPacketInfos(), nextWorker == workers.Length(), nextWorker >= 2 * workers.Length()); |
| 586 | |
| 587 | nextWorker++; |
| 588 | } |
| 589 | |
| 590 | return dataLength; |
| 591 | } |
| 592 | |
| 593 | Int BoCA::EncoderCoreAudio::ProcessPackets(const Buffer<unsigned char> &packetData, const Array<Int> &packetSizes, const Array<CA::AudioStreamPacketDescription *> &packetInfos, Bool first, Bool discardMissing) |
| 594 | { |
| 595 | Int offset = 0; |
| 596 | Int dataLength = 0; |
| 597 | |
| 598 | if (discardMissing) packetsMissing = 0; |
| 599 | |
| 600 | if (!first) for (Int i = 0; i < overlap - packetsMissing; i++) offset += packetSizes.GetNth(i); |
| 601 | |
| 602 | for (Int i = 0; i < packetSizes.Length(); i++) |
| 603 | { |
| 604 | if (i < overlap - packetsMissing && !first) continue; |
| 605 | if (packetSizes.GetNth(i) == 0) continue; |
| 606 | |
| 607 | CA::UInt32 packets = 1; |
| 608 | CA::AudioStreamPacketDescription *packet = packetInfos.GetNth(i); |
| 609 | |
| 610 | CA::AudioFileWritePackets(audioFile, False, packetSizes.GetNth(i), packet, packetsWritten, &packets, (unsigned char *) packetData + offset); |
| 611 | |
| 612 | offset += packetSizes.GetNth(i); |
| 613 | dataLength += packetSizes.GetNth(i); |
| 614 | |
| 615 | packetsWritten += packets; |
| 616 | } |
| 617 | |
| 618 | packetsMissing = blockSize - packetSizes.Length(); |
| 619 | |
| 620 | return dataLength; |
| 621 | } |
| 622 | |
| 623 | Bool BoCA::EncoderCoreAudio::SetOutputFormat(Int n) |
| 624 | { |
| 625 | Config *config = Config::Get(); |
| 626 | |
| 627 | if (n != 1) config->SetIntValue(ConfigureCoreAudio::ConfigID, "MP4Container", True); |
| 628 | else config->SetIntValue(ConfigureCoreAudio::ConfigID, "MP4Container", False); |
| 629 | |
| 630 | if (n != 2 && (CA::UInt32) config->GetIntValue(ConfigureCoreAudio::ConfigID, "Codec", CA::kAudioFormatMPEG4AAC) == CA::kAudioFormatAppleLossless) config->SetIntValue(ConfigureCoreAudio::ConfigID, "Codec", CA::kAudioFormatMPEG4AAC); |
| 631 | else if (n == 2) config->SetIntValue(ConfigureCoreAudio::ConfigID, "Codec", CA::kAudioFormatAppleLossless); |
| 632 | |
| 633 | return True; |
| 634 | } |
| 635 | |
| 636 | String BoCA::EncoderCoreAudio::GetOutputFileExtension() const |
| 637 | { |
| 638 | const Config *config = GetConfiguration(); |
| 639 | |
| 640 | if (config->GetIntValue(ConfigureCoreAudio::ConfigID, "MP4Container", True)) |
| 641 | { |
| 642 | switch (config->GetIntValue(ConfigureCoreAudio::ConfigID, "MP4FileExtension", 0)) |
| 643 | { |
| 644 | default: |
| 645 | case 0: return "m4a"; |
| 646 | case 1: return "m4b"; |
| 647 | case 2: return "m4r"; |
| 648 | case 3: return "mp4"; |
| 649 | } |
| 650 | } |
| 651 | |
| 652 | return "aac"; |
| 653 | } |
| 654 | |
| 655 | Bool BoCA::EncoderCoreAudio::FixupDurationAtoms(Int64 duration, InStream &in, OutStream &out, Int64 size, Bool seenMdat) |
| 656 | { |
| 657 | Int64 bytesLeft = size; |
| 658 | Buffer<UnsignedByte> buffer(65536); |
| 659 | |
| 660 | while (bytesLeft > 0) |
| 661 | { |
| 662 | UnsignedInt64 bytes = UnsignedInt32(in.InputNumberRaw(4)); |
| 663 | UnsignedInt32 id = in.InputNumberRaw(4); |
| 664 | Bool use64bit = (bytes == 1); |
| 665 | Int grow = 0; |
| 666 | |
| 667 | if (use64bit == 1) bytes = in.InputNumberRaw(8); |
| 668 | |
| 669 | if (id == 'moov') grow = 36; |
| 670 | else if (id == 'trak') grow = 24; |
| 671 | else if (id == 'mdia' || |
| 672 | id == 'tkhd' || |
| 673 | id == 'mdhd' || |
| 674 | id == 'mvhd') grow = 12; |
| 675 | |
| 676 | out.OutputNumberRaw(use64bit ? 1 : bytes + grow, 4); |
| 677 | out.OutputNumberRaw(id, 4); |
| 678 | |
| 679 | if (use64bit) |
| 680 | { |
| 681 | out.OutputNumberRaw(bytes + grow, 8); |
| 682 | |
| 683 | bytes -= 8; |
| 684 | bytesLeft -= 8; |
| 685 | } |
| 686 | |
| 687 | bytes -= 8; |
| 688 | bytesLeft -= 8; |
| 689 | |
| 690 | /* Recurse into moov, trak, mdia, minf and stbl boxes. |
| 691 | */ |
| 692 | if (id == 'moov' || |
| 693 | id == 'trak' || |
| 694 | id == 'mdia' || |
| 695 | id == 'minf' || |
| 696 | id == 'stbl') |
| 697 | { |
| 698 | if (!FixupDurationAtoms(duration, in, out, bytes, seenMdat)) return False; |
| 699 | |
| 700 | bytesLeft -= bytes; |
| 701 | |
| 702 | continue; |
| 703 | } |
| 704 | |
| 705 | /* Fixup duration atoms. |
| 706 | */ |
| 707 | if (id == 'tkhd' || |
| 708 | id == 'mdhd' || |
| 709 | id == 'mvhd') |
| 710 | { |
| 711 | Int size = 0; |
| 712 | |
| 713 | // Version. |
| 714 | if (in.InputNumberRaw(1) >= 1) return False; |
| 715 | |
| 716 | out.OutputNumberRaw(1, 1); |
| 717 | size += 1; |
| 718 | |
| 719 | // Flags. |
| 720 | out.OutputNumberRaw(in.InputNumberRaw(3), 3); |
| 721 | size += 3; |
| 722 | |
| 723 | // Creation time. |
| 724 | out.OutputNumberRaw(0, 4); |
| 725 | out.OutputNumberRaw(in.InputNumberRaw(4), 4); |
| 726 | size += 4; |
| 727 | |
| 728 | // Modification time. |
| 729 | out.OutputNumberRaw(0, 4); |
| 730 | out.OutputNumberRaw(in.InputNumberRaw(4), 4); |
| 731 | size += 4; |
| 732 | |
| 733 | // Time scale. |
| 734 | out.OutputNumberRaw(in.InputNumberRaw(4), 4); |
| 735 | size += 4; |
| 736 | |
| 737 | // Reserved. |
| 738 | if (id == 'tkhd') |
| 739 | { |
| 740 | out.OutputNumberRaw(in.InputNumberRaw(4), 4); |
| 741 | size += 4; |
| 742 | } |
| 743 | |
| 744 | // Duration. |
| 745 | in.RelSeek(4); |
| 746 | out.OutputNumberRaw(duration, 8); |
| 747 | size += 4; |
| 748 | |
| 749 | // Rest of atom. |
| 750 | in.InputData(buffer, bytes - size); |
| 751 | out.OutputData(buffer, bytes - size); |
| 752 | |
| 753 | bytesLeft -= bytes; |
| 754 | |
| 755 | continue; |
| 756 | } |
| 757 | |
| 758 | /* Fixup chunk offset atoms. |
| 759 | */ |
| 760 | if (!seenMdat && (id == 'stco' || |
| 761 | id == 'co64')) |
| 762 | { |
| 763 | // Version. |
| 764 | out.OutputNumberRaw(in.InputNumberRaw(1), 1); |
| 765 | |
| 766 | // Flags. |
| 767 | out.OutputNumberRaw(in.InputNumberRaw(3), 3); |
| 768 | |
| 769 | // Number of entries. |
| 770 | UnsignedInt32 numEntries = in.InputNumberRaw(4); |
| 771 | |
| 772 | out.OutputNumberRaw(numEntries, 4); |
| 773 | |
| 774 | // Entries. |
| 775 | if (id == 'stco') for (UnsignedInt32 i = 0; i < numEntries; i++) out.OutputNumberRaw(in.InputNumberRaw(4) + 36, 4); |
| 776 | else for (UnsignedInt32 i = 0; i < numEntries; i++) out.OutputNumberRaw(in.InputNumberRaw(8) + 36, 8); |
| 777 | |
| 778 | bytesLeft -= bytes; |
| 779 | |
| 780 | continue; |
| 781 | } |
| 782 | |
| 783 | /* Copy other boxes/atoms. |
| 784 | */ |
| 785 | if (id == 'mdat') seenMdat = True; |
| 786 | |
| 787 | while (bytes > 0) |
| 788 | { |
| 789 | Int size = Math::Min(bytes, buffer.Size()); |
| 790 | |
| 791 | in.InputData(buffer, size); |
| 792 | out.OutputData(buffer, size); |
| 793 | |
| 794 | bytes -= size; |
| 795 | bytesLeft -= size; |
| 796 | } |
| 797 | } |
| 798 | |
| 799 | return True; |
| 800 | } |
| 801 | |
| 802 | Bool BoCA::EncoderCoreAudio::ConvertArguments(Config *config) |
| 803 | { |
| 804 | if (!config->GetIntValue("Settings", "EnableConsole", False)) return False; |
| 805 | |
| 806 | static const String encoderID = "coreaudio-enc"; |
| 807 | |
| 808 | /* Set default values. |
| 809 | */ |
| 810 | if (!config->GetIntValue("Settings", "UserSpecifiedConfig", False)) |
| 811 | { |
| 812 | config->SetIntValue(ConfigureCoreAudio::ConfigID, "MP4Container", True); |
| 813 | |
| 814 | config->SetIntValue(ConfigureCoreAudio::ConfigID, "Codec", CA::kAudioFormatMPEG4AAC); |
| 815 | config->SetIntValue(ConfigureCoreAudio::ConfigID, "Bitrate", 64); |
| 816 | } |
| 817 | |
| 818 | /* Get command line settings. |
| 819 | */ |
| 820 | Bool rawAAC = config->GetIntValue(encoderID, "Create ADTS AAC files (no MP4 container)", !config->GetIntValue(ConfigureCoreAudio::ConfigID, "MP4Container", True)); |
| 821 | |
| 822 | Int bitrate = config->GetIntValue(ConfigureCoreAudio::ConfigID, "Bitrate", 64); |
| 823 | Int format = config->GetIntValue(ConfigureCoreAudio::ConfigID, "Codec", CA::kAudioFormatMPEG4AAC); |
| 824 | String formatName = "AAC"; |
| 825 | |
| 826 | if (format == CA::kAudioFormatAppleLossless) formatName = "ALAC"; |
| 827 | |
| 828 | if (config->GetIntValue(encoderID, "Set Bitrate per channel", False)) bitrate = config->GetIntValue(encoderID, "Bitrate per channel", bitrate); |
| 829 | if (config->GetIntValue(encoderID, "Set Output format", False)) formatName = config->GetStringValue(encoderID, "Output format", formatName).ToUpper(); |
| 830 | |
| 831 | /* Set configuration values. |
| 832 | */ |
| 833 | config->SetIntValue(ConfigureCoreAudio::ConfigID, "MP4Container", !rawAAC || formatName == "ALAC"); |
| 834 | |
| 835 | if (formatName == "AAC" ) format = CA::kAudioFormatMPEG4AAC; |
| 836 | else if (formatName == "ALAC") format = CA::kAudioFormatAppleLossless; |
| 837 | |
| 838 | config->SetIntValue(ConfigureCoreAudio::ConfigID, "Codec", format); |
| 839 | config->SetIntValue(ConfigureCoreAudio::ConfigID, "Bitrate", Math::Max(8, Math::Min(256, bitrate))); |
| 840 | |
| 841 | return True; |
| 842 | } |
| 843 | |
| 844 | ConfigLayer *BoCA::EncoderCoreAudio::GetConfigurationLayer() |
| 845 | { |
| 846 | if (configLayer == NIL) configLayer = new ConfigureCoreAudio(); |
| 847 | |
| 848 | return configLayer; |
| 849 | } |
| 850 | |
| 851 | CA::OSStatus BoCA::AudioFileReadProc(void *inClientData, CA::SInt64 inPosition, CA::UInt32 requestCount, void *buffer, CA::UInt32 *actualCount) |
| 852 | { |
| 853 | EncoderCoreAudio *filter = (EncoderCoreAudio *) inClientData; |
| 854 | |
| 855 | filter->driver->Seek(inPosition + filter->dataOffset); |
| 856 | |
| 857 | *actualCount = filter->driver->ReadData((UnsignedByte *) buffer, requestCount); |
| 858 | |
| 859 | return 0; |
| 860 | } |
| 861 | |
| 862 | CA::OSStatus BoCA::AudioFileWriteProc(void *inClientData, CA::SInt64 inPosition, CA::UInt32 requestCount, const void *buffer, CA::UInt32 *actualCount) |
| 863 | { |
| 864 | EncoderCoreAudio *filter = (EncoderCoreAudio *) inClientData; |
| 865 | |
| 866 | filter->driver->Seek(inPosition + filter->dataOffset); |
| 867 | |
| 868 | *actualCount = filter->driver->WriteData((UnsignedByte *) buffer, requestCount); |
| 869 | |
| 870 | return 0; |
| 871 | } |
| 872 | |
| 873 | CA::SInt64 BoCA::AudioFileGetSizeProc(void *inClientData) |
| 874 | { |
| 875 | EncoderCoreAudio *filter = (EncoderCoreAudio *) inClientData; |
| 876 | |
| 877 | return filter->driver->GetSize() - filter->dataOffset; |
| 878 | } |
| 879 | |
| 880 | CA::OSStatus BoCA::AudioFileSetSizeProc(void *inClientData, CA::SInt64 inSize) |
| 881 | { |
| 882 | EncoderCoreAudio *filter = (EncoderCoreAudio *) inClientData; |
| 883 | |
| 884 | filter->driver->Truncate(inSize + filter->dataOffset); |
| 885 | |
| 886 | return 0; |
| 887 | } |