]> git.sesse.net Git - vlc/blob - modules/access/qtsound.m
vpx: fix leak
[vlc] / modules / access / qtsound.m
1 /*****************************************************************************
2 * qtsound.m: qtkit (Mac OS X) based audio capture module
3 *****************************************************************************
4 * Copyright © 2011 VLC authors and VideoLAN
5 *
6 * Authors: Pierre d'Herbemont <pdherbemont@videolan.org>
7 *          Gustaf Neumann <neumann@wu.ac.at>
8 *          Michael S. Feurstein <michael.feurstein@wu.ac.at>
9 *
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.
15 *
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.
20 *
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
24 *
25 *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30
31 #ifdef HAVE_CONFIG_H
32 # include "config.h"
33 #endif
34
35 #include <vlc_common.h>
36 #include <vlc_plugin.h>
37 #include <vlc_aout.h>
38
39 #include <vlc_demux.h>
40 #include <vlc_dialog.h>
41
42 #define QTKIT_VERSION_MIN_REQUIRED 70603
43
44 #import <QTKit/QTKit.h>
45
46 /*****************************************************************************
47  * Local prototypes.
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);
53
54 /*****************************************************************************
55  * Module descriptor
56  *****************************************************************************/
57
58 vlc_module_begin()
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)
66 vlc_module_end ()
67
68
69 /*****************************************************************************
70  * QTKit Bridge
71  *****************************************************************************/
72 @interface VLCDecompressedAudioOutput : QTCaptureDecompressedAudioOutput
73 {
74     demux_t *p_qtsound;
75     AudioBuffer *currentAudioBuffer;
76     void *rawAudioData;
77     UInt32 numberOfSamples;
78     date_t date;
79     mtime_t currentPts;
80     mtime_t previousPts;
81 }
82 - (id)initWithDemux:(demux_t *)p_demux;
83 - (void)outputAudioSampleBuffer:(QTSampleBuffer *)sampleBuffer fromConnection:(QTCaptureConnection *)connection;
84 - (BOOL)checkCurrentAudioBuffer;
85 - (void)freeAudioMem;
86 - (mtime_t)getCurrentPts;
87 - (void *)getCurrentAudioBufferData;
88 - (UInt32)getCurrentTotalDataSize;
89 - (UInt32)getNumberOfSamples;
90
91 @end
92
93 @implementation VLCDecompressedAudioOutput : QTCaptureDecompressedAudioOutput
94 - (id)initWithDemux:(demux_t *)p_demux
95 {
96     if (self = [super init]) {
97         p_qtsound = p_demux;
98         currentAudioBuffer = nil;
99         date_Init(&date, 44100, 1);
100         date_Set(&date,0);
101         currentPts = 0;
102         previousPts = 0;
103     }
104     return self;
105 }
106 - (void)dealloc
107 {
108     [super dealloc];
109 }
110
111 - (void)outputAudioSampleBuffer:(QTSampleBuffer *)sampleBuffer fromConnection:(QTCaptureConnection *)connection
112 {
113     AudioBufferList *tempAudioBufferList;
114     UInt32 totalDataSize = 0;
115     UInt32 count = 0;
116
117     @synchronized (self) {
118         numberOfSamples = [sampleBuffer numberOfSamples];
119         date_Increment(&date,numberOfSamples);
120         currentPts = date_Get(&date);
121
122         tempAudioBufferList = [sampleBuffer audioBufferListWithOptions:0];
123         if (tempAudioBufferList->mNumberBuffers == 2) {
124             /*
125              * Compute totalDataSize as sum of all data blocks in the
126              * audio buffer list:
127              */
128             for (count = 0; count < tempAudioBufferList->mNumberBuffers; count++)
129                 totalDataSize += tempAudioBufferList->mBuffers[count].mDataByteSize;
130
131             /*
132              * Allocate storage for the interleaved audio data
133              */
134             rawAudioData = malloc(totalDataSize);
135             if (NULL == rawAudioData) {
136                 msg_Err(p_qtsound, "Raw audiodata could not be allocated");
137                 return;
138             }
139         } else {
140             msg_Err(p_qtsound, "Too many or only one channel found: %i.",
141                                tempAudioBufferList->mNumberBuffers);
142             return;
143         }
144
145         /*
146          * Interleave raw data (provided in two separate channels as
147          * F32L) with 2 samples per frame
148          */
149         if (totalDataSize) {
150             unsigned short i;
151             const float *b1Ptr, *b2Ptr;
152             float *uPtr;
153
154             for (i = 0,
155                  uPtr = (float *)rawAudioData,
156                  b1Ptr = (const float *) tempAudioBufferList->mBuffers[0].mData,
157                  b2Ptr = (const float *) tempAudioBufferList->mBuffers[1].mData;
158                  i < numberOfSamples; i++) {
159                 *uPtr++ = *b1Ptr++;
160                 *uPtr++ = *b2Ptr++;
161             }
162
163             if (currentAudioBuffer == nil) {
164                 currentAudioBuffer = (AudioBuffer *)malloc(sizeof(AudioBuffer));
165                 if (NULL == currentAudioBuffer) {
166                     msg_Err(p_qtsound, "AudioBuffer could not be allocated.");
167                     return;
168                 }
169             }
170             currentAudioBuffer->mNumberChannels = 2;
171             currentAudioBuffer->mDataByteSize = totalDataSize;
172             currentAudioBuffer->mData = rawAudioData;
173         }
174     }
175 }
176
177 - (BOOL)checkCurrentAudioBuffer
178 {
179     return (currentAudioBuffer) ? 1 : 0;
180 }
181
182 - (void)freeAudioMem
183 {
184     FREENULL(rawAudioData);
185 }
186
187 - (mtime_t)getCurrentPts
188 {
189     /* FIXME: can this getter be minimized? */
190     mtime_t pts;
191
192     if(!currentAudioBuffer || currentPts == previousPts)
193         return 0;
194
195     @synchronized (self) {
196         pts = previousPts = currentPts;
197     }
198
199     return (currentAudioBuffer->mData) ? currentPts : 0;
200 }
201
202 - (void *)getCurrentAudioBufferData
203 {
204     return currentAudioBuffer->mData;
205 }
206
207 - (UInt32)getCurrentTotalDataSize
208 {
209     return currentAudioBuffer->mDataByteSize;
210 }
211
212 - (UInt32)getNumberOfSamples
213 {
214     return numberOfSamples;
215 }
216
217 @end
218
219 /*****************************************************************************
220  * Struct
221  *****************************************************************************/
222
223 struct demux_sys_t {
224     QTCaptureSession * session;
225     QTCaptureDevice * audiodevice;
226     VLCDecompressedAudioOutput * audiooutput;
227     es_out_id_t *p_es_audio;
228 };
229
230 /*****************************************************************************
231  * Open: initialize interface
232  *****************************************************************************/
233 static int Open(vlc_object_t *p_this)
234 {
235     demux_t *p_demux = (demux_t*)p_this;
236     demux_sys_t *p_sys;
237     es_format_t audiofmt;
238     char *psz_uid = NULL;
239     int audiocodec;
240     bool success;
241     NSString *qtk_curraudiodevice_uid;
242     NSAutoreleasePool *pool;
243     NSArray *myAudioDevices, *audioformat_array;
244     QTFormatDescription *audio_format;
245     QTCaptureDeviceInput *audioInput;
246     NSError *o_returnedAudioError;
247
248     if(p_demux->psz_location && *p_demux->psz_location)
249         psz_uid = p_demux->psz_location;
250
251     msg_Dbg(p_demux, "qtsound uid = %s", psz_uid);
252     qtk_curraudiodevice_uid = [[NSString alloc] initWithFormat:@"%s", psz_uid];
253
254     pool = [[NSAutoreleasePool alloc] init];
255
256     p_demux->p_sys = p_sys = calloc(1, sizeof(demux_sys_t));
257     if(!p_sys)
258         return VLC_ENOMEM;
259
260     msg_Dbg(p_demux, "qtsound : uid = %s", [qtk_curraudiodevice_uid UTF8String]);
261     myAudioDevices = [[[QTCaptureDevice inputDevicesWithMediaType:QTMediaTypeSound] arrayByAddingObjectsFromArray:[QTCaptureDevice inputDevicesWithMediaType:QTMediaTypeMuxed]] retain];
262     if([myAudioDevices count] == 0) {
263         dialog_FatalWait(p_demux, _("No Audio Input device found"),
264                          _("Your Mac does not seem to be equipped with a suitable audio input device."
265                      "Please check your connectors and drivers."));
266         msg_Err(p_demux, "Can't find any Audio device");
267
268         goto error;
269     }
270     unsigned iaudio;
271     for (iaudio = 0; iaudio < [myAudioDevices count]; iaudio++) {
272         QTCaptureDevice *qtk_audioDevice;
273         qtk_audioDevice = [myAudioDevices objectAtIndex:iaudio];
274         msg_Dbg(p_demux, "qtsound audio %u/%lu localizedDisplayName: %s uniqueID: %s", iaudio, [myAudioDevices count], [[qtk_audioDevice localizedDisplayName] UTF8String], [[qtk_audioDevice uniqueID] UTF8String]);
275         if ([[[qtk_audioDevice uniqueID]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString:qtk_curraudiodevice_uid]) {
276             msg_Dbg(p_demux, "Device found");
277             break;
278         }
279     }
280
281     audioInput = nil;
282     if(iaudio < [myAudioDevices count])
283         p_sys->audiodevice = [myAudioDevices objectAtIndex:iaudio];
284     else {
285         /* cannot find designated audio device, fall back to open default audio device */
286         msg_Dbg(p_demux, "Cannot find designated uid audio device as %s. Fall back to open default audio device.", [qtk_curraudiodevice_uid UTF8String]);
287         p_sys->audiodevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
288     }
289     if(!p_sys->audiodevice) {
290         dialog_FatalWait(p_demux, _("No audio input device found"),
291                          _("Your Mac does not seem to be equipped with a suitable audio input device."
292                      "Please check your connectors and drivers."));
293         msg_Err(p_demux, "Can't find any Audio device");
294
295         goto error;
296     }
297
298     if(![p_sys->audiodevice open: &o_returnedAudioError]) {
299         msg_Err(p_demux, "Unable to open the audio capture device (%ld)", [o_returnedAudioError code]);
300         goto error;
301     }
302
303     if([p_sys->audiodevice isInUseByAnotherApplication] == YES) {
304         msg_Err(p_demux, "default audio capture device is exclusively in use by another application");
305         goto error;
306     }
307     audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: p_sys->audiodevice];
308     if(!audioInput) {
309         msg_Err(p_demux, "can't create a valid audio capture input facility");
310         goto error;
311     } else
312         msg_Dbg(p_demux, "created valid audio capture input facility");
313
314     p_sys->audiooutput = [[VLCDecompressedAudioOutput alloc] initWithDemux:p_demux];
315     msg_Dbg (p_demux, "initialized audio output");
316
317     /* Get the formats */
318     /*
319      FIXME: the format description gathered here does not seem to be the same
320      in comparison to the format description collected from the actual sampleBuffer.
321      This information needs to be updated some other place. For the time being this shall suffice.
322
323      The following verbose output is an example of what is read from the input device during the below block
324      [0x3042138] qtsound demux debug: Audio localized format summary: Linear PCM, 24 bit little-endian signed integer, 2 channels, 44100 Hz
325      [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
326      [0x3042138] qtsound demux debug: Flag float 0 bigEndian 0 signedInt 1 packed 0 alignedHigh 0 non interleaved 0 non mixable 0
327      canonical 0 nativeFloatPacked 0 nativeEndian 0
328
329      However when reading this information from the sampleBuffer during the delegate call from
330      - (void)outputAudioSampleBuffer:(QTSampleBuffer *)sampleBuffer fromConnection:(QTCaptureConnection *)connection;
331      the following data shows up
332      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
333      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
334      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
335      canonical 1 nativeFloatPacked 1 nativeEndian 0
336
337      Note the differences
338      24bit vs. 32bit
339      little-endian signed integer vs. little-endian floating point
340      format flag 00000004 vs. 00000029
341      bytes per packet 8 vs. 4
342      packed 0 vs. 1
343      non interleaved 0 vs. 1 -> this makes a major difference when filling our own buffer
344      canonical 0 vs. 1
345      nativeFloatPacked 0 vs. 1
346
347      One would assume we'd need to feed the (es_format_t)audiofmt with the data collected here.
348      This is not the case. Audio will be transmitted in artefacts, due to wrong information.
349
350      At the moment this data is set manually, however one should consider trying to set this data dynamically
351      */
352     audioformat_array = [p_sys->audiodevice formatDescriptions];
353     audio_format = NULL;
354     for(int k = 0; k < [audioformat_array count]; k++) {
355         audio_format = (QTFormatDescription *)[audioformat_array objectAtIndex:k];
356
357         msg_Dbg(p_demux, "Audio localized format summary: %s", [[audio_format localizedFormatSummary] UTF8String]);
358         msg_Dbg(p_demux, "Audio format description attributes: %s",[[[audio_format formatDescriptionAttributes] description] UTF8String]);
359
360         AudioStreamBasicDescription asbd = {0};
361         NSValue *asbdValue =  [audio_format attributeForKey:QTFormatDescriptionAudioStreamBasicDescriptionAttribute];
362         [asbdValue getValue:&asbd];
363
364         char formatIDString[5];
365         UInt32 formatID = CFSwapInt32HostToBig (asbd.mFormatID);
366         bcopy (&formatID, formatIDString, 4);
367         formatIDString[4] = '\0';
368
369         /* kept for development purposes */
370 #if 0
371         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",
372                 asbd.mSampleRate,
373                 formatIDString,
374                 asbd.mFormatFlags,
375                 asbd.mBytesPerPacket,
376                 asbd.mFramesPerPacket,
377                 asbd.mBytesPerFrame,
378                 asbd.mChannelsPerFrame,
379                 asbd.mBitsPerChannel);
380
381         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",
382                 (asbd.mFormatFlags & kAudioFormatFlagIsFloat) != 0,
383                 (asbd.mFormatFlags & kAudioFormatFlagIsBigEndian) != 0,
384                 (asbd.mFormatFlags & kAudioFormatFlagIsSignedInteger) != 0,
385                 (asbd.mFormatFlags & kAudioFormatFlagIsPacked) != 0,
386                 (asbd.mFormatFlags & kAudioFormatFlagIsAlignedHigh) != 0,
387                 (asbd.mFormatFlags & kAudioFormatFlagIsNonInterleaved) != 0,
388                 (asbd.mFormatFlags & kAudioFormatFlagIsNonMixable) != 0,
389
390                 (asbd.mFormatFlags & kAudioFormatFlagsCanonical) != 0,
391                 (asbd.mFormatFlags & kAudioFormatFlagsNativeFloatPacked) != 0,
392                 (asbd.mFormatFlags & kAudioFormatFlagsNativeEndian) != 0
393                );
394 #endif
395     }
396
397     if([audioformat_array count])
398         audio_format = [audioformat_array objectAtIndex:0];
399     else
400         goto error;
401
402     /* Now we can init */
403     audiocodec = VLC_CODEC_FL32;
404     es_format_Init(&audiofmt, AUDIO_ES, audiocodec);
405
406     audiofmt.audio.i_format = audiocodec;
407     audiofmt.audio.i_rate = 44100;
408     /*
409      * i_physical_channels Describes the channels configuration of the
410      * samples (ie. number of channels which are available in the
411      * buffer, and positions).
412      */
413     audiofmt.audio.i_physical_channels = AOUT_CHAN_RIGHT | AOUT_CHAN_LEFT;
414     /*
415      * i_original_channels Describes from which original channels,
416      * before downmixing, the buffer is derived.
417      */
418     audiofmt.audio.i_original_channels = AOUT_CHAN_RIGHT | AOUT_CHAN_LEFT;
419     /*
420      * Please note that it may be completely arbitrary - buffers are not
421      * obliged to contain a integral number of so-called "frames". It's
422      * just here for the division:
423      * buffer_size = i_nb_samples * i_bytes_per_frame / i_frame_length
424      */
425     audiofmt.audio.i_bitspersample = 32;
426     audiofmt.audio.i_channels = 2;
427     audiofmt.audio.i_blockalign = audiofmt.audio.i_channels * (audiofmt.audio.i_bitspersample / 8);
428     audiofmt.i_bitrate = audiofmt.audio.i_channels * audiofmt.audio.i_rate * audiofmt.audio.i_bitspersample;
429
430     p_sys->session = [[QTCaptureSession alloc] init];
431
432     success = [p_sys->session addInput:audioInput error: &o_returnedAudioError];
433     if(!success) {
434         msg_Err(p_demux, "the audio capture device could not be added to capture session (%ld)", [o_returnedAudioError code]);
435         goto error;
436     }
437
438     success = [p_sys->session addOutput:p_sys->audiooutput error: &o_returnedAudioError];
439     if(!success) {
440         msg_Err(p_demux, "audio output could not be added to capture session (%ld)", [o_returnedAudioError code]);
441         goto error;
442     }
443
444     [p_sys->session startRunning];
445
446     /* Set up p_demux */
447     p_demux->pf_demux = Demux;
448     p_demux->pf_control = Control;
449     p_demux->info.i_update = 0;
450     p_demux->info.i_title = 0;
451     p_demux->info.i_seekpoint = 0;
452
453     msg_Dbg(p_demux, "New audio es %d channels %dHz",
454             audiofmt.audio.i_channels, audiofmt.audio.i_rate);
455
456     p_sys->p_es_audio = es_out_Add(p_demux->out, &audiofmt);
457
458     [audioInput release];
459     [pool release];
460
461     msg_Dbg(p_demux, "QTSound: We have an audio device ready!");
462
463     return VLC_SUCCESS;
464 error:
465     [audioInput release];
466     [pool release];
467
468     free(p_sys);
469
470     return VLC_EGENERIC;
471 }
472
473 /*****************************************************************************
474  * Close: destroy interface
475  *****************************************************************************/
476 static void Close(vlc_object_t *p_this)
477 {
478     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
479     demux_t *p_demux = (demux_t*)p_this;
480     demux_sys_t *p_sys = p_demux->p_sys;
481
482     [p_sys->session performSelectorOnMainThread:@selector(stopRunning) withObject:nil waitUntilDone:NO];
483     [p_sys->audiooutput performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
484     [p_sys->session performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];
485
486     free(p_sys);
487
488     [pool release];
489 }
490
491 /*****************************************************************************
492  * Demux:
493  *****************************************************************************/
494 static int Demux(demux_t *p_demux)
495 {
496     demux_sys_t *p_sys = p_demux->p_sys;
497     block_t *p_blocka = nil;
498     NSAutoreleasePool *pool;
499
500
501
502     @synchronized (p_sys->audiooutput) {
503         if ([p_sys->audiooutput checkCurrentAudioBuffer]) {
504             unsigned i_buffer_size = [p_sys->audiooutput getCurrentTotalDataSize];
505             p_blocka = block_Alloc(i_buffer_size);
506
507             if(!p_blocka) {
508                 msg_Err(p_demux, "cannot get audio block");
509                 return 0;
510             }
511
512             memcpy(p_blocka->p_buffer, [p_sys->audiooutput getCurrentAudioBufferData], i_buffer_size);
513             p_blocka->i_nb_samples = [p_sys->audiooutput getNumberOfSamples];
514             p_blocka->i_pts = [p_sys->audiooutput getCurrentPts];
515
516             [p_sys->audiooutput freeAudioMem];
517         }
518     }
519
520     if (p_blocka) {
521         if (!p_blocka->i_pts) {
522             block_Release(p_blocka);
523
524             // Nothing to transfer yet, just forget
525             msleep(10000);
526             return 1;
527         }
528
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);
531     }
532
533     return 1;
534 }
535
536 /*****************************************************************************
537  * Control:
538  *****************************************************************************/
539 static int Control(demux_t *p_demux, int i_query, va_list args)
540 {
541     bool *pb;
542     int64_t *pi64;
543
544     switch(i_query) {
545             /* Special for access_demux */
546         case DEMUX_CAN_PAUSE:
547         case DEMUX_CAN_SEEK:
548         case DEMUX_SET_PAUSE_STATE:
549         case DEMUX_CAN_CONTROL_PACE:
550             pb = (bool*)va_arg(args, bool *);
551             *pb = false;
552             return VLC_SUCCESS;
553
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");
557             return VLC_SUCCESS;
558
559         default:
560             return VLC_EGENERIC;
561     }
562     return VLC_EGENERIC;
563 }