Debian Codegraph @

components/encoder/coreaudioconnect/connector/main.cpp

raw symbols SCIP
1 /* BoCA - BonkEnc Component Architecture
2 * Copyright (C) 2007-2021 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 #define _FILE_OFFSET_BITS 64
14
15 #include "dllinterface.h"
16 #include "communication.h"
17
18 #include <stdio.h>
19 #include <math.h>
20
21 #ifdef __WINE__
22 # include <sys/mman.h>
23 # include <sys/sem.h>
24 # include <unistd.h>
25 # include <fcntl.h>
26 #else
27 # include <io.h>
28
29 # if !defined __MINGW32__
30 # define fseeko _fseeki64
31 # define ftello _ftelli64
32 # endif
33
34 # define ftruncate chsize
35 #endif
36
37 #ifndef min
38 # define min(n, m) ((n) < (m) ? (n) : (m))
39 #endif
40
41 static CoreAudioCommSetup setup = { 0 };
42
43 static unsigned int dataOffset = 0;
44
45 static unsigned char *buffer = NULL;
46 static unsigned int bufferSize = 0;
47 static unsigned int bytesConsumed = 0;
48
49 static CA::SInt64 totalSamples = 0;
50
51 void QueryCoreAudioCodecs(CoreAudioCommCodecs *comm)
52 {
53 ZeroMemory(comm, sizeof(CoreAudioCommCodecs));
54
55 /* Get supported codecs.
56 */
57 CA::UInt32 size = 0;
58
59 CA::AudioFormatGetPropertyInfo(CA::kAudioFormatProperty_EncodeFormatIDs, 0, NULL, &size);
60
61 CA::UInt32 *formats = (CA::UInt32 *) malloc(size);
62
63 CA::AudioFormatGetProperty(CA::kAudioFormatProperty_EncodeFormatIDs, 0, NULL, &size, formats);
64
65 for (CA::UInt32 i = 0; i < size / sizeof(CA::UInt32) && i < 32; i++)
66 {
67 comm->codecs[i] = formats[i];
68
69 /* Get bitrate ranges for each codec.
70 */
71 CA::UInt32 brSize = 0;
72
73 CA::AudioFormatGetPropertyInfo(CA::kAudioFormatProperty_AvailableEncodeBitRates, sizeof(CA::UInt32), &formats[i], &brSize);
74
75 CA::AudioValueRange *bitrateValues = (CA::AudioValueRange *) malloc(brSize);
76
77 CA::AudioFormatGetProperty(CA::kAudioFormatProperty_AvailableEncodeBitRates, sizeof(CA::UInt32), &formats[i], &brSize, bitrateValues);
78
79 for (CA::UInt32 j = 0; j < brSize / sizeof(CA::AudioValueRange) && j < 64; j++)
80 {
81 if (bitrateValues[j].mMinimum / 1000 > 192 && bitrateValues[j].mMaximum / 1000 > 192) continue;
82 if ( bitrateValues[j].mMaximum / 1000 > 192) bitrateValues[j].mMaximum = 192 * 1000;
83
84 comm->bitrates[i][j * 2 ] = bitrateValues[j].mMinimum;
85 comm->bitrates[i][j * 2 + 1] = bitrateValues[j].mMaximum;
86 }
87
88 free(bitrateValues);
89 }
90
91 free(formats);
92 }
93
94 int GetOutputSampleRate(const CoreAudioCommSetup &setup)
95 {
96 /* Get supported sample rate ranges for selected codec.
97 */
98 CA::UInt32 format = setup.codec;
99 CA::UInt32 size = 0;
100
101 CA::AudioFormatGetPropertyInfo(CA::kAudioFormatProperty_AvailableEncodeSampleRates, sizeof(format), &format, &size);
102
103 if (size == 0) return setup.rate;
104
105 CA::AudioValueRange *sampleRates = (CA::AudioValueRange *) malloc(size);
106
107 CA::AudioFormatGetProperty(CA::kAudioFormatProperty_AvailableEncodeSampleRates, sizeof(format), &format, &size, sampleRates);
108
109 /* Find best fit output sample rate.
110 */
111 int outputRate = 0;
112
113 for (CA::UInt32 i = 0; i < size / sizeof(CA::AudioValueRange); i++)
114 {
115 /* Check if encoder supports arbitrary sample rate.
116 */
117 if (sampleRates[i].mMinimum == 0 &&
118 sampleRates[i].mMaximum == 0) { outputRate = setup.rate; break; }
119
120 /* Check if input rate falls into current sample rate range.
121 */
122 if (setup.rate >= sampleRates[i].mMinimum &&
123 setup.rate <= sampleRates[i].mMaximum) { outputRate = setup.rate; break; }
124
125 /* Check if current sample rate range fits better than previous best.
126 */
127 if (abs(setup.rate - (int) sampleRates[i].mMinimum) < abs(setup.rate - outputRate)) outputRate = sampleRates[i].mMinimum;
128 if (abs(setup.rate - (int) sampleRates[i].mMaximum) < abs(setup.rate - outputRate)) outputRate = sampleRates[i].mMaximum;
129 }
130
131 free(sampleRates);
132
133 return outputRate;
134 }
135
136 CA::OSStatus AudioFileReadProc(void *inClientData, CA::SInt64 inPosition, CA::UInt32 requestCount, void *buffer, CA::UInt32 *actualCount)
137 {
138 FILE *file = (FILE *) inClientData;
139
140 fseeko(file, inPosition + dataOffset, SEEK_SET);
141
142 *actualCount = fread(buffer, 1, requestCount, file);
143
144 return 0;
145 }
146
147 CA::OSStatus AudioFileWriteProc(void *inClientData, CA::SInt64 inPosition, CA::UInt32 requestCount, const void *buffer, CA::UInt32 *actualCount)
148 {
149 FILE *file = (FILE *) inClientData;
150
151 fseeko(file, inPosition + dataOffset, SEEK_SET);
152
153 *actualCount = fwrite(buffer, 1, requestCount, file);
154
155 return 0;
156 }
157
158 CA::SInt64 AudioFileGetSizeProc(void *inClientData)
159 {
160 FILE *file = (FILE *) inClientData;
161
162 int64_t pos = ftello(file);
163
164 fseeko(file, 0, SEEK_END);
165
166 int64_t size = ftello(file);
167
168 fseeko(file, pos, SEEK_SET);
169
170 return size - dataOffset;
171 }
172
173 CA::OSStatus AudioFileSetSizeProc(void *inClientData, CA::SInt64 inSize)
174 {
175 FILE *file = (FILE *) inClientData;
176
177 fflush(file);
178 ftruncate(fileno(file), inSize + dataOffset);
179
180 return 0;
181 }
182
183 CA::OSStatus AudioConverterComplexInputDataProc(CA::AudioConverterRef inAudioConverter, CA::UInt32 *ioNumberDataPackets, CA::AudioBufferList *ioData, CA::AudioStreamPacketDescription **outDataPacketDescription, void *inUserData)
184 {
185 static unsigned char *suppliedData = NULL;
186 static unsigned int suppliedDataSize = 0;
187
188 suppliedDataSize = min(bufferSize - bytesConsumed, (unsigned int) *ioNumberDataPackets * setup.channels * (setup.bits / 8));
189 suppliedData = (unsigned char *) realloc(suppliedData, suppliedDataSize);
190
191 memcpy(suppliedData, buffer + bytesConsumed, suppliedDataSize);
192
193 *ioNumberDataPackets = suppliedDataSize / setup.channels / (setup.bits / 8);
194
195 ioData->mBuffers[0].mData = suppliedData;
196 ioData->mBuffers[0].mDataByteSize = suppliedDataSize;
197 ioData->mBuffers[0].mNumberChannels = setup.channels;
198
199 totalSamples += *ioNumberDataPackets;
200 bytesConsumed += ioData->mBuffers[0].mDataByteSize;
201
202 return 0;
203 }
204
205 int main(int argc, char *argv[])
206 {
207 /* Get application prefix from mapping name.
208 */
209 char applicationPrefix[128] = { 0 };
210
211 #ifndef __WINE__
212 strcpy(applicationPrefix, argv[1]);
213 strchr(applicationPrefix, ':')[0] = 0;
214 #else
215 strcpy(applicationPrefix, argv[1] + 1);
216 strchr(applicationPrefix, ':')[0] = 0;
217 #endif
218
219 /* Open shared memory object and map view to communication buffer.
220 */
221 #ifndef __WINE__
222 char semaphoreName[128] = { 0 };
223
224 strcpy(semaphoreName, argv[1]);
225 strcat(semaphoreName, "-sem");
226
227 HANDLE semaphore = OpenSemaphoreA(SEMAPHORE_ALL_ACCESS, false, semaphoreName);
228 HANDLE mapping = OpenFileMappingA(FILE_MAP_ALL_ACCESS, false, argv[1]);
229
230 if (semaphore == NULL || mapping == NULL) return 1;
231
232 CoreAudioCommBuffer *comm = (CoreAudioCommBuffer *) MapViewOfFile(mapping, FILE_MAP_ALL_ACCESS, 0, 0, 0);
233 #else
234 sembuf opWait[1] = { 0, -1, SEM_UNDO };
235 sembuf opPost[1] = { 0, 1, SEM_UNDO };
236
237 int semaphore = semget(atoi(argv[2]), 1, IPC_PRIVATE);
238 int mapping = shm_open(argv[1], O_RDWR, 0666);
239
240 if (semaphore == -1 || mapping == -1) return 1;
241
242 CoreAudioCommBuffer *comm = (CoreAudioCommBuffer *) mmap(NULL, sizeof(CoreAudioCommBuffer), PROT_READ | PROT_WRITE, MAP_SHARED, mapping, 0);
243 #endif
244
245 /* Load Core Audio DLLs.
246 */
247 LoadCoreAudioDLL(applicationPrefix);
248
249 /* Main processing loop.
250 */
251 FILE *file = NULL;
252
253 CA::AudioFileID audioFile = NULL;
254 CA::AudioConverterRef converter = NULL;
255 CA::AudioBufferList *buffers = NULL;
256
257 int frameSize = 0;
258 int64_t duration = 0;
259
260 CA::UInt32 dataSize = 0;
261 CA::UInt32 packetsWritten = 0;
262
263 while (true)
264 {
265 #ifndef __WINE__
266 WaitForSingleObject(semaphore, INFINITE);
267 #else
268 semop(semaphore, opWait, 1);
269 #endif
270
271 if (comm->status != CommStatusIssued)
272 {
273 #ifndef __WINE__
274 ReleaseSemaphore(semaphore, 1, NULL);
275 #else
276 semop(semaphore, opPost, 1);
277 #endif
278
279 continue;
280 }
281
282 switch (comm->command)
283 {
284 case CommCommandHello:
285 if (((CoreAudioCommHello *) &comm->data)->version == 1 && coreaudiodll != NULL)
286 {
287 /* Check whether any codecs are available.
288 */
289 CoreAudioCommCodecs codecs;
290
291 memset(&codecs, 0, sizeof(CoreAudioCommCodecs));
292
293 QueryCoreAudioCodecs(&codecs);
294
295 if (codecs.codecs[0] != 0) comm->status = CommStatusReady;
296 }
297
298 if (comm->status != CommStatusReady) comm->status = CommStatusError;
299
300 break;
301 case CommCommandCodecs:
302 QueryCoreAudioCodecs((CoreAudioCommCodecs *) &comm->data);
303
304 comm->length = sizeof(CoreAudioCommCodecs);
305 comm->status = CommStatusReady;
306
307 break;
308 case CommCommandSetup:
309 memcpy(&setup, comm->data, sizeof(CoreAudioCommSetup));
310
311 /* Setup encoder for first packet.
312 */
313 {
314 /* Fill out source format description.
315 */
316 CA::AudioStreamBasicDescription sourceFormat = { 0 };
317
318 sourceFormat.mFormatID = CA::kAudioFormatLinearPCM;
319 sourceFormat.mFormatFlags = CA::kLinearPCMFormatFlagIsPacked;
320 sourceFormat.mFormatFlags |= setup.fp ? CA::kLinearPCMFormatFlagIsFloat : 0;
321 sourceFormat.mFormatFlags |= setup.sign && !setup.fp ? CA::kLinearPCMFormatFlagIsSignedInteger : 0;
322 sourceFormat.mSampleRate = setup.rate;
323 sourceFormat.mChannelsPerFrame = setup.channels;
324 sourceFormat.mBitsPerChannel = setup.bits;
325 sourceFormat.mFramesPerPacket = 1;
326 sourceFormat.mBytesPerFrame = sourceFormat.mChannelsPerFrame * sourceFormat.mBitsPerChannel / 8;
327 sourceFormat.mBytesPerPacket = sourceFormat.mFramesPerPacket * sourceFormat.mBytesPerFrame;
328
329 /* Fill out destination format description.
330 */
331 CA::AudioStreamBasicDescription destinationFormat = { 0 };
332
333 destinationFormat.mFormatID = setup.codec;
334 destinationFormat.mSampleRate = GetOutputSampleRate(setup);
335 destinationFormat.mChannelsPerFrame = setup.channels;
336
337 CA::UInt32 formatSize = sizeof(destinationFormat);
338
339 CA::AudioFormatGetProperty(CA::kAudioFormatProperty_FormatInfo, 0, NULL, &formatSize, &destinationFormat);
340
341 /* Create audio converter object.
342 */
343 if (CA::AudioConverterNew(&sourceFormat, &destinationFormat, &converter) != 0) { comm->status = CommStatusError; break; }
344
345 frameSize = destinationFormat.mFramesPerPacket;
346
347 /* Set bitrate if format does support bitrates.
348 */
349 CA::UInt32 size = 0;
350
351 if (CA::AudioConverterGetPropertyInfo(converter, CA::kAudioConverterApplicableEncodeBitRates, &size, NULL) == 0)
352 {
353 /* Get applicable bitrate values.
354 */
355 CA::UInt32 bitrate = setup.bitrate;
356 CA::AudioValueRange *bitrateValues = (CA::AudioValueRange *) malloc(size);
357
358 CA::AudioConverterGetProperty(converter, CA::kAudioConverterApplicableEncodeBitRates, &size, bitrateValues);
359
360 /* Find best supported bitrate.
361 */
362 CA::Float64 nearest = 0xFFFFFFFF;
363
364 for (unsigned int i = 0; i < size / sizeof(CA::AudioValueRange); i++)
365 {
366 if (bitrate >= bitrateValues[i].mMinimum && bitrate <= bitrateValues[i].mMaximum) nearest = bitrate;
367
368 if (fabs(bitrate - bitrateValues[i].mMinimum) < fabs(bitrate - nearest)) nearest = bitrateValues[i].mMinimum;
369 if (fabs(bitrate - bitrateValues[i].mMaximum) < fabs(bitrate - nearest)) nearest = bitrateValues[i].mMaximum;
370 }
371
372 bitrate = nearest;
373
374 free(bitrateValues);
375
376 /* Set bitrate on converter.
377 */
378 CA::AudioConverterSetProperty(converter, CA::kAudioConverterEncodeBitRate, sizeof(CA::UInt32), &bitrate);
379 }
380
381 /* Create audio file object for output file.
382 */
383 CA::UInt32 fileType = setup.format ? CA::kAudioFileM4AType : CA::kAudioFileAAC_ADTSType;
384
385 #ifdef __WINE__
386 file = fopen(setup.file, "r+b");
387 #else
388 wchar_t fileName[32768] = L"\\\\?\\";
389
390 MultiByteToWideChar(CP_UTF8, 0, setup.file, -1, fileName + 4, sizeof(fileName) / sizeof(wchar_t) - 4);
391
392 file = _wfopen(fileName, L"r+b");
393 #endif
394
395 fseeko(file, 0, SEEK_END);
396 dataOffset = ftello(file);
397
398 CA::AudioFileInitializeWithCallbacks(file, AudioFileReadProc, AudioFileWriteProc, AudioFileGetSizeProc, AudioFileSetSizeProc, fileType, &destinationFormat, 0, &audioFile);
399
400 /* Get magic cookie and supply it to audio file.
401 */
402 CA::UInt32 cookieSize = 0;
403
404 if (CA::AudioConverterGetPropertyInfo(converter, CA::kAudioConverterCompressionMagicCookie, &cookieSize, NULL) == 0)
405 {
406 unsigned char *cookie = (unsigned char *) malloc(cookieSize);
407
408 CA::AudioConverterGetProperty(converter, CA::kAudioConverterCompressionMagicCookie, &cookieSize, cookie);
409 CA::AudioFileSetProperty(audioFile, CA::kAudioFilePropertyMagicCookieData, cookieSize, cookie);
410
411 free(cookie);
412 }
413
414 /* Get maximum output packet size.
415 */
416 CA::UInt32 valueSize = 4;
417
418 CA::AudioConverterGetProperty(converter, CA::kAudioConverterPropertyMaximumOutputPacketSize, &valueSize, &dataSize);
419
420 /* Set up buffer for Core Audio.
421 */
422 buffers = (CA::AudioBufferList *) malloc(sizeof(CA::AudioBufferList) + sizeof(CA::AudioBuffer));
423
424 buffers->mNumberBuffers = 1;
425
426 buffers->mBuffers[0].mData = (unsigned char *) malloc(dataSize);
427 buffers->mBuffers[0].mDataByteSize = dataSize;
428 buffers->mBuffers[0].mNumberChannels = setup.channels;
429 }
430
431 packetsWritten = 0;
432 totalSamples = 0;
433
434 comm->status = CommStatusReady;
435
436 break;
437 case CommCommandEncode:
438 if (converter == NULL) { comm->status = CommStatusError; break; }
439
440 /* Encode supplied packet.
441 */
442 {
443 /* Configure buffer.
444 */
445 bufferSize += comm->length;
446 buffer = (unsigned char *) realloc(buffer, bufferSize);
447
448 memmove(buffer, buffer + bytesConsumed, bufferSize - bytesConsumed - comm->length);
449 memcpy(buffer + bufferSize - bytesConsumed - comm->length, comm->data, comm->length);
450
451 bufferSize -= bytesConsumed;
452 buffer = (unsigned char *) realloc(buffer, bufferSize);
453
454 bytesConsumed = 0;
455
456 /* Convert frames.
457 */
458 CA::UInt32 packets = 1;
459 CA::AudioStreamPacketDescription packet;
460
461 buffers->mBuffers[0].mDataByteSize = dataSize;
462
463 while (CA::AudioConverterFillComplexBuffer(converter, &AudioConverterComplexInputDataProc, NULL, &packets, buffers, &packet) == 0)
464 {
465 if (buffers->mBuffers[0].mDataByteSize == 0) break;
466
467 CA::AudioFileWritePackets(audioFile, false, buffers->mBuffers[0].mDataByteSize, &packet, packetsWritten, &packets, buffers->mBuffers[0].mData);
468
469 packetsWritten += packets;
470
471 if (bufferSize - bytesConsumed < 65536) break;
472
473 buffers->mBuffers[0].mDataByteSize = dataSize;
474 }
475 }
476
477 comm->status = CommStatusReady;
478
479 break;
480 case CommCommandFinish:
481 if (converter == NULL) { comm->status = CommStatusError; break; }
482
483 /* Finish encoding after last packet.
484 */
485 {
486 /* Convert final frames.
487 */
488 CA::UInt32 packets = 1;
489 CA::AudioStreamPacketDescription packet;
490
491 buffers->mBuffers[0].mDataByteSize = dataSize;
492
493 while (CA::AudioConverterFillComplexBuffer(converter, &AudioConverterComplexInputDataProc, NULL, &packets, buffers, &packet) == 0)
494 {
495 if (buffers->mBuffers[0].mDataByteSize == 0) break;
496
497 CA::AudioFileWritePackets(audioFile, false, buffers->mBuffers[0].mDataByteSize, &packet, packetsWritten, &packets, buffers->mBuffers[0].mData);
498
499 packetsWritten += packets;
500
501 buffers->mBuffers[0].mDataByteSize = dataSize;
502 }
503
504 free(buffers->mBuffers[0].mData);
505 free(buffers);
506
507 /* Calculate frame size divider and duration.
508 */
509 int rate = GetOutputSampleRate(setup);
510
511 if (rate == 0) rate = setup.rate;
512
513 float divider = float(setup.rate) / rate;
514
515 if (setup.codec == CA::kAudioFormatMPEG4AAC_HE ||
516 setup.codec == CA::kAudioFormatMPEG4AAC_HE_V2) divider *= 2.0;
517
518 duration = int64_t(packetsWritten) * frameSize / divider;
519
520 /* Write priming and remainder info.
521 */
522 CA::AudioConverterPrimeInfo primeInfo;
523 CA::UInt32 size = sizeof(primeInfo);
524
525 if (CA::AudioConverterGetProperty(converter, CA::kAudioConverterPrimeInfo, &size, &primeInfo) == 0)
526 {
527 CA::AudioFilePacketTableInfo pti;
528
529 pti.mPrimingFrames = primeInfo.leadingFrames;
530 pti.mRemainderFrames = primeInfo.trailingFrames;
531 pti.mNumberValidFrames = ceil(totalSamples / divider);
532
533 CA::AudioFileSetProperty(audioFile, CA::kAudioFilePropertyPacketTableInfo, sizeof(pti), &pti);
534 }
535
536 /* Get and set magic cookie again as some
537 * encoders may change it during encoding.
538 */
539 CA::UInt32 cookieSize = 4;
540
541 if (CA::AudioConverterGetPropertyInfo(converter, CA::kAudioConverterCompressionMagicCookie, &cookieSize, NULL) == 0)
542 {
543 unsigned char *cookie = (unsigned char *) malloc(cookieSize);
544
545 CA::AudioConverterGetProperty(converter, CA::kAudioConverterCompressionMagicCookie, &cookieSize, cookie);
546 CA::AudioFileSetProperty(audioFile, CA::kAudioFilePropertyMagicCookieData, cookieSize, cookie);
547
548 free(cookie);
549 }
550
551 /* Close converter and audio file.
552 */
553 CA::AudioConverterDispose(converter);
554 CA::AudioFileClose(audioFile);
555
556 fclose(file);
557 }
558
559 comm->status = CommStatusReady;
560
561 break;
562 case CommCommandDuration:
563 comm->length = sizeof(int64_t);
564
565 comm->data[0] = duration >> 32;
566 comm->data[1] = duration & 0xFFFFFFFF;
567
568 comm->status = CommStatusReady;
569
570 break;
571 case CommCommandQuit:
572 comm->status = CommStatusReady;
573
574 break;
575 }
576
577 #ifndef __WINE__
578 ReleaseSemaphore(semaphore, 1, NULL);
579 #else
580 semop(semaphore, opPost, 1);
581 #endif
582
583 if (comm->command == CommCommandQuit) break;
584 }
585
586 /* Free Core Audio DLLs.
587 */
588 FreeCoreAudioDLL();
589
590 /* Unmap view and close shared memory object.
591 */
592 #ifndef __WINE__
593 UnmapViewOfFile(comm);
594 CloseHandle(mapping);
595 CloseHandle(semaphore);
596 #else
597 munmap(comm, sizeof(CoreAudioCommBuffer));
598 close(mapping);
599 #endif
600
601 return 0;
602 }