]> git.sesse.net Git - ffmpeg/blob - libavdevice/avfoundation.m
Merge commit 'b39ebcddd47daf37659796aaa7d068668086507a'
[ffmpeg] / libavdevice / avfoundation.m
1 /*
2  * AVFoundation input device
3  * Copyright (c) 2014 Thilo Borgmann <thilo.borgmann@mail.de>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * AVFoundation input device
25  * @author Thilo Borgmann <thilo.borgmann@mail.de>
26  */
27
28 #import <AVFoundation/AVFoundation.h>
29 #include <pthread.h>
30
31 #include "libavutil/pixdesc.h"
32 #include "libavutil/opt.h"
33 #include "libavformat/internal.h"
34 #include "libavutil/internal.h"
35 #include "libavutil/time.h"
36 #include "avdevice.h"
37
38 static const int avf_time_base = 1000000;
39
40 static const AVRational avf_time_base_q = {
41     .num = 1,
42     .den = avf_time_base
43 };
44
45 struct AVFPixelFormatSpec {
46     enum AVPixelFormat ff_id;
47     OSType avf_id;
48 };
49
50 static const struct AVFPixelFormatSpec avf_pixel_formats[] = {
51     { AV_PIX_FMT_MONOBLACK,    kCVPixelFormatType_1Monochrome },
52     { AV_PIX_FMT_RGB555BE,     kCVPixelFormatType_16BE555 },
53     { AV_PIX_FMT_RGB555LE,     kCVPixelFormatType_16LE555 },
54     { AV_PIX_FMT_RGB565BE,     kCVPixelFormatType_16BE565 },
55     { AV_PIX_FMT_RGB565LE,     kCVPixelFormatType_16LE565 },
56     { AV_PIX_FMT_RGB24,        kCVPixelFormatType_24RGB },
57     { AV_PIX_FMT_BGR24,        kCVPixelFormatType_24BGR },
58     { AV_PIX_FMT_0RGB,         kCVPixelFormatType_32ARGB },
59     { AV_PIX_FMT_BGR0,         kCVPixelFormatType_32BGRA },
60     { AV_PIX_FMT_0BGR,         kCVPixelFormatType_32ABGR },
61     { AV_PIX_FMT_RGB0,         kCVPixelFormatType_32RGBA },
62     { AV_PIX_FMT_BGR48BE,      kCVPixelFormatType_48RGB },
63     { AV_PIX_FMT_UYVY422,      kCVPixelFormatType_422YpCbCr8 },
64     { AV_PIX_FMT_YUVA444P,     kCVPixelFormatType_4444YpCbCrA8R },
65     { AV_PIX_FMT_YUVA444P16LE, kCVPixelFormatType_4444AYpCbCr16 },
66     { AV_PIX_FMT_YUV444P,      kCVPixelFormatType_444YpCbCr8 },
67     { AV_PIX_FMT_YUV422P16,    kCVPixelFormatType_422YpCbCr16 },
68     { AV_PIX_FMT_YUV422P10,    kCVPixelFormatType_422YpCbCr10 },
69     { AV_PIX_FMT_YUV444P10,    kCVPixelFormatType_444YpCbCr10 },
70     { AV_PIX_FMT_YUV420P,      kCVPixelFormatType_420YpCbCr8Planar },
71     { AV_PIX_FMT_NV12,         kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange },
72     { AV_PIX_FMT_YUYV422,      kCVPixelFormatType_422YpCbCr8_yuvs },
73 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
74     { AV_PIX_FMT_GRAY8,        kCVPixelFormatType_OneComponent8 },
75 #endif
76     { AV_PIX_FMT_NONE, 0 }
77 };
78
79 typedef struct
80 {
81     AVClass*        class;
82
83     float           frame_rate;
84     int             frames_captured;
85     int64_t         first_pts;
86     pthread_mutex_t frame_lock;
87     pthread_cond_t  frame_wait_cond;
88     id              avf_delegate;
89
90     int             list_devices;
91     int             video_device_index;
92     int             video_stream_index;
93     enum AVPixelFormat pixel_format;
94
95     AVCaptureSession         *capture_session;
96     AVCaptureVideoDataOutput *video_output;
97     CMSampleBufferRef         current_frame;
98 } AVFContext;
99
100 static void lock_frames(AVFContext* ctx)
101 {
102     pthread_mutex_lock(&ctx->frame_lock);
103 }
104
105 static void unlock_frames(AVFContext* ctx)
106 {
107     pthread_mutex_unlock(&ctx->frame_lock);
108 }
109
110 /** FrameReciever class - delegate for AVCaptureSession
111  */
112 @interface AVFFrameReceiver : NSObject
113 {
114     AVFContext* _context;
115 }
116
117 - (id)initWithContext:(AVFContext*)context;
118
119 - (void)  captureOutput:(AVCaptureOutput *)captureOutput
120   didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
121          fromConnection:(AVCaptureConnection *)connection;
122
123 @end
124
125 @implementation AVFFrameReceiver
126
127 - (id)initWithContext:(AVFContext*)context
128 {
129     if (self = [super init]) {
130         _context = context;
131     }
132     return self;
133 }
134
135 - (void)  captureOutput:(AVCaptureOutput *)captureOutput
136   didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
137          fromConnection:(AVCaptureConnection *)connection
138 {
139     lock_frames(_context);
140
141     if (_context->current_frame != nil) {
142         CFRelease(_context->current_frame);
143     }
144
145     _context->current_frame = (CMSampleBufferRef)CFRetain(videoFrame);
146
147     pthread_cond_signal(&_context->frame_wait_cond);
148
149     unlock_frames(_context);
150
151     ++_context->frames_captured;
152 }
153
154 @end
155
156 static void destroy_context(AVFContext* ctx)
157 {
158     [ctx->capture_session stopRunning];
159
160     [ctx->capture_session release];
161     [ctx->video_output    release];
162     [ctx->avf_delegate    release];
163
164     ctx->capture_session = NULL;
165     ctx->video_output    = NULL;
166     ctx->avf_delegate    = NULL;
167
168     pthread_mutex_destroy(&ctx->frame_lock);
169     pthread_cond_destroy(&ctx->frame_wait_cond);
170
171     if (ctx->current_frame) {
172         CFRelease(ctx->current_frame);
173     }
174 }
175
176 static int add_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
177 {
178     AVFContext *ctx = (AVFContext*)s->priv_data;
179     NSError *error  = nil;
180     AVCaptureDeviceInput* capture_dev_input = [[[AVCaptureDeviceInput alloc] initWithDevice:video_device error:&error] autorelease];
181
182     if (!capture_dev_input) {
183         av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
184                [[error localizedDescription] UTF8String]);
185         return 1;
186     }
187
188     if ([ctx->capture_session canAddInput:capture_dev_input]) {
189         [ctx->capture_session addInput:capture_dev_input];
190     } else {
191         av_log(s, AV_LOG_ERROR, "can't add video input to capture session\n");
192         return 1;
193     }
194
195     // Attaching output
196     ctx->video_output = [[AVCaptureVideoDataOutput alloc] init];
197
198     if (!ctx->video_output) {
199         av_log(s, AV_LOG_ERROR, "Failed to init AV video output\n");
200         return 1;
201     }
202
203     // select pixel format
204     struct AVFPixelFormatSpec pxl_fmt_spec;
205     pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
206
207     for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
208         if (ctx->pixel_format == avf_pixel_formats[i].ff_id) {
209             pxl_fmt_spec = avf_pixel_formats[i];
210             break;
211         }
212     }
213
214     // check if selected pixel format is supported by AVFoundation
215     if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
216         av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by AVFoundation.\n",
217                av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
218         return 1;
219     }
220
221     // check if the pixel format is available for this device
222     if ([[ctx->video_output availableVideoCVPixelFormatTypes] indexOfObject:[NSNumber numberWithInt:pxl_fmt_spec.avf_id]] == NSNotFound) {
223         av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by the input device.\n",
224                av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
225
226         pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
227
228         av_log(s, AV_LOG_ERROR, "Supported pixel formats:\n");
229         for (NSNumber *pxl_fmt in [ctx->video_output availableVideoCVPixelFormatTypes]) {
230             struct AVFPixelFormatSpec pxl_fmt_dummy;
231             pxl_fmt_dummy.ff_id = AV_PIX_FMT_NONE;
232             for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
233                 if ([pxl_fmt intValue] == avf_pixel_formats[i].avf_id) {
234                     pxl_fmt_dummy = avf_pixel_formats[i];
235                     break;
236                 }
237             }
238
239             if (pxl_fmt_dummy.ff_id != AV_PIX_FMT_NONE) {
240                 av_log(s, AV_LOG_ERROR, "  %s\n", av_get_pix_fmt_name(pxl_fmt_dummy.ff_id));
241
242                 // select first supported pixel format instead of user selected (or default) pixel format
243                 if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
244                     pxl_fmt_spec = pxl_fmt_dummy;
245                 }
246             }
247         }
248
249         // fail if there is no appropriate pixel format or print a warning about overriding the pixel format
250         if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
251             return 1;
252         } else {
253             av_log(s, AV_LOG_WARNING, "Overriding selected pixel format to use %s instead.\n",
254                    av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
255         }
256     }
257
258     ctx->pixel_format          = pxl_fmt_spec.ff_id;
259     NSNumber     *pixel_format = [NSNumber numberWithUnsignedInt:pxl_fmt_spec.avf_id];
260     NSDictionary *capture_dict = [NSDictionary dictionaryWithObject:pixel_format
261                                                forKey:(id)kCVPixelBufferPixelFormatTypeKey];
262
263     [ctx->video_output setVideoSettings:capture_dict];
264     [ctx->video_output setAlwaysDiscardsLateVideoFrames:YES];
265
266     ctx->avf_delegate = [[AVFFrameReceiver alloc] initWithContext:ctx];
267
268     dispatch_queue_t queue = dispatch_queue_create("avf_queue", NULL);
269     [ctx->video_output setSampleBufferDelegate:ctx->avf_delegate queue:queue];
270     dispatch_release(queue);
271
272     if ([ctx->capture_session canAddOutput:ctx->video_output]) {
273         [ctx->capture_session addOutput:ctx->video_output];
274     } else {
275         av_log(s, AV_LOG_ERROR, "can't add video output to capture session\n");
276         return 1;
277     }
278
279     return 0;
280 }
281
282 static int get_video_config(AVFormatContext *s)
283 {
284     AVFContext *ctx = (AVFContext*)s->priv_data;
285
286     // Take stream info from the first frame.
287     while (ctx->frames_captured < 1) {
288         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
289     }
290
291     lock_frames(ctx);
292
293     AVStream* stream = avformat_new_stream(s, NULL);
294
295     if (!stream) {
296         return 1;
297     }
298
299     ctx->video_stream_index = stream->index;
300
301     avpriv_set_pts_info(stream, 64, 1, avf_time_base);
302
303     CVImageBufferRef image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
304     CGSize image_buffer_size      = CVImageBufferGetEncodedSize(image_buffer);
305
306     stream->codec->codec_id   = AV_CODEC_ID_RAWVIDEO;
307     stream->codec->codec_type = AVMEDIA_TYPE_VIDEO;
308     stream->codec->width      = (int)image_buffer_size.width;
309     stream->codec->height     = (int)image_buffer_size.height;
310     stream->codec->pix_fmt    = ctx->pixel_format;
311
312     CFRelease(ctx->current_frame);
313     ctx->current_frame = nil;
314
315     unlock_frames(ctx);
316
317     return 0;
318 }
319
320 static int avf_read_header(AVFormatContext *s)
321 {
322     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
323     AVFContext *ctx         = (AVFContext*)s->priv_data;
324     ctx->first_pts          = av_gettime();
325
326     pthread_mutex_init(&ctx->frame_lock, NULL);
327     pthread_cond_init(&ctx->frame_wait_cond, NULL);
328
329     // List devices if requested
330     if (ctx->list_devices) {
331         av_log(ctx, AV_LOG_INFO, "AVFoundation video devices:\n");
332         NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
333         for (AVCaptureDevice *device in devices) {
334             const char *name = [[device localizedName] UTF8String];
335             int index  = [devices indexOfObject:device];
336             av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
337         }
338         goto fail;
339     }
340
341     // Find capture device
342     AVCaptureDevice *video_device = nil;
343
344     // check for device index given in filename
345     if (ctx->video_device_index == -1) {
346         sscanf(s->filename, "%d", &ctx->video_device_index);
347     }
348
349     if (ctx->video_device_index >= 0) {
350         NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
351
352         if (ctx->video_device_index >= [devices count]) {
353             av_log(ctx, AV_LOG_ERROR, "Invalid device index\n");
354             goto fail;
355         }
356
357         video_device = [devices objectAtIndex:ctx->video_device_index];
358     } else if (strncmp(s->filename, "",        1) &&
359                strncmp(s->filename, "default", 7)) {
360         NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
361
362         for (AVCaptureDevice *device in devices) {
363             if (!strncmp(s->filename, [[device localizedName] UTF8String], strlen(s->filename))) {
364                 video_device = device;
365                 break;
366             }
367         }
368
369         if (!video_device) {
370             av_log(ctx, AV_LOG_ERROR, "Video device not found\n");
371             goto fail;
372         }
373     } else {
374         video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
375     }
376
377     // Video capture device not found, looking for AVMediaTypeVideo
378     if (!video_device) {
379         video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
380
381         if (!video_device) {
382             av_log(s, AV_LOG_ERROR, "No AV capture device found\n");
383             goto fail;
384         }
385     }
386
387     av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device localizedName] UTF8String]);
388
389     // Initialize capture session
390     ctx->capture_session = [[AVCaptureSession alloc] init];
391
392     if (add_video_device(s, video_device)) {
393         goto fail;
394     }
395
396     [ctx->capture_session startRunning];
397
398     if (get_video_config(s)) {
399         goto fail;
400     }
401
402     [pool release];
403     return 0;
404
405 fail:
406     [pool release];
407     destroy_context(ctx);
408     return AVERROR(EIO);
409 }
410
411 static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
412 {
413     AVFContext* ctx = (AVFContext*)s->priv_data;
414
415     do {
416         lock_frames(ctx);
417
418         CVImageBufferRef image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
419
420         if (ctx->current_frame != nil) {
421             if (av_new_packet(pkt, (int)CVPixelBufferGetDataSize(image_buffer)) < 0) {
422                 return AVERROR(EIO);
423             }
424
425             pkt->pts = pkt->dts = av_rescale_q(av_gettime() - ctx->first_pts,
426                                                AV_TIME_BASE_Q,
427                                                avf_time_base_q);
428             pkt->stream_index  = ctx->video_stream_index;
429             pkt->flags        |= AV_PKT_FLAG_KEY;
430
431             CVPixelBufferLockBaseAddress(image_buffer, 0);
432
433             void* data = CVPixelBufferGetBaseAddress(image_buffer);
434             memcpy(pkt->data, data, pkt->size);
435
436             CVPixelBufferUnlockBaseAddress(image_buffer, 0);
437             CFRelease(ctx->current_frame);
438             ctx->current_frame = nil;
439         } else {
440             pkt->data = NULL;
441             pthread_cond_wait(&ctx->frame_wait_cond, &ctx->frame_lock);
442         }
443
444         unlock_frames(ctx);
445     } while (!pkt->data);
446
447     return 0;
448 }
449
450 static int avf_close(AVFormatContext *s)
451 {
452     AVFContext* ctx = (AVFContext*)s->priv_data;
453     destroy_context(ctx);
454     return 0;
455 }
456
457 static const AVOption options[] = {
458     { "frame_rate", "set frame rate", offsetof(AVFContext, frame_rate), AV_OPT_TYPE_FLOAT, { .dbl = 30.0 }, 0.1, 30.0, AV_OPT_TYPE_VIDEO_RATE, NULL },
459     { "list_devices", "list available devices", offsetof(AVFContext, list_devices), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
460     { "true", "", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
461     { "false", "", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
462     { "video_device_index", "select video device by index for devices with same name (starts at 0)", offsetof(AVFContext, video_device_index), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
463     { "pixel_format", "set pixel format", offsetof(AVFContext, pixel_format), AV_OPT_TYPE_PIXEL_FMT, {.i64 = AV_PIX_FMT_YUV420P}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM},
464     { NULL },
465 };
466
467 static const AVClass avf_class = {
468     .class_name = "AVFoundation input device",
469     .item_name  = av_default_item_name,
470     .option     = options,
471     .version    = LIBAVUTIL_VERSION_INT,
472     .category   = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
473 };
474
475 AVInputFormat ff_avfoundation_demuxer = {
476     .name           = "avfoundation",
477     .long_name      = NULL_IF_CONFIG_SMALL("AVFoundation input device"),
478     .priv_data_size = sizeof(AVFContext),
479     .read_header    = avf_read_header,
480     .read_packet    = avf_read_packet,
481     .read_close     = avf_close,
482     .flags          = AVFMT_NOFILE,
483     .priv_class     = &avf_class,
484 };