| 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 | #ifdef __WIN32__ |
| 17 | # include <windows.h> |
| 18 | #else |
| 19 | # include <sys/mman.h> |
| 20 | # include <sys/sem.h> |
| 21 | # include <sys/wait.h> |
| 22 | # include <stdlib.h> |
| 23 | # include <unistd.h> |
| 24 | # include <fcntl.h> |
| 25 | # include <pthread.h> |
| 26 | #endif |
| 27 | |
| 28 | #include "coreaudioconnect.h" |
| 29 | #include "dllinterface.h" |
| 30 | #include "config.h" |
| 31 | |
| 32 | using namespace smooth::IO; |
| 33 | |
| 34 | const String &BoCA::EncoderCoreAudioConnect::GetComponentSpecs() |
| 35 | { |
| 36 | static String componentSpecs; |
| 37 | |
| 38 | #ifndef __WIN32__ |
| 39 | const Array<String> &args = GUI::Application::GetArguments(); |
| 40 | |
| 41 | foreach (const String &arg, args) |
| 42 | { |
| 43 | if (arg == "--disable-wine") return componentSpecs; |
| 44 | } |
| 45 | #endif |
| 46 | |
| 47 | if (EncoderCoreAudioConnect().IsReady()) |
| 48 | { |
| 49 | componentSpecs = " \ |
| 50 | \ |
| 51 | <?xml version=\"1.0\" encoding=\"UTF-8\"?> \ |
| 52 | <component> \ |
| 53 | <name>Core Audio AAC/ALAC Encoder</name> \ |
| 54 | <version>1.0</version> \ |
| 55 | <id>coreaudio-enc</id> \ |
| 56 | <type>encoder</type> \ |
| 57 | <replace>faac-enc</replace> \ |
| 58 | <replace>voaacenc-enc</replace> \ |
| 59 | <replace>ffmpeg-alac-enc</replace> \ |
| 60 | <format> \ |
| 61 | <name>MPEG-4 AAC Files</name> \ |
| 62 | <extension>m4a</extension> \ |
| 63 | <extension>m4b</extension> \ |
| 64 | <extension>m4r</extension> \ |
| 65 | <extension>mp4</extension> \ |
| 66 | <tag id=\"mp4-tag\" mode=\"other\">MP4 Metadata</tag> \ |
| 67 | </format> \ |
| 68 | <format> \ |
| 69 | <name>Raw AAC Files</name> \ |
| 70 | <extension>aac</extension> \ |
| 71 | <tag id=\"id3v2-tag\" mode=\"prepend\">ID3v2</tag> \ |
| 72 | </format> \ |
| 73 | <format> \ |
| 74 | <name>Apple Lossless Files</name> \ |
| 75 | <extension>m4a</extension> \ |
| 76 | <extension>m4b</extension> \ |
| 77 | <extension>mp4</extension> \ |
| 78 | <tag id=\"mp4-tag\" mode=\"other\">MP4 Metadata</tag> \ |
| 79 | </format> \ |
| 80 | <parameters> \ |
| 81 | <selection name=\"Output format\" argument=\"-f %VALUE\" default=\"AAC\"> \ |
| 82 | <option alias=\"Advanced Audio Coding\">AAC</option> \ |
| 83 | <option alias=\"Apple Lossless Audio Codec\">ALAC</option> \ |
| 84 | </selection> \ |
| 85 | <range name=\"Bitrate per channel\" argument=\"-b %VALUE\" default=\"64\"> \ |
| 86 | <min alias=\"min\">8</min> \ |
| 87 | <max alias=\"max\">192</max> \ |
| 88 | </range> \ |
| 89 | <switch name=\"Create ADTS AAC files (no MP4 container)\" argument=\"--adts\"/> \ |
| 90 | </parameters> \ |
| 91 | </component> \ |
| 92 | \ |
| 93 | "; |
| 94 | } |
| 95 | |
| 96 | return componentSpecs; |
| 97 | } |
| 98 | |
| 99 | Void smooth::AttachDLL(Void *instance) |
| 100 | { |
| 101 | LoadMP4v2DLL(); |
| 102 | } |
| 103 | |
| 104 | Void smooth::DetachDLL() |
| 105 | { |
| 106 | FreeMP4v2DLL(); |
| 107 | } |
| 108 | |
| 109 | BoCA::EncoderCoreAudioConnect::EncoderCoreAudioConnect() |
| 110 | { |
| 111 | #ifdef __WIN32__ |
| 112 | connector = NIL; |
| 113 | mapping = NIL; |
| 114 | #else |
| 115 | connector = -1; |
| 116 | mapping = -1; |
| 117 | #endif |
| 118 | |
| 119 | comm = NIL; |
| 120 | connected = False; |
| 121 | ready = False; |
| 122 | |
| 123 | fileType = 0; |
| 124 | |
| 125 | configLayer = NIL; |
| 126 | config = NIL; |
| 127 | } |
| 128 | |
| 129 | BoCA::EncoderCoreAudioConnect::~EncoderCoreAudioConnect() |
| 130 | { |
| 131 | if (connected) Disconnect(); |
| 132 | |
| 133 | if (config != NIL) Config::Free(config); |
| 134 | |
| 135 | if (configLayer != NIL) Object::DeleteObject(configLayer); |
| 136 | } |
| 137 | |
| 138 | Bool BoCA::EncoderCoreAudioConnect::IsReady() const |
| 139 | { |
| 140 | if (!connected) const_cast<EncoderCoreAudioConnect *>(this)->Connect(); |
| 141 | |
| 142 | return ready; |
| 143 | } |
| 144 | |
| 145 | Bool BoCA::EncoderCoreAudioConnect::IsLossless() const |
| 146 | { |
| 147 | /* Get configuration. |
| 148 | */ |
| 149 | const Config *config = GetConfiguration(); |
| 150 | |
| 151 | Int codec = config->GetIntValue(ConfigureCoreAudio::ConfigID, "Codec", CA::kAudioFormatMPEG4AAC); |
| 152 | |
| 153 | /* Signal lossless for ALAC. |
| 154 | */ |
| 155 | if (codec == CA::kAudioFormatAppleLossless) return True; |
| 156 | |
| 157 | return False; |
| 158 | } |
| 159 | |
| 160 | Bool BoCA::EncoderCoreAudioConnect::Activate() |
| 161 | { |
| 162 | const Format &format = track.GetFormat(); |
| 163 | |
| 164 | /* Get configuration. |
| 165 | */ |
| 166 | config = Config::Copy(GetConfiguration()); |
| 167 | |
| 168 | ConvertArguments(config); |
| 169 | |
| 170 | Int codec = config->GetIntValue(ConfigureCoreAudio::ConfigID, "Codec", CA::kAudioFormatMPEG4AAC); |
| 171 | Int kbps = config->GetIntValue(ConfigureCoreAudio::ConfigID, "Bitrate", 64); |
| 172 | Bool mp4Container = config->GetIntValue(ConfigureCoreAudio::ConfigID, "MP4Container", True); |
| 173 | |
| 174 | /* Fall back to HE/ELD-SBR if HEv2/ELDv2 is selected for non-stereo input. |
| 175 | */ |
| 176 | if (codec == CA::kAudioFormatMPEG4AAC_HE_V2 && format.channels != 2) codec = CA::kAudioFormatMPEG4AAC_HE; |
| 177 | if (codec == CA::kAudioFormatMPEG4AAC_ELD_V2 && format.channels != 2) codec = CA::kAudioFormatMPEG4AAC_ELD_SBR; |
| 178 | |
| 179 | /* Get file type of output file. |
| 180 | */ |
| 181 | fileType = mp4Container ? CA::kAudioFileM4AType : CA::kAudioFileAAC_ADTSType; |
| 182 | |
| 183 | /* Write ID3v2 tag if requested. |
| 184 | */ |
| 185 | if (fileType == CA::kAudioFileAAC_ADTSType && config->GetIntValue("Tags", "EnableID3v2", True) && config->GetIntValue(ConfigureCoreAudio::ConfigID, "AllowID3v2", False)) |
| 186 | { |
| 187 | const Info &info = track.GetInfo(); |
| 188 | |
| 189 | if (info.HasBasicInfo() || (track.tracks.Length() > 0 && config->GetIntValue("Tags", "WriteChapters", True))) |
| 190 | { |
| 191 | AS::Registry &boca = AS::Registry::Get(); |
| 192 | AS::TaggerComponent *tagger = (AS::TaggerComponent *) boca.CreateComponentByID("id3v2-tag"); |
| 193 | |
| 194 | if (tagger != NIL) |
| 195 | { |
| 196 | Buffer<unsigned char> id3Buffer; |
| 197 | |
| 198 | tagger->SetConfiguration(config); |
| 199 | tagger->RenderBuffer(id3Buffer, track); |
| 200 | |
| 201 | driver->WriteData(id3Buffer, id3Buffer.Size()); |
| 202 | |
| 203 | boca.DeleteComponent(tagger); |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | driver->Close(); |
| 209 | |
| 210 | /* Send Setup command. |
| 211 | */ |
| 212 | if (!connected) Connect(); |
| 213 | |
| 214 | comm->command = CommCommandSetup; |
| 215 | comm->length = sizeof(CoreAudioCommSetup); |
| 216 | |
| 217 | ((CoreAudioCommSetup *) &comm->data)->codec = codec; |
| 218 | ((CoreAudioCommSetup *) &comm->data)->bitrate = kbps * 1000 * format.channels; |
| 219 | ((CoreAudioCommSetup *) &comm->data)->format = mp4Container; |
| 220 | |
| 221 | ((CoreAudioCommSetup *) &comm->data)->channels = format.channels; |
| 222 | ((CoreAudioCommSetup *) &comm->data)->rate = format.rate; |
| 223 | ((CoreAudioCommSetup *) &comm->data)->bits = format.bits; |
| 224 | |
| 225 | ((CoreAudioCommSetup *) &comm->data)->fp = format.fp; |
| 226 | ((CoreAudioCommSetup *) &comm->data)->sign = format.sign; |
| 227 | |
| 228 | char *outfile = track.outputFile.ConvertTo("UTF-8"); |
| 229 | |
| 230 | memcpy(((CoreAudioCommSetup *) &comm->data)->file, outfile, strlen(outfile) + 1); |
| 231 | |
| 232 | ProcessConnectorCommand(); |
| 233 | |
| 234 | if (comm->status != CommStatusReady) return False; |
| 235 | |
| 236 | return True; |
| 237 | } |
| 238 | |
| 239 | Bool BoCA::EncoderCoreAudioConnect::Deactivate() |
| 240 | { |
| 241 | /* Send Finish command. |
| 242 | */ |
| 243 | if (!connected) Connect(); |
| 244 | |
| 245 | comm->command = CommCommandFinish; |
| 246 | comm->length = 0; |
| 247 | |
| 248 | ProcessConnectorCommand(); |
| 249 | |
| 250 | if (comm->status != CommStatusReady) return False; |
| 251 | |
| 252 | /* Finish MP4 writing. |
| 253 | */ |
| 254 | if (fileType == CA::kAudioFileM4AType) |
| 255 | { |
| 256 | /* Get total duration. |
| 257 | */ |
| 258 | comm->command = CommCommandDuration; |
| 259 | comm->length = 0; |
| 260 | |
| 261 | ProcessConnectorCommand(); |
| 262 | |
| 263 | if (comm->status != CommStatusReady) return False; |
| 264 | |
| 265 | Int64 duration = Int64(comm->data[0]) << 32 | comm->data[1]; |
| 266 | |
| 267 | /* Fix mhdr atom for long running tracks. |
| 268 | */ |
| 269 | if (duration > 0xFFFFFFFF) |
| 270 | { |
| 271 | String tempFile = String(track.outputFile).Append(".temp"); |
| 272 | |
| 273 | InStream in(STREAM_FILE, track.outputFile, IS_READ); |
| 274 | OutStream out(STREAM_FILE, tempFile, OS_REPLACE); |
| 275 | |
| 276 | Bool result = FixupDurationAtoms(duration, in, out, in.Size()); |
| 277 | |
| 278 | in.Close(); |
| 279 | out.Close(); |
| 280 | |
| 281 | if (result) |
| 282 | { |
| 283 | File(track.outputFile).Delete(); |
| 284 | File(tempFile).Move(track.outputFile); |
| 285 | } |
| 286 | |
| 287 | File(tempFile).Delete(); |
| 288 | } |
| 289 | |
| 290 | /* Fix number of channels in sound atom. |
| 291 | */ |
| 292 | if (mp4v2dll != NIL) |
| 293 | { |
| 294 | const Format &format = track.GetFormat(); |
| 295 | |
| 296 | MP4FileHandle mp4File = ex_MP4Modify(track.outputFile, 0); |
| 297 | MP4TrackId mp4Track = ex_MP4FindTrackId(mp4File, 0, MP4_AUDIO_TRACK_TYPE, 0); |
| 298 | |
| 299 | ex_MP4SetTrackIntegerProperty(mp4File, mp4Track, "mdia.minf.stbl.stsd.*[0].channels", format.channels); |
| 300 | ex_MP4Close(mp4File, 0); |
| 301 | } |
| 302 | |
| 303 | /* Write metadata to file. |
| 304 | */ |
| 305 | const Info &info = track.GetInfo(); |
| 306 | |
| 307 | if (config->GetIntValue("Tags", "EnableMP4Metadata", True) && (info.HasBasicInfo() || (track.tracks.Length() > 0 && config->GetIntValue("Tags", "WriteChapters", True)))) |
| 308 | { |
| 309 | AS::Registry &boca = AS::Registry::Get(); |
| 310 | AS::TaggerComponent *tagger = (AS::TaggerComponent *) boca.CreateComponentByID("mp4-tag"); |
| 311 | |
| 312 | if (tagger != NIL) |
| 313 | { |
| 314 | tagger->SetConfiguration(config); |
| 315 | tagger->RenderStreamInfo(track.outputFile, track); |
| 316 | |
| 317 | boca.DeleteComponent(tagger); |
| 318 | } |
| 319 | } |
| 320 | else if (mp4v2dll != NIL) |
| 321 | { |
| 322 | /* Optimize file even when no tags are written. |
| 323 | */ |
| 324 | String tempFile = String(track.outputFile).Append(".temp"); |
| 325 | |
| 326 | ex_MP4Optimize(track.outputFile.ConvertTo("UTF-8"), tempFile.ConvertTo("UTF-8")); |
| 327 | |
| 328 | File(track.outputFile).Delete(); |
| 329 | File(tempFile).Move(track.outputFile); |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | /* Write ID3v1 tag if requested. |
| 334 | */ |
| 335 | if (fileType == CA::kAudioFileAAC_ADTSType && config->GetIntValue("Tags", "EnableID3v1", False)) |
| 336 | { |
| 337 | const Info &info = track.GetInfo(); |
| 338 | |
| 339 | if (info.HasBasicInfo()) |
| 340 | { |
| 341 | AS::Registry &boca = AS::Registry::Get(); |
| 342 | AS::TaggerComponent *tagger = (AS::TaggerComponent *) boca.CreateComponentByID("id3v1-tag"); |
| 343 | |
| 344 | if (tagger != NIL) |
| 345 | { |
| 346 | OutStream out(STREAM_FILE, track.outputFile, OS_APPEND); |
| 347 | Buffer<unsigned char> id3Buffer; |
| 348 | |
| 349 | tagger->SetConfiguration(config); |
| 350 | tagger->RenderBuffer(id3Buffer, track); |
| 351 | |
| 352 | out.OutputData(id3Buffer, id3Buffer.Size()); |
| 353 | |
| 354 | boca.DeleteComponent(tagger); |
| 355 | } |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | /* Update ID3v2 tag with correct chapter marks. |
| 360 | */ |
| 361 | if (fileType == CA::kAudioFileAAC_ADTSType && config->GetIntValue("Tags", "EnableID3v2", True) && config->GetIntValue(ConfigureCoreAudio::ConfigID, "AllowID3v2", False)) |
| 362 | { |
| 363 | if (track.tracks.Length() > 0 && config->GetIntValue("Tags", "WriteChapters", True)) |
| 364 | { |
| 365 | AS::Registry &boca = AS::Registry::Get(); |
| 366 | AS::TaggerComponent *tagger = (AS::TaggerComponent *) boca.CreateComponentByID("id3v2-tag"); |
| 367 | |
| 368 | if (tagger != NIL) |
| 369 | { |
| 370 | OutStream out(STREAM_FILE, track.outputFile, OS_APPEND); |
| 371 | Buffer<unsigned char> id3Buffer; |
| 372 | |
| 373 | tagger->SetConfiguration(config); |
| 374 | tagger->RenderBuffer(id3Buffer, track); |
| 375 | |
| 376 | out.Seek(0); |
| 377 | out.OutputData(id3Buffer, id3Buffer.Size()); |
| 378 | |
| 379 | boca.DeleteComponent(tagger); |
| 380 | } |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | return True; |
| 385 | } |
| 386 | |
| 387 | Int BoCA::EncoderCoreAudioConnect::WriteData(Buffer<UnsignedByte> &data) |
| 388 | { |
| 389 | const Format &format = track.GetFormat(); |
| 390 | |
| 391 | /* Change to AAC channel order. |
| 392 | */ |
| 393 | if (format.channels == 3) Utilities::ChangeChannelOrder(data, format, Channel::Default_3_0, Channel::AAC_3_0); |
| 394 | else if (format.channels == 5) Utilities::ChangeChannelOrder(data, format, Channel::Default_5_0, Channel::AAC_5_0); |
| 395 | else if (format.channels == 6) Utilities::ChangeChannelOrder(data, format, Channel::Default_5_1, Channel::AAC_5_1); |
| 396 | else if (format.channels == 7) Utilities::ChangeChannelOrder(data, format, Channel::Default_6_1, Channel::AAC_6_1); |
| 397 | else if (format.channels == 8) Utilities::ChangeChannelOrder(data, format, Channel::Default_7_1, Channel::AAC_7_1); |
| 398 | |
| 399 | /* Send Encode command. |
| 400 | */ |
| 401 | if (!connected) Connect(); |
| 402 | |
| 403 | comm->command = CommCommandEncode; |
| 404 | comm->length = data.Size(); |
| 405 | |
| 406 | memcpy(comm->data, data, data.Size()); |
| 407 | |
| 408 | ProcessConnectorCommand(); |
| 409 | |
| 410 | if (comm->status != CommStatusReady) return -1; |
| 411 | else return data.Size(); |
| 412 | } |
| 413 | |
| 414 | Bool BoCA::EncoderCoreAudioConnect::SetOutputFormat(Int n) |
| 415 | { |
| 416 | Config *config = Config::Get(); |
| 417 | |
| 418 | if (n != 1) config->SetIntValue(ConfigureCoreAudio::ConfigID, "MP4Container", True); |
| 419 | else config->SetIntValue(ConfigureCoreAudio::ConfigID, "MP4Container", False); |
| 420 | |
| 421 | if (n != 2 && config->GetIntValue(ConfigureCoreAudio::ConfigID, "Codec", CA::kAudioFormatMPEG4AAC) == CA::kAudioFormatAppleLossless) config->SetIntValue(ConfigureCoreAudio::ConfigID, "Codec", CA::kAudioFormatMPEG4AAC); |
| 422 | else if (n == 2) config->SetIntValue(ConfigureCoreAudio::ConfigID, "Codec", CA::kAudioFormatAppleLossless); |
| 423 | |
| 424 | return True; |
| 425 | } |
| 426 | |
| 427 | String BoCA::EncoderCoreAudioConnect::GetOutputFileExtension() const |
| 428 | { |
| 429 | const Config *config = GetConfiguration(); |
| 430 | |
| 431 | if (config->GetIntValue(ConfigureCoreAudio::ConfigID, "MP4Container", True)) |
| 432 | { |
| 433 | switch (config->GetIntValue(ConfigureCoreAudio::ConfigID, "MP4FileExtension", 0)) |
| 434 | { |
| 435 | default: |
| 436 | case 0: return "m4a"; |
| 437 | case 1: return "m4b"; |
| 438 | case 2: return "m4r"; |
| 439 | case 3: return "mp4"; |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | return "aac"; |
| 444 | } |
| 445 | |
| 446 | Bool BoCA::EncoderCoreAudioConnect::FixupDurationAtoms(Int64 duration, InStream &in, OutStream &out, Int64 size, Bool seenMdat) |
| 447 | { |
| 448 | Int64 bytesLeft = size; |
| 449 | Buffer<UnsignedByte> buffer(65536); |
| 450 | |
| 451 | while (bytesLeft > 0) |
| 452 | { |
| 453 | UnsignedInt64 bytes = UnsignedInt32(in.InputNumberRaw(4)); |
| 454 | UnsignedInt32 id = in.InputNumberRaw(4); |
| 455 | Bool use64bit = (bytes == 1); |
| 456 | Int grow = 0; |
| 457 | |
| 458 | if (use64bit == 1) bytes = in.InputNumberRaw(8); |
| 459 | |
| 460 | if (id == 'moov') grow = 36; |
| 461 | else if (id == 'trak') grow = 24; |
| 462 | else if (id == 'mdia' || |
| 463 | id == 'tkhd' || |
| 464 | id == 'mdhd' || |
| 465 | id == 'mvhd') grow = 12; |
| 466 | |
| 467 | out.OutputNumberRaw(use64bit ? 1 : bytes + grow, 4); |
| 468 | out.OutputNumberRaw(id, 4); |
| 469 | |
| 470 | if (use64bit) |
| 471 | { |
| 472 | out.OutputNumberRaw(bytes + grow, 8); |
| 473 | |
| 474 | bytes -= 8; |
| 475 | bytesLeft -= 8; |
| 476 | } |
| 477 | |
| 478 | bytes -= 8; |
| 479 | bytesLeft -= 8; |
| 480 | |
| 481 | /* Recurse into moov, trak, mdia, minf and stbl boxes. |
| 482 | */ |
| 483 | if (id == 'moov' || |
| 484 | id == 'trak' || |
| 485 | id == 'mdia' || |
| 486 | id == 'minf' || |
| 487 | id == 'stbl') |
| 488 | { |
| 489 | if (!FixupDurationAtoms(duration, in, out, bytes, seenMdat)) return False; |
| 490 | |
| 491 | bytesLeft -= bytes; |
| 492 | |
| 493 | continue; |
| 494 | } |
| 495 | |
| 496 | /* Fixup duration atoms. |
| 497 | */ |
| 498 | if (id == 'tkhd' || |
| 499 | id == 'mdhd' || |
| 500 | id == 'mvhd') |
| 501 | { |
| 502 | Int size = 0; |
| 503 | |
| 504 | // Version. |
| 505 | if (in.InputNumberRaw(1) >= 1) return False; |
| 506 | |
| 507 | out.OutputNumberRaw(1, 1); |
| 508 | size += 1; |
| 509 | |
| 510 | // Flags. |
| 511 | out.OutputNumberRaw(in.InputNumberRaw(3), 3); |
| 512 | size += 3; |
| 513 | |
| 514 | // Creation time. |
| 515 | out.OutputNumberRaw(0, 4); |
| 516 | out.OutputNumberRaw(in.InputNumberRaw(4), 4); |
| 517 | size += 4; |
| 518 | |
| 519 | // Modification time. |
| 520 | out.OutputNumberRaw(0, 4); |
| 521 | out.OutputNumberRaw(in.InputNumberRaw(4), 4); |
| 522 | size += 4; |
| 523 | |
| 524 | // Time scale. |
| 525 | out.OutputNumberRaw(in.InputNumberRaw(4), 4); |
| 526 | size += 4; |
| 527 | |
| 528 | // Reserved. |
| 529 | if (id == 'tkhd') |
| 530 | { |
| 531 | out.OutputNumberRaw(in.InputNumberRaw(4), 4); |
| 532 | size += 4; |
| 533 | } |
| 534 | |
| 535 | // Duration. |
| 536 | in.RelSeek(4); |
| 537 | out.OutputNumberRaw(duration, 8); |
| 538 | size += 4; |
| 539 | |
| 540 | // Rest of atom. |
| 541 | in.InputData(buffer, bytes - size); |
| 542 | out.OutputData(buffer, bytes - size); |
| 543 | |
| 544 | bytesLeft -= bytes; |
| 545 | |
| 546 | continue; |
| 547 | } |
| 548 | |
| 549 | /* Fixup chunk offset atoms. |
| 550 | */ |
| 551 | if (!seenMdat && (id == 'stco' || |
| 552 | id == 'co64')) |
| 553 | { |
| 554 | // Version. |
| 555 | out.OutputNumberRaw(in.InputNumberRaw(1), 1); |
| 556 | |
| 557 | // Flags. |
| 558 | out.OutputNumberRaw(in.InputNumberRaw(3), 3); |
| 559 | |
| 560 | // Number of entries. |
| 561 | UnsignedInt32 numEntries = in.InputNumberRaw(4); |
| 562 | |
| 563 | out.OutputNumberRaw(numEntries, 4); |
| 564 | |
| 565 | // Entries. |
| 566 | if (id == 'stco') for (UnsignedInt32 i = 0; i < numEntries; i++) out.OutputNumberRaw(in.InputNumberRaw(4) + 36, 4); |
| 567 | else for (UnsignedInt32 i = 0; i < numEntries; i++) out.OutputNumberRaw(in.InputNumberRaw(8) + 36, 8); |
| 568 | |
| 569 | bytesLeft -= bytes; |
| 570 | |
| 571 | continue; |
| 572 | } |
| 573 | |
| 574 | /* Copy other boxes/atoms. |
| 575 | */ |
| 576 | if (id == 'mdat') seenMdat = True; |
| 577 | |
| 578 | while (bytes > 0) |
| 579 | { |
| 580 | Int size = Math::Min(bytes, buffer.Size()); |
| 581 | |
| 582 | in.InputData(buffer, size); |
| 583 | out.OutputData(buffer, size); |
| 584 | |
| 585 | bytes -= size; |
| 586 | bytesLeft -= size; |
| 587 | } |
| 588 | } |
| 589 | |
| 590 | return True; |
| 591 | } |
| 592 | |
| 593 | Bool BoCA::EncoderCoreAudioConnect::ConvertArguments(Config *config) |
| 594 | { |
| 595 | if (!config->GetIntValue("Settings", "EnableConsole", False)) return False; |
| 596 | |
| 597 | static const String encoderID = "coreaudio-enc"; |
| 598 | |
| 599 | /* Set default values. |
| 600 | */ |
| 601 | if (!config->GetIntValue("Settings", "UserSpecifiedConfig", False)) |
| 602 | { |
| 603 | config->SetIntValue(ConfigureCoreAudio::ConfigID, "MP4Container", True); |
| 604 | |
| 605 | config->SetIntValue(ConfigureCoreAudio::ConfigID, "Codec", CA::kAudioFormatMPEG4AAC); |
| 606 | config->SetIntValue(ConfigureCoreAudio::ConfigID, "Bitrate", 64); |
| 607 | } |
| 608 | |
| 609 | /* Get command line settings. |
| 610 | */ |
| 611 | Bool rawAAC = config->GetIntValue(encoderID, "Create ADTS AAC files (no MP4 container)", !config->GetIntValue(ConfigureCoreAudio::ConfigID, "MP4Container", True)); |
| 612 | |
| 613 | Int bitrate = config->GetIntValue(ConfigureCoreAudio::ConfigID, "Bitrate", 64); |
| 614 | Int format = config->GetIntValue(ConfigureCoreAudio::ConfigID, "Codec", CA::kAudioFormatMPEG4AAC); |
| 615 | String formatName = "AAC"; |
| 616 | |
| 617 | if (format == CA::kAudioFormatAppleLossless) formatName = "ALAC"; |
| 618 | |
| 619 | if (config->GetIntValue(encoderID, "Set Bitrate per channel", False)) bitrate = config->GetIntValue(encoderID, "Bitrate per channel", bitrate); |
| 620 | if (config->GetIntValue(encoderID, "Set Output format", False)) formatName = config->GetStringValue(encoderID, "Output format", formatName).ToUpper(); |
| 621 | |
| 622 | /* Set configuration values. |
| 623 | */ |
| 624 | config->SetIntValue(ConfigureCoreAudio::ConfigID, "MP4Container", !rawAAC || formatName == "ALAC"); |
| 625 | |
| 626 | if (formatName == "AAC" ) format = CA::kAudioFormatMPEG4AAC; |
| 627 | else if (formatName == "ALAC") format = CA::kAudioFormatAppleLossless; |
| 628 | |
| 629 | config->SetIntValue(ConfigureCoreAudio::ConfigID, "Codec", format); |
| 630 | config->SetIntValue(ConfigureCoreAudio::ConfigID, "Bitrate", Math::Max(8, Math::Min(256, bitrate))); |
| 631 | |
| 632 | return True; |
| 633 | } |
| 634 | |
| 635 | ConfigLayer *BoCA::EncoderCoreAudioConnect::GetConfigurationLayer() |
| 636 | { |
| 637 | if (configLayer == NIL) |
| 638 | { |
| 639 | static CoreAudioCommCodecs codecs; |
| 640 | static Bool initialized = False; |
| 641 | |
| 642 | if (!initialized) |
| 643 | { |
| 644 | /* Send Codecs command. |
| 645 | */ |
| 646 | if (!connected) Connect(); |
| 647 | |
| 648 | comm->command = CommCommandCodecs; |
| 649 | comm->length = sizeof(CoreAudioCommCodecs); |
| 650 | |
| 651 | ProcessConnectorCommand(); |
| 652 | |
| 653 | if (comm->status == CommStatusReady) memcpy(&codecs, comm->data, comm->length); |
| 654 | else codecs.codecs[0] = 0; |
| 655 | |
| 656 | initialized = True; |
| 657 | } |
| 658 | |
| 659 | configLayer = new ConfigureCoreAudio(codecs); |
| 660 | } |
| 661 | |
| 662 | return configLayer; |
| 663 | } |
| 664 | |
| 665 | Bool BoCA::EncoderCoreAudioConnect::Connect() |
| 666 | { |
| 667 | static multithread (intptr_t) count = 0; |
| 668 | |
| 669 | if (connected) return False; |
| 670 | |
| 671 | /* Try 32 and 64 bit connector. |
| 672 | */ |
| 673 | Array<String> files; |
| 674 | |
| 675 | #ifdef __WIN32__ |
| 676 | files.Add(GUI::Application::GetApplicationDirectory().Append("boca\\boca_encoder_coreaudioconnect.1.0.exe")); |
| 677 | files.Add(GUI::Application::GetApplicationDirectory().Append("boca\\boca_encoder_coreaudioconnect64.1.0.exe")); |
| 678 | #else |
| 679 | files.Add(Utilities::GetBoCADirectory().Append("/boca_encoder_coreaudioconnect.1.0")); |
| 680 | files.Add(Utilities::GetBoCADirectory().Append("/boca_encoder_coreaudioconnect64.1.0")); |
| 681 | #endif |
| 682 | |
| 683 | foreachreverse (const String &file, files) if (!File(file).Exists()) files.RemoveNth(foreachindex); |
| 684 | |
| 685 | foreach (const String &file, files) |
| 686 | { |
| 687 | /* Disconnect any previously established connections. |
| 688 | */ |
| 689 | Disconnect(); |
| 690 | |
| 691 | /* Create shared memory object and map view to communication buffer. |
| 692 | */ |
| 693 | #ifdef __WIN32__ |
| 694 | mappingName = BoCA::GetApplicationPrefix().Append(":").Append(Number((Int64) GetCurrentProcessId()).ToHexString()).Append("-").Append(Number((Int64) GetCurrentThreadId()).ToHexString()).Append("-").Append(Number((Int64) count++).ToHexString()); |
| 695 | |
| 696 | semaphore = CreateSemaphoreA(NIL, 0, 1, String(mappingName).Append("-sem")); |
| 697 | mapping = CreateFileMappingA(INVALID_HANDLE_VALUE, NIL, PAGE_READWRITE, 0, sizeof(CoreAudioCommBuffer), mappingName); |
| 698 | comm = (CoreAudioCommBuffer *) MapViewOfFile(mapping, FILE_MAP_ALL_ACCESS, 0, 0, 0); |
| 699 | #else |
| 700 | mappingName = String("/").Append(BoCA::GetApplicationPrefix()).Append(":").Append(Number((Int64) getpid()).ToHexString()).Append("-").Append(Number((Int64) pthread_self()).ToHexString()).Append("-").Append(Number((Int64) count++).ToHexString()); |
| 701 | |
| 702 | key_t key = mappingName.ComputeCRC32(); |
| 703 | |
| 704 | semaphore = semget(key, 1, IPC_CREAT | IPC_EXCL | 0666); |
| 705 | mapping = shm_open(mappingName, O_CREAT | O_EXCL | O_RDWR, 0666); |
| 706 | |
| 707 | semctl(semaphore, 0, SETVAL, 0); |
| 708 | ftruncate(mapping, sizeof(CoreAudioCommBuffer)); |
| 709 | |
| 710 | comm = (CoreAudioCommBuffer *) mmap(NULL, sizeof(CoreAudioCommBuffer), PROT_READ | PROT_WRITE, MAP_SHARED, mapping, 0); |
| 711 | #endif |
| 712 | |
| 713 | /* Start connector process. |
| 714 | */ |
| 715 | #ifdef __WIN32__ |
| 716 | SHELLEXECUTEINFOA execInfo; |
| 717 | |
| 718 | ZeroMemory(&execInfo, sizeof(execInfo)); |
| 719 | |
| 720 | execInfo.cbSize = sizeof(execInfo); |
| 721 | execInfo.fMask = SEE_MASK_NOCLOSEPROCESS; |
| 722 | execInfo.lpVerb = "open"; |
| 723 | execInfo.lpDirectory = GUI::Application::GetApplicationDirectory(); |
| 724 | execInfo.nShow = SW_HIDE; |
| 725 | execInfo.lpFile = file; |
| 726 | execInfo.lpParameters = mappingName; |
| 727 | |
| 728 | ShellExecuteExA(&execInfo); |
| 729 | |
| 730 | connector = execInfo.hProcess; |
| 731 | #else |
| 732 | const char *cmd = String("wine ").Append(file).Append(" ").Append(mappingName).Append(" ").Append(String::FromInt(key)).Append(" 2> /dev/null"); |
| 733 | |
| 734 | connector = fork(); |
| 735 | |
| 736 | if (!connector) { execl("/bin/sh", "sh", "-c", cmd, NULL); exit(0); } |
| 737 | #endif |
| 738 | |
| 739 | connected = True; |
| 740 | |
| 741 | /* Send Hello command. |
| 742 | */ |
| 743 | comm->command = CommCommandHello; |
| 744 | comm->length = sizeof(CoreAudioCommHello); |
| 745 | |
| 746 | ((CoreAudioCommHello *) &comm->data)->version = 1; |
| 747 | |
| 748 | ProcessConnectorCommand(); |
| 749 | |
| 750 | if (comm->status == CommStatusReady) ready = True; |
| 751 | else ready = False; |
| 752 | |
| 753 | if (ready) break; |
| 754 | } |
| 755 | |
| 756 | return True; |
| 757 | } |
| 758 | |
| 759 | Bool BoCA::EncoderCoreAudioConnect::Disconnect() |
| 760 | { |
| 761 | if (!connected) return False; |
| 762 | |
| 763 | /* Send Quit command. |
| 764 | */ |
| 765 | comm->command = CommCommandQuit; |
| 766 | comm->length = 0; |
| 767 | |
| 768 | ProcessConnectorCommand(); |
| 769 | |
| 770 | /* Wait until the connector exits. |
| 771 | */ |
| 772 | #ifdef __WIN32__ |
| 773 | while (WaitForSingleObject(connector, 0) == WAIT_TIMEOUT) S::System::System::Sleep(1); |
| 774 | #else |
| 775 | int status = 0; |
| 776 | |
| 777 | waitpid(connector, &status, 0); |
| 778 | #endif |
| 779 | |
| 780 | /* Unmap view and close shared memory object. |
| 781 | */ |
| 782 | #ifdef __WIN32__ |
| 783 | UnmapViewOfFile(comm); |
| 784 | CloseHandle(mapping); |
| 785 | CloseHandle(semaphore); |
| 786 | #else |
| 787 | munmap(comm, sizeof(CoreAudioCommBuffer)); |
| 788 | close(mapping); |
| 789 | |
| 790 | shm_unlink(mappingName); |
| 791 | semctl(semaphore, 0, IPC_RMID, 0); |
| 792 | #endif |
| 793 | |
| 794 | connected = False; |
| 795 | |
| 796 | return True; |
| 797 | } |
| 798 | |
| 799 | Bool BoCA::EncoderCoreAudioConnect::ProcessConnectorCommand() |
| 800 | { |
| 801 | if (!connected) return False; |
| 802 | |
| 803 | #ifndef __WIN32__ |
| 804 | static sembuf opWait[1] = { 0, -1, SEM_UNDO }; |
| 805 | static sembuf opPost[1] = { 0, 1, SEM_UNDO }; |
| 806 | #endif |
| 807 | |
| 808 | comm->status = CommStatusIssued; |
| 809 | |
| 810 | while (True) |
| 811 | { |
| 812 | #ifdef __WIN32__ |
| 813 | ReleaseSemaphore(semaphore, 1, NULL); |
| 814 | |
| 815 | while (WaitForSingleObject(semaphore, 1000) != WAIT_OBJECT_0) |
| 816 | { |
| 817 | /* Check if the connector still exists. |
| 818 | */ |
| 819 | if (WaitForSingleObject(connector, 0) != WAIT_TIMEOUT) return False; |
| 820 | } |
| 821 | #else |
| 822 | semop(semaphore, opPost, 1); |
| 823 | |
| 824 | if (semop(semaphore, opWait, 1) != 0) return False; |
| 825 | |
| 826 | /* Check if the connector still exists. |
| 827 | */ |
| 828 | int status = 0; |
| 829 | |
| 830 | if (waitpid(connector, &status, WNOHANG) != 0) return False; |
| 831 | #endif |
| 832 | |
| 833 | if (comm->status != CommStatusIssued) break; |
| 834 | } |
| 835 | |
| 836 | return True; |
| 837 | } |