| 1 | /* BoCA - BonkEnc Component Architecture |
| 2 | * Copyright (C) 2007-2024 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 | |
| 15 | #include "worker.h" |
| 16 | #include "config.h" |
| 17 | |
| 18 | namespace BoCA |
| 19 | { |
| 20 | CA::OSStatus AudioConverterComplexInputDataProc(CA::AudioConverterRef, CA::UInt32 *, CA::AudioBufferList *, CA::AudioStreamPacketDescription **, void *); |
| 21 | }; |
| 22 | |
| 23 | BoCA::SuperWorker::SuperWorker(const Config *config, const Format &iFormat) : processSignal(1), readySignal(1) |
| 24 | { |
| 25 | static Endianness endianness = CPU().GetEndianness(); |
| 26 | |
| 27 | processSignal.Wait(); |
| 28 | |
| 29 | flush = False; |
| 30 | quit = False; |
| 31 | |
| 32 | format = iFormat; |
| 33 | |
| 34 | threadMain.Connect(&SuperWorker::Run, this); |
| 35 | |
| 36 | /* Get configuration. |
| 37 | */ |
| 38 | CA::UInt32 codec = config->GetIntValue(ConfigureCoreAudio::ConfigID, "Codec", CA::kAudioFormatMPEG4AAC); |
| 39 | Int kbps = config->GetIntValue(ConfigureCoreAudio::ConfigID, "Bitrate", 64); |
| 40 | |
| 41 | /* Fall back to HE/ELD-SBR if HEv2/ELDv2 is selected for non-stereo input. |
| 42 | */ |
| 43 | if (codec == CA::kAudioFormatMPEG4AAC_HE_V2 && format.channels != 2) codec = CA::kAudioFormatMPEG4AAC_HE; |
| 44 | if (codec == CA::kOptionalAudioFormatMPEG4AAC_ELD_V2 && format.channels != 2) codec = CA::kOptionalAudioFormatMPEG4AAC_ELD_SBR; |
| 45 | |
| 46 | /* Fill out source format description. |
| 47 | */ |
| 48 | CA::AudioStreamBasicDescription sourceFormat = { 0 }; |
| 49 | |
| 50 | sourceFormat.mFormatID = CA::kAudioFormatLinearPCM; |
| 51 | sourceFormat.mFormatFlags = CA::kLinearPCMFormatFlagIsPacked; |
| 52 | sourceFormat.mFormatFlags |= format.fp ? CA::kLinearPCMFormatFlagIsFloat : 0; |
| 53 | sourceFormat.mFormatFlags |= format.sign && !format.fp ? CA::kLinearPCMFormatFlagIsSignedInteger : 0; |
| 54 | sourceFormat.mFormatFlags |= endianness == EndianBig ? CA::kLinearPCMFormatFlagIsBigEndian : 0; |
| 55 | sourceFormat.mSampleRate = format.rate; |
| 56 | sourceFormat.mChannelsPerFrame = format.channels; |
| 57 | sourceFormat.mBitsPerChannel = format.bits; |
| 58 | sourceFormat.mFramesPerPacket = 1; |
| 59 | sourceFormat.mBytesPerFrame = sourceFormat.mChannelsPerFrame * sourceFormat.mBitsPerChannel / 8; |
| 60 | sourceFormat.mBytesPerPacket = sourceFormat.mFramesPerPacket * sourceFormat.mBytesPerFrame; |
| 61 | |
| 62 | /* Fill out destination format description. |
| 63 | */ |
| 64 | CA::AudioStreamBasicDescription destinationFormat = { 0 }; |
| 65 | |
| 66 | destinationFormat.mFormatID = codec; |
| 67 | destinationFormat.mSampleRate = GetOutputSampleRate(destinationFormat.mFormatID, format.rate); |
| 68 | destinationFormat.mChannelsPerFrame = format.channels; |
| 69 | |
| 70 | CA::UInt32 formatSize = sizeof(destinationFormat); |
| 71 | |
| 72 | CA::AudioFormatGetProperty(CA::kAudioFormatProperty_FormatInfo, 0, NIL, &formatSize, &destinationFormat); |
| 73 | |
| 74 | /* Create audio converter object. |
| 75 | */ |
| 76 | CA::AudioConverterNew(&sourceFormat, &destinationFormat, &converter); |
| 77 | |
| 78 | frameSize = destinationFormat.mFramesPerPacket; |
| 79 | sampleRate = destinationFormat.mSampleRate; |
| 80 | |
| 81 | /* Set bitrate if format does support bitrates. |
| 82 | */ |
| 83 | CA::UInt32 size = 0; |
| 84 | |
| 85 | if (CA::AudioConverterGetPropertyInfo(converter, CA::kAudioConverterApplicableEncodeBitRates, &size, NIL) == 0) |
| 86 | { |
| 87 | /* Get applicable bitrate values. |
| 88 | */ |
| 89 | CA::UInt32 bitrate = kbps * 1000 * format.channels; |
| 90 | CA::AudioValueRange *bitrateValues = new CA::AudioValueRange [size / sizeof(CA::AudioValueRange)]; |
| 91 | |
| 92 | CA::AudioConverterGetProperty(converter, CA::kAudioConverterApplicableEncodeBitRates, &size, bitrateValues); |
| 93 | |
| 94 | /* Find best supported bitrate. |
| 95 | */ |
| 96 | CA::Float64 nearest = 0xFFFFFFFF; |
| 97 | |
| 98 | for (UnsignedInt i = 0; i < size / sizeof(CA::AudioValueRange); i++) |
| 99 | { |
| 100 | if (bitrate >= bitrateValues[i].mMinimum && bitrate <= bitrateValues[i].mMaximum) nearest = bitrate; |
| 101 | |
| 102 | if (Math::Abs(bitrate - bitrateValues[i].mMinimum) < Math::Abs(bitrate - nearest)) nearest = bitrateValues[i].mMinimum; |
| 103 | if (Math::Abs(bitrate - bitrateValues[i].mMaximum) < Math::Abs(bitrate - nearest)) nearest = bitrateValues[i].mMaximum; |
| 104 | } |
| 105 | |
| 106 | bitrate = nearest; |
| 107 | |
| 108 | delete [] bitrateValues; |
| 109 | |
| 110 | /* Set bitrate on converter. |
| 111 | */ |
| 112 | CA::AudioConverterSetProperty(converter, CA::kAudioConverterEncodeBitRate, sizeof(CA::UInt32), &bitrate); |
| 113 | } |
| 114 | |
| 115 | /* Get maximum output packet size. |
| 116 | */ |
| 117 | CA::UInt32 valueSize = 4; |
| 118 | |
| 119 | CA::AudioConverterGetProperty(converter, CA::kAudioConverterPropertyMaximumOutputPacketSize, &valueSize, &bufferSize); |
| 120 | |
| 121 | /* Set up buffer for Core Audio. |
| 122 | */ |
| 123 | buffers = (CA::AudioBufferList *) new unsigned char [sizeof(CA::AudioBufferList) + sizeof(CA::AudioBuffer)]; |
| 124 | |
| 125 | buffers->mNumberBuffers = 1; |
| 126 | |
| 127 | buffers->mBuffers[0].mData = new unsigned char [bufferSize]; |
| 128 | buffers->mBuffers[0].mDataByteSize = bufferSize; |
| 129 | buffers->mBuffers[0].mNumberChannels = format.channels; |
| 130 | |
| 131 | bytesConsumed = 0; |
| 132 | } |
| 133 | |
| 134 | BoCA::SuperWorker::~SuperWorker() |
| 135 | { |
| 136 | /* Free buffer. |
| 137 | */ |
| 138 | delete [] (unsigned char *) buffers->mBuffers[0].mData; |
| 139 | delete [] (unsigned char *) buffers; |
| 140 | |
| 141 | /* Close converter. |
| 142 | */ |
| 143 | CA::AudioConverterDispose(converter); |
| 144 | } |
| 145 | |
| 146 | Int BoCA::SuperWorker::Run() |
| 147 | { |
| 148 | while (!Threads::Access::Value(quit)) |
| 149 | { |
| 150 | processSignal.Wait(); |
| 151 | |
| 152 | if (Threads::Access::Value(quit)) break; |
| 153 | |
| 154 | packetBuffer.Resize(0); |
| 155 | packetSizes.RemoveAll(); |
| 156 | |
| 157 | foreach (CA::AudioStreamPacketDescription *packet, packetInfos) delete packet; |
| 158 | |
| 159 | packetInfos.RemoveAll(); |
| 160 | |
| 161 | Int bytesPerFrame = Math::Ceil(frameSize * format.channels * (format.bits / 8) * (Float(format.rate) / sampleRate)); |
| 162 | |
| 163 | CA::UInt32 packets = 1; |
| 164 | CA::AudioStreamPacketDescription packet; |
| 165 | |
| 166 | buffers->mBuffers[0].mDataByteSize = bufferSize; |
| 167 | |
| 168 | while ((flush || samplesBuffer.Size() - bytesConsumed >= bytesPerFrame) && CA::AudioConverterFillComplexBuffer(converter, &AudioConverterComplexInputDataProc, this, &packets, buffers, &packet) == 0) |
| 169 | { |
| 170 | if (buffers->mBuffers[0].mDataByteSize == 0) break; |
| 171 | |
| 172 | packetBuffer.Resize(packetBuffer.Size() + buffers->mBuffers[0].mDataByteSize); |
| 173 | |
| 174 | memcpy(packetBuffer + packetBuffer.Size() - buffers->mBuffers[0].mDataByteSize, buffers->mBuffers[0].mData, buffers->mBuffers[0].mDataByteSize); |
| 175 | |
| 176 | packetSizes.Add(buffers->mBuffers[0].mDataByteSize); |
| 177 | packetInfos.Add(new CA::AudioStreamPacketDescription(packet)); |
| 178 | |
| 179 | buffers->mBuffers[0].mDataByteSize = bufferSize; |
| 180 | } |
| 181 | |
| 182 | readySignal.Release(); |
| 183 | } |
| 184 | |
| 185 | return Success(); |
| 186 | } |
| 187 | |
| 188 | Void BoCA::SuperWorker::Encode(const Buffer<unsigned char> &buffer, Int offset, Int size, Bool last) |
| 189 | { |
| 190 | samplesBuffer.Resize(samplesBuffer.Size() + size); |
| 191 | |
| 192 | memmove(samplesBuffer, samplesBuffer + bytesConsumed, samplesBuffer.Size() - bytesConsumed - size); |
| 193 | memcpy(samplesBuffer + samplesBuffer.Size() - bytesConsumed - size, buffer + offset, size); |
| 194 | |
| 195 | samplesBuffer.Resize(samplesBuffer.Size() - bytesConsumed); |
| 196 | |
| 197 | bytesConsumed = 0; |
| 198 | flush = last; |
| 199 | |
| 200 | processSignal.Release(); |
| 201 | } |
| 202 | |
| 203 | Void BoCA::SuperWorker::WaitUntilReady() |
| 204 | { |
| 205 | readySignal.Wait(); |
| 206 | } |
| 207 | |
| 208 | Int BoCA::SuperWorker::Quit() |
| 209 | { |
| 210 | Threads::Access::Set(quit, True); |
| 211 | |
| 212 | processSignal.Release(); |
| 213 | |
| 214 | return Success(); |
| 215 | } |
| 216 | |
| 217 | CA::AudioConverterPrimeInfo BoCA::SuperWorker::GetPrimeInfo() const |
| 218 | { |
| 219 | CA::AudioConverterPrimeInfo primeInfo; |
| 220 | CA::UInt32 size = sizeof(primeInfo); |
| 221 | |
| 222 | if (CA::AudioConverterGetProperty(converter, CA::kAudioConverterPrimeInfo, &size, &primeInfo) != 0) |
| 223 | { |
| 224 | primeInfo.leadingFrames = 0xFFFFFFFF; |
| 225 | primeInfo.trailingFrames = 0xFFFFFFFF; |
| 226 | } |
| 227 | |
| 228 | return primeInfo; |
| 229 | } |
| 230 | |
| 231 | unsigned char *BoCA::SuperWorker::GetMagicCookie(CA::UInt32 *cookieSize) const |
| 232 | { |
| 233 | if (CA::AudioConverterGetPropertyInfo(converter, CA::kAudioConverterCompressionMagicCookie, cookieSize, NIL) == 0) |
| 234 | { |
| 235 | unsigned char *cookie = new unsigned char [*cookieSize]; |
| 236 | |
| 237 | CA::AudioConverterGetProperty(converter, CA::kAudioConverterCompressionMagicCookie, cookieSize, cookie); |
| 238 | |
| 239 | return cookie; |
| 240 | } |
| 241 | |
| 242 | return NIL; |
| 243 | } |
| 244 | |
| 245 | Int BoCA::SuperWorker::GetOutputSampleRate(CA::UInt32 format, Int inputRate) |
| 246 | { |
| 247 | /* Get supported sample rate ranges for selected codec. |
| 248 | */ |
| 249 | CA::UInt32 size = 0; |
| 250 | |
| 251 | CA::AudioFormatGetPropertyInfo(CA::kAudioFormatProperty_AvailableEncodeSampleRates, sizeof(format), &format, &size); |
| 252 | |
| 253 | if (size == 0) return inputRate; |
| 254 | |
| 255 | CA::AudioValueRange *sampleRates = new CA::AudioValueRange [size / sizeof(CA::AudioValueRange)]; |
| 256 | |
| 257 | CA::AudioFormatGetProperty(CA::kAudioFormatProperty_AvailableEncodeSampleRates, sizeof(format), &format, &size, sampleRates); |
| 258 | |
| 259 | /* Find best fit output sample rate. |
| 260 | */ |
| 261 | Int outputRate = 0; |
| 262 | |
| 263 | for (UnsignedInt i = 0; i < size / sizeof(CA::AudioValueRange); i++) |
| 264 | { |
| 265 | /* Check if encoder supports arbitrary sample rate. |
| 266 | */ |
| 267 | if (sampleRates[i].mMinimum == 0 && |
| 268 | sampleRates[i].mMaximum == 0) { outputRate = inputRate; break; } |
| 269 | |
| 270 | /* Check if input rate falls into current sample rate range. |
| 271 | */ |
| 272 | if (inputRate >= sampleRates[i].mMinimum && |
| 273 | inputRate <= sampleRates[i].mMaximum) { outputRate = inputRate; break; } |
| 274 | |
| 275 | /* Check if current sample rate range fits better than previous best. |
| 276 | */ |
| 277 | if (Math::Abs(inputRate - sampleRates[i].mMinimum) < Math::Abs(inputRate - outputRate)) outputRate = sampleRates[i].mMinimum; |
| 278 | if (Math::Abs(inputRate - sampleRates[i].mMaximum) < Math::Abs(inputRate - outputRate)) outputRate = sampleRates[i].mMaximum; |
| 279 | } |
| 280 | |
| 281 | delete [] sampleRates; |
| 282 | |
| 283 | return outputRate; |
| 284 | } |
| 285 | |
| 286 | CA::OSStatus BoCA::AudioConverterComplexInputDataProc(CA::AudioConverterRef inAudioConverter, CA::UInt32 *ioNumberDataPackets, CA::AudioBufferList *ioData, CA::AudioStreamPacketDescription **outDataPacketDescription, void *inUserData) |
| 287 | { |
| 288 | SuperWorker *worker = (SuperWorker *) inUserData; |
| 289 | const Format &format = worker->format; |
| 290 | |
| 291 | worker->suppliedData.Resize(Math::Min(worker->samplesBuffer.Size() - worker->bytesConsumed, *ioNumberDataPackets * format.channels * (format.bits / 8))); |
| 292 | |
| 293 | memcpy(worker->suppliedData, worker->samplesBuffer + worker->bytesConsumed, worker->suppliedData.Size()); |
| 294 | |
| 295 | *ioNumberDataPackets = worker->suppliedData.Size() / format.channels / (format.bits / 8); |
| 296 | |
| 297 | ioData->mBuffers[0].mData = worker->suppliedData; |
| 298 | ioData->mBuffers[0].mDataByteSize = worker->suppliedData.Size(); |
| 299 | ioData->mBuffers[0].mNumberChannels = format.channels; |
| 300 | |
| 301 | worker->bytesConsumed += ioData->mBuffers[0].mDataByteSize; |
| 302 | |
| 303 | return 0; |
| 304 | } |