1 /*****************************************************************************
2 * qtsound.m: qtkit (Mac OS X) based audio capture module
3 *****************************************************************************
4 * Copyright © 2011 VLC authors and VideoLAN
6 * Authors: Pierre d'Herbemont <pdherbemont@videolan.org>
7 * Gustaf Neumann <neumann@wu.ac.at>
8 * Michael S. Feurstein <michael.feurstein@wu.ac.at>
10 *****************************************************************************
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public License
13 * as published by the Free Software Foundation; either version 2.1
14 * of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
25 *****************************************************************************/
27 /*****************************************************************************
29 *****************************************************************************/
35 #include <vlc_common.h>
36 #include <vlc_plugin.h>
39 #include <vlc_demux.h>
40 #include <vlc_dialog.h>
42 #define QTKIT_VERSION_MIN_REQUIRED 70603
44 #import <QTKit/QTKit.h>
46 /*****************************************************************************
48 *****************************************************************************/
49 static int Open(vlc_object_t *p_this);
50 static void Close(vlc_object_t *p_this);
51 static int Demux(demux_t *p_demux);
52 static int Control(demux_t *, int, va_list);
54 /*****************************************************************************
56 *****************************************************************************/
59 set_shortname(N_("QTSound"))
60 set_description(N_("QuickTime Sound Capture"))
61 set_category(CAT_INPUT)
62 set_subcategory(SUBCAT_INPUT_ACCESS)
63 add_shortcut("qtsound")
64 set_capability("access_demux", 0)
65 set_callbacks(Open, Close)
69 /*****************************************************************************
71 *****************************************************************************/
72 @interface VLCDecompressedAudioOutput : QTCaptureDecompressedAudioOutput
75 AudioBuffer *currentAudioBuffer;
77 UInt32 numberOfSamples;
82 - (id)initWithDemux:(demux_t *)p_demux;
83 - (void)outputAudioSampleBuffer:(QTSampleBuffer *)sampleBuffer fromConnection:(QTCaptureConnection *)connection;
84 - (BOOL)checkCurrentAudioBuffer;
86 - (mtime_t)getCurrentPts;
87 - (void *)getCurrentAudioBufferData;
88 - (UInt32)getCurrentTotalDataSize;
89 - (UInt32)getNumberOfSamples;
93 @implementation VLCDecompressedAudioOutput : QTCaptureDecompressedAudioOutput
94 - (id)initWithDemux:(demux_t *)p_demux
96 if (self = [super init]) {
98 currentAudioBuffer = nil;
99 date_Init(&date, 44100, 1);
111 - (void)outputAudioSampleBuffer:(QTSampleBuffer *)sampleBuffer fromConnection:(QTCaptureConnection *)connection
113 AudioBufferList *tempAudioBufferList;
114 UInt32 totalDataSize = 0;
117 @synchronized (self) {
118 numberOfSamples = [sampleBuffer numberOfSamples];
119 date_Increment(&date,numberOfSamples);
120 currentPts = date_Get(&date);
122 tempAudioBufferList = [sampleBuffer audioBufferListWithOptions:0];
123 if (tempAudioBufferList->mNumberBuffers == 2) {
125 * Compute totalDataSize as sum of all data blocks in the
128 for (count = 0; count < tempAudioBufferList->mNumberBuffers; count++)
129 totalDataSize += tempAudioBufferList->mBuffers[count].mDataByteSize;
132 * Allocate storage for the interleaved audio data
134 rawAudioData = malloc(totalDataSize);
135 if (NULL == rawAudioData) {
136 msg_Err(p_qtsound, "Raw audiodata could not be allocated");
140 msg_Err(p_qtsound, "Too many or only one channel found: %i.",
141 tempAudioBufferList->mNumberBuffers);
146 * Interleave raw data (provided in two separate channels as
147 * F32L) with 2 samples per frame
151 const float *b1Ptr, *b2Ptr;
155 uPtr = (float *)rawAudioData,
156 b1Ptr = (const float *) tempAudioBufferList->mBuffers[0].mData,
157 b2Ptr = (const float *) tempAudioBufferList->mBuffers[1].mData;
158 i < numberOfSamples; i++) {
163 if (currentAudioBuffer == nil) {
164 currentAudioBuffer = (AudioBuffer *)malloc(sizeof(AudioBuffer));
165 if (NULL == currentAudioBuffer) {
166 msg_Err(p_qtsound, "AudioBuffer could not be allocated.");
170 currentAudioBuffer->mNumberChannels = 2;
171 currentAudioBuffer->mDataByteSize = totalDataSize;
172 currentAudioBuffer->mData = rawAudioData;
177 - (BOOL)checkCurrentAudioBuffer
179 return (currentAudioBuffer) ? 1 : 0;
184 FREENULL(rawAudioData);
187 - (mtime_t)getCurrentPts
189 /* FIXME: can this getter be minimized? */
192 if(!currentAudioBuffer || currentPts == previousPts)
195 @synchronized (self) {
196 pts = previousPts = currentPts;
199 return (currentAudioBuffer->mData) ? currentPts : 0;
202 - (void *)getCurrentAudioBufferData
204 return currentAudioBuffer->mData;
207 - (UInt32)getCurrentTotalDataSize
209 return currentAudioBuffer->mDataByteSize;
212 - (UInt32)getNumberOfSamples
214 return numberOfSamples;
219 /*****************************************************************************
221 *****************************************************************************/
224 QTCaptureSession * session;
225 QTCaptureDevice * audiodevice;
226 VLCDecompressedAudioOutput * audiooutput;
227 es_out_id_t *p_es_audio;
230 /*****************************************************************************
231 * Open: initialize interface
232 *****************************************************************************/
233 static int Open(vlc_object_t *p_this)
235 demux_t *p_demux = (demux_t*)p_this;
237 es_format_t audiofmt;
238 char *psz_uid = NULL;
241 NSString *qtk_curraudiodevice_uid;
242 NSArray *myAudioDevices, *audioformat_array;
243 QTFormatDescription *audio_format;
244 QTCaptureDeviceInput *audioInput;
245 NSError *o_returnedAudioError;
248 if(p_demux->psz_location && *p_demux->psz_location)
249 psz_uid = p_demux->psz_location;
251 msg_Dbg(p_demux, "qtsound uid = %s", psz_uid);
252 qtk_curraudiodevice_uid = [[NSString alloc] initWithFormat:@"%s", psz_uid];
254 p_demux->p_sys = p_sys = calloc(1, sizeof(demux_sys_t));
258 msg_Dbg(p_demux, "qtsound : uid = %s", [qtk_curraudiodevice_uid UTF8String]);
259 myAudioDevices = [[[QTCaptureDevice inputDevicesWithMediaType:QTMediaTypeSound]
260 arrayByAddingObjectsFromArray:[QTCaptureDevice inputDevicesWithMediaType:QTMediaTypeMuxed]] retain];
261 if([myAudioDevices count] == 0) {
262 vlc_dialog_display_error(p_demux, _("No Audio Input device found"),
263 _("Your Mac does not seem to be equipped with a suitable audio input device."
264 "Please check your connectors and drivers."));
265 msg_Err(p_demux, "Can't find any Audio device");
270 for (iaudio = 0; iaudio < [myAudioDevices count]; iaudio++) {
271 QTCaptureDevice *qtk_audioDevice;
272 qtk_audioDevice = [myAudioDevices objectAtIndex:iaudio];
273 msg_Dbg(p_demux, "qtsound audio %u/%lu localizedDisplayName: %s uniqueID: %s",
274 iaudio, [myAudioDevices count],
275 [[qtk_audioDevice localizedDisplayName] UTF8String],
276 [[qtk_audioDevice uniqueID] UTF8String]);
277 if ([[[qtk_audioDevice uniqueID] stringByTrimmingCharactersInSet:
278 [NSCharacterSet whitespaceCharacterSet]] isEqualToString:qtk_curraudiodevice_uid]) {
279 msg_Dbg(p_demux, "Device found");
285 if(iaudio < [myAudioDevices count])
286 p_sys->audiodevice = [myAudioDevices objectAtIndex:iaudio];
288 /* cannot find designated audio device, fall back to open default audio device */
289 msg_Dbg(p_demux, "Cannot find designated uid audio device as %s. Fall back to open default audio device.", [qtk_curraudiodevice_uid UTF8String]);
290 p_sys->audiodevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
292 if(!p_sys->audiodevice) {
293 vlc_dialog_display_error(p_demux, _("No audio input device found"),
294 _("Your Mac does not seem to be equipped with a suitable audio input device."
295 "Please check your connectors and drivers."));
296 msg_Err(p_demux, "Can't find any Audio device");
301 if(![p_sys->audiodevice open: &o_returnedAudioError]) {
302 msg_Err(p_demux, "Unable to open the audio capture device (%ld)", [o_returnedAudioError code]);
306 if([p_sys->audiodevice isInUseByAnotherApplication] == YES) {
307 msg_Err(p_demux, "default audio capture device is exclusively in use by another application");
310 audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: p_sys->audiodevice];
312 msg_Err(p_demux, "can't create a valid audio capture input facility");
315 msg_Dbg(p_demux, "created valid audio capture input facility");
317 p_sys->audiooutput = [[VLCDecompressedAudioOutput alloc] initWithDemux:p_demux];
318 msg_Dbg (p_demux, "initialized audio output");
320 /* Get the formats */
322 FIXME: the format description gathered here does not seem to be the same
323 in comparison to the format description collected from the actual sampleBuffer.
324 This information needs to be updated some other place. For the time being this shall suffice.
326 The following verbose output is an example of what is read from the input device during the below block
327 [0x3042138] qtsound demux debug: Audio localized format summary: Linear PCM, 24 bit little-endian signed integer, 2 channels, 44100 Hz
328 [0x3042138] qtsound demux debug: Sample Rate: 44100; Format ID: lpcm; Format Flags: 00000004; Bytes per Packet: 8; Frames per Packet: 1; Bytes per Frame: 8; Channels per Frame: 2; Bits per Channel: 24
329 [0x3042138] qtsound demux debug: Flag float 0 bigEndian 0 signedInt 1 packed 0 alignedHigh 0 non interleaved 0 non mixable 0
330 canonical 0 nativeFloatPacked 0 nativeEndian 0
332 However when reading this information from the sampleBuffer during the delegate call from
333 - (void)outputAudioSampleBuffer:(QTSampleBuffer *)sampleBuffer fromConnection:(QTCaptureConnection *)connection;
334 the following data shows up
335 2011-09-23 22:06:03.077 VLC[23070:f103] Audio localized format summary: Linear PCM, 32 bit little-endian floating point, 2 channels, 44100 Hz
336 2011-09-23 22:06:03.078 VLC[23070:f103] Sample Rate: 44100; Format ID: lpcm; Format Flags: 00000029; Bytes per Packet: 4; Frames per Packet: 1; Bytes per Frame: 4; Channels per Frame: 2; Bits per Channel: 32
337 2011-09-23 22:06:03.078 VLC[23070:f103] Flag float 1 bigEndian 0 signedInt 0 packed 1 alignedHigh 0 non interleaved 1 non mixable 0
338 canonical 1 nativeFloatPacked 1 nativeEndian 0
342 little-endian signed integer vs. little-endian floating point
343 format flag 00000004 vs. 00000029
344 bytes per packet 8 vs. 4
346 non interleaved 0 vs. 1 -> this makes a major difference when filling our own buffer
348 nativeFloatPacked 0 vs. 1
350 One would assume we'd need to feed the (es_format_t)audiofmt with the data collected here.
351 This is not the case. Audio will be transmitted in artefacts, due to wrong information.
353 At the moment this data is set manually, however one should consider trying to set this data dynamically
355 audioformat_array = [p_sys->audiodevice formatDescriptions];
357 for(int k = 0; k < [audioformat_array count]; k++) {
358 audio_format = (QTFormatDescription *)[audioformat_array objectAtIndex:k];
360 msg_Dbg(p_demux, "Audio localized format summary: %s", [[audio_format localizedFormatSummary] UTF8String]);
361 msg_Dbg(p_demux, "Audio format description attributes: %s",[[[audio_format formatDescriptionAttributes] description] UTF8String]);
363 AudioStreamBasicDescription asbd = {0};
364 NSValue *asbdValue = [audio_format attributeForKey:QTFormatDescriptionAudioStreamBasicDescriptionAttribute];
365 [asbdValue getValue:&asbd];
367 char formatIDString[5];
368 UInt32 formatID = CFSwapInt32HostToBig (asbd.mFormatID);
369 bcopy (&formatID, formatIDString, 4);
370 formatIDString[4] = '\0';
372 /* kept for development purposes */
374 msg_Dbg(p_demux, "Sample Rate: %.0lf; Format ID: %s; Format Flags: %.8x; Bytes per Packet: %d; Frames per Packet: %d; Bytes per Frame: %d; Channels per Frame: %d; Bits per Channel: %d",
378 asbd.mBytesPerPacket,
379 asbd.mFramesPerPacket,
381 asbd.mChannelsPerFrame,
382 asbd.mBitsPerChannel);
384 msg_Dbg(p_demux, "Flag float %d bigEndian %d signedInt %d packed %d alignedHigh %d non interleaved %d non mixable %d\ncanonical %d nativeFloatPacked %d nativeEndian %d",
385 (asbd.mFormatFlags & kAudioFormatFlagIsFloat) != 0,
386 (asbd.mFormatFlags & kAudioFormatFlagIsBigEndian) != 0,
387 (asbd.mFormatFlags & kAudioFormatFlagIsSignedInteger) != 0,
388 (asbd.mFormatFlags & kAudioFormatFlagIsPacked) != 0,
389 (asbd.mFormatFlags & kAudioFormatFlagIsAlignedHigh) != 0,
390 (asbd.mFormatFlags & kAudioFormatFlagIsNonInterleaved) != 0,
391 (asbd.mFormatFlags & kAudioFormatFlagIsNonMixable) != 0,
393 (asbd.mFormatFlags & kAudioFormatFlagsCanonical) != 0,
394 (asbd.mFormatFlags & kAudioFormatFlagsNativeFloatPacked) != 0,
395 (asbd.mFormatFlags & kAudioFormatFlagsNativeEndian) != 0
400 if([audioformat_array count])
401 audio_format = [audioformat_array objectAtIndex:0];
405 /* Now we can init */
406 audiocodec = VLC_CODEC_FL32;
407 es_format_Init(&audiofmt, AUDIO_ES, audiocodec);
409 audiofmt.audio.i_format = audiocodec;
410 audiofmt.audio.i_rate = 44100;
412 * i_physical_channels Describes the channels configuration of the
413 * samples (ie. number of channels which are available in the
414 * buffer, and positions).
416 audiofmt.audio.i_physical_channels = AOUT_CHAN_RIGHT | AOUT_CHAN_LEFT;
418 * i_original_channels Describes from which original channels,
419 * before downmixing, the buffer is derived.
421 audiofmt.audio.i_original_channels = AOUT_CHAN_RIGHT | AOUT_CHAN_LEFT;
423 * Please note that it may be completely arbitrary - buffers are not
424 * obliged to contain a integral number of so-called "frames". It's
425 * just here for the division:
426 * buffer_size = i_nb_samples * i_bytes_per_frame / i_frame_length
428 audiofmt.audio.i_bitspersample = 32;
429 audiofmt.audio.i_channels = 2;
430 audiofmt.audio.i_blockalign = audiofmt.audio.i_channels * (audiofmt.audio.i_bitspersample / 8);
431 audiofmt.i_bitrate = audiofmt.audio.i_channels * audiofmt.audio.i_rate * audiofmt.audio.i_bitspersample;
433 p_sys->session = [[QTCaptureSession alloc] init];
435 success = [p_sys->session addInput:audioInput error: &o_returnedAudioError];
437 msg_Err(p_demux, "the audio capture device could not be added to capture session (%ld)", [o_returnedAudioError code]);
441 success = [p_sys->session addOutput:p_sys->audiooutput error: &o_returnedAudioError];
443 msg_Err(p_demux, "audio output could not be added to capture session (%ld)", [o_returnedAudioError code]);
447 [p_sys->session startRunning];
450 p_demux->pf_demux = Demux;
451 p_demux->pf_control = Control;
452 p_demux->info.i_update = 0;
453 p_demux->info.i_title = 0;
454 p_demux->info.i_seekpoint = 0;
456 msg_Dbg(p_demux, "New audio es %d channels %dHz",
457 audiofmt.audio.i_channels, audiofmt.audio.i_rate);
459 p_sys->p_es_audio = es_out_Add(p_demux->out, &audiofmt);
461 [audioInput release];
463 msg_Dbg(p_demux, "QTSound: We have an audio device ready!");
467 [audioInput release];
475 /*****************************************************************************
476 * Close: destroy interface
477 *****************************************************************************/
478 static void Close(vlc_object_t *p_this)
481 demux_t *p_demux = (demux_t*)p_this;
482 demux_sys_t *p_sys = p_demux->p_sys;
484 [p_sys->session performSelectorOnMainThread:@selector(stopRunning) withObject:nil waitUntilDone:NO];
485 [p_sys->audiooutput performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
486 [p_sys->session performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
492 /*****************************************************************************
494 *****************************************************************************/
495 static int Demux(demux_t *p_demux)
497 demux_sys_t *p_sys = p_demux->p_sys;
498 block_t *p_blocka = nil;
501 @synchronized (p_sys->audiooutput) {
502 if ([p_sys->audiooutput checkCurrentAudioBuffer]) {
503 unsigned i_buffer_size = [p_sys->audiooutput getCurrentTotalDataSize];
504 p_blocka = block_Alloc(i_buffer_size);
507 msg_Err(p_demux, "cannot get audio block");
511 memcpy(p_blocka->p_buffer, [p_sys->audiooutput getCurrentAudioBufferData], i_buffer_size);
512 p_blocka->i_nb_samples = [p_sys->audiooutput getNumberOfSamples];
513 p_blocka->i_pts = [p_sys->audiooutput getCurrentPts];
515 [p_sys->audiooutput freeAudioMem];
521 if (!p_blocka->i_pts) {
522 block_Release(p_blocka);
524 // Nothing to transfer yet, just forget
529 es_out_Control(p_demux->out, ES_OUT_SET_PCR, p_blocka->i_pts);
530 es_out_Send(p_demux->out, p_sys->p_es_audio, p_blocka);
536 /*****************************************************************************
538 *****************************************************************************/
539 static int Control(demux_t *p_demux, int i_query, va_list args)
545 /* Special for access_demux */
546 case DEMUX_CAN_PAUSE:
548 case DEMUX_SET_PAUSE_STATE:
549 case DEMUX_CAN_CONTROL_PACE:
550 pb = (bool*)va_arg(args, bool *);
554 case DEMUX_GET_PTS_DELAY:
555 pi64 = (int64_t*)va_arg(args, int64_t *);
556 *pi64 = INT64_C(1000) * var_InheritInteger(p_demux, "live-caching");