]> git.sesse.net Git - ffmpeg/blob - libavdevice/avfoundation.m
Merge commit '6bc4934b75dde9354ee16a6e700ebe6775abf69e'
[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 = 100;
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     { AV_PIX_FMT_GRAY8,        kCVPixelFormatType_OneComponent8 },
74     { AV_PIX_FMT_NONE, 0 }
75 };
76
77 typedef struct
78 {
79     AVClass*        class;
80
81     float           frame_rate;
82     int             frames_captured;
83     int64_t         first_pts;
84     pthread_mutex_t frame_lock;
85     pthread_cond_t  frame_wait_cond;
86     id              avf_delegate;
87
88     int             list_devices;
89     int             video_device_index;
90     enum AVPixelFormat pixel_format;
91
92     AVCaptureSession         *capture_session;
93     AVCaptureVideoDataOutput *video_output;
94     CMSampleBufferRef         current_frame;
95 } AVFContext;
96
97 static void lock_frames(AVFContext* ctx)
98 {
99     pthread_mutex_lock(&ctx->frame_lock);
100 }
101
102 static void unlock_frames(AVFContext* ctx)
103 {
104     pthread_mutex_unlock(&ctx->frame_lock);
105 }
106
107 /** FrameReciever class - delegate for AVCaptureSession
108  */
109 @interface AVFFrameReceiver : NSObject
110 {
111     AVFContext* _context;
112 }
113
114 - (id)initWithContext:(AVFContext*)context;
115
116 - (void)  captureOutput:(AVCaptureOutput *)captureOutput
117   didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
118          fromConnection:(AVCaptureConnection *)connection;
119
120 @end
121
122 @implementation AVFFrameReceiver
123
124 - (id)initWithContext:(AVFContext*)context
125 {
126     if (self = [super init]) {
127         _context = context;
128     }
129     return self;
130 }
131
132 - (void)  captureOutput:(AVCaptureOutput *)captureOutput
133   didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
134          fromConnection:(AVCaptureConnection *)connection
135 {
136     lock_frames(_context);
137
138     if (_context->current_frame != nil) {
139         CFRelease(_context->current_frame);
140     }
141
142     _context->current_frame = (CMSampleBufferRef)CFRetain(videoFrame);
143
144     pthread_cond_signal(&_context->frame_wait_cond);
145
146     unlock_frames(_context);
147
148     ++_context->frames_captured;
149 }
150
151 @end
152
153 static void destroy_context(AVFContext* ctx)
154 {
155     [ctx->capture_session stopRunning];
156
157     [ctx->capture_session release];
158     [ctx->video_output    release];
159     [ctx->avf_delegate    release];
160
161     ctx->capture_session = NULL;
162     ctx->video_output    = NULL;
163     ctx->avf_delegate    = NULL;
164
165     pthread_mutex_destroy(&ctx->frame_lock);
166     pthread_cond_destroy(&ctx->frame_wait_cond);
167
168     if (ctx->current_frame) {
169         CFRelease(ctx->current_frame);
170     }
171 }
172
173 static int avf_read_header(AVFormatContext *s)
174 {
175     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
176     AVFContext *ctx         = (AVFContext*)s->priv_data;
177     ctx->first_pts          = av_gettime();
178
179     pthread_mutex_init(&ctx->frame_lock, NULL);
180     pthread_cond_init(&ctx->frame_wait_cond, NULL);
181
182     // List devices if requested
183     if (ctx->list_devices) {
184         av_log(ctx, AV_LOG_INFO, "AVFoundation video devices:\n");
185         NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
186         for (AVCaptureDevice *device in devices) {
187             const char *name = [[device localizedName] UTF8String];
188             int index  = [devices indexOfObject:device];
189             av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
190         }
191         goto fail;
192     }
193
194     // Find capture device
195     AVCaptureDevice *video_device = nil;
196
197     // check for device index given in filename
198     if (ctx->video_device_index == -1) {
199         sscanf(s->filename, "%d", &ctx->video_device_index);
200     }
201
202     if (ctx->video_device_index >= 0) {
203         NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
204
205         if (ctx->video_device_index >= [devices count]) {
206             av_log(ctx, AV_LOG_ERROR, "Invalid device index\n");
207             goto fail;
208         }
209
210         video_device = [devices objectAtIndex:ctx->video_device_index];
211     } else if (strncmp(s->filename, "",        1) &&
212                strncmp(s->filename, "default", 7)) {
213         NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
214
215         for (AVCaptureDevice *device in devices) {
216             if (!strncmp(s->filename, [[device localizedName] UTF8String], strlen(s->filename))) {
217                 video_device = device;
218                 break;
219             }
220         }
221
222         if (!video_device) {
223             av_log(ctx, AV_LOG_ERROR, "Video device not found\n");
224             goto fail;
225         }
226     } else {
227         video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeMuxed];
228     }
229
230     // Video capture device not found, looking for AVMediaTypeVideo
231     if (!video_device) {
232         video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
233
234         if (!video_device) {
235             av_log(s, AV_LOG_ERROR, "No AV capture device found\n");
236             goto fail;
237         }
238     }
239
240     NSString* dev_display_name = [video_device localizedName];
241     av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [dev_display_name UTF8String]);
242
243     // Initialize capture session
244     ctx->capture_session = [[AVCaptureSession alloc] init];
245
246     NSError *error = nil;
247     AVCaptureDeviceInput* capture_dev_input = [[[AVCaptureDeviceInput alloc] initWithDevice:video_device error:&error] autorelease];
248
249     if (!capture_dev_input) {
250         av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
251                [[error localizedDescription] UTF8String]);
252         goto fail;
253     }
254
255     if (!capture_dev_input) {
256         av_log(s, AV_LOG_ERROR, "Failed to add AV capture input device to session: %s\n",
257                [[error localizedDescription] UTF8String]);
258         goto fail;
259     }
260
261     if ([ctx->capture_session canAddInput:capture_dev_input]) {
262         [ctx->capture_session addInput:capture_dev_input];
263     } else {
264         av_log(s, AV_LOG_ERROR, "can't add video input to capture session\n");
265         goto fail;
266     }
267
268     // Attaching output
269     ctx->video_output = [[AVCaptureVideoDataOutput alloc] init];
270
271     if (!ctx->video_output) {
272         av_log(s, AV_LOG_ERROR, "Failed to init AV video output\n");
273         goto fail;
274     }
275
276     // select pixel format
277     struct AVFPixelFormatSpec pxl_fmt_spec;
278     pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
279
280     for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
281         if (ctx->pixel_format == avf_pixel_formats[i].ff_id) {
282             pxl_fmt_spec = avf_pixel_formats[i];
283             break;
284         }
285     }
286
287     // check if selected pixel format is supported by AVFoundation
288     if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
289         av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by AVFoundation.\n",
290                av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
291         goto fail;
292     }
293
294     // check if the pixel format is available for this device
295     if ([[ctx->video_output availableVideoCVPixelFormatTypes] indexOfObject:[NSNumber numberWithInt:pxl_fmt_spec.avf_id]] == NSNotFound) {
296         av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by the input device.\n",
297                av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
298
299         pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
300
301         av_log(s, AV_LOG_ERROR, "Supported pixel formats:\n");
302         for (NSNumber *pxl_fmt in [ctx->video_output availableVideoCVPixelFormatTypes]) {
303             struct AVFPixelFormatSpec pxl_fmt_dummy;
304             pxl_fmt_dummy.ff_id = AV_PIX_FMT_NONE;
305             for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
306                 if ([pxl_fmt intValue] == avf_pixel_formats[i].avf_id) {
307                     pxl_fmt_dummy = avf_pixel_formats[i];
308                     break;
309                 }
310             }
311
312             if (pxl_fmt_dummy.ff_id != AV_PIX_FMT_NONE) {
313                 av_log(s, AV_LOG_ERROR, "  %s\n", av_get_pix_fmt_name(pxl_fmt_dummy.ff_id));
314
315                 // select first supported pixel format instead of user selected (or default) pixel format
316                 if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
317                     pxl_fmt_spec = pxl_fmt_dummy;
318                 }
319             }
320         }
321
322         // fail if there is no appropriate pixel format or print a warning about overriding the pixel format
323         if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
324             goto fail;
325         } else {
326             av_log(s, AV_LOG_WARNING, "Overriding selected pixel format to use %s instead.\n",
327                    av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
328         }
329     }
330
331
332     NSNumber     *pixel_format = [NSNumber numberWithUnsignedInt:pxl_fmt_spec.avf_id];
333     NSDictionary *capture_dict = [NSDictionary dictionaryWithObject:pixel_format
334                                                forKey:(id)kCVPixelBufferPixelFormatTypeKey];
335
336     [ctx->video_output setVideoSettings:capture_dict];
337     [ctx->video_output setAlwaysDiscardsLateVideoFrames:YES];
338
339     ctx->avf_delegate = [[AVFFrameReceiver alloc] initWithContext:ctx];
340
341     dispatch_queue_t queue = dispatch_queue_create("avf_queue", NULL);
342     [ctx->video_output setSampleBufferDelegate:ctx->avf_delegate queue:queue];
343     dispatch_release(queue);
344
345     if ([ctx->capture_session canAddOutput:ctx->video_output]) {
346         [ctx->capture_session addOutput:ctx->video_output];
347     } else {
348         av_log(s, AV_LOG_ERROR, "can't add video output to capture session\n");
349         goto fail;
350     }
351
352     [ctx->capture_session startRunning];
353
354     // Take stream info from the first frame.
355     while (ctx->frames_captured < 1) {
356         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
357     }
358
359     lock_frames(ctx);
360
361     AVStream* stream = avformat_new_stream(s, NULL);
362
363     if (!stream) {
364         goto fail;
365     }
366
367     avpriv_set_pts_info(stream, 64, 1, avf_time_base);
368
369     CVImageBufferRef image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
370     CGSize image_buffer_size      = CVImageBufferGetEncodedSize(image_buffer);
371
372     stream->codec->codec_id   = AV_CODEC_ID_RAWVIDEO;
373     stream->codec->codec_type = AVMEDIA_TYPE_VIDEO;
374     stream->codec->width      = (int)image_buffer_size.width;
375     stream->codec->height     = (int)image_buffer_size.height;
376     stream->codec->pix_fmt    = pxl_fmt_spec.ff_id;
377
378     CFRelease(ctx->current_frame);
379     ctx->current_frame = nil;
380
381     unlock_frames(ctx);
382     [pool release];
383     return 0;
384
385 fail:
386     [pool release];
387     destroy_context(ctx);
388     return AVERROR(EIO);
389 }
390
391 static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
392 {
393     AVFContext* ctx = (AVFContext*)s->priv_data;
394
395     do {
396         lock_frames(ctx);
397
398         CVImageBufferRef image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
399
400         if (ctx->current_frame != nil) {
401             if (av_new_packet(pkt, (int)CVPixelBufferGetDataSize(image_buffer)) < 0) {
402                 return AVERROR(EIO);
403             }
404
405             pkt->pts = pkt->dts = av_rescale_q(av_gettime() - ctx->first_pts,
406                                                AV_TIME_BASE_Q,
407                                                avf_time_base_q);
408             pkt->stream_index  = 0;
409             pkt->flags        |= AV_PKT_FLAG_KEY;
410
411             CVPixelBufferLockBaseAddress(image_buffer, 0);
412
413             void* data = CVPixelBufferGetBaseAddress(image_buffer);
414             memcpy(pkt->data, data, pkt->size);
415
416             CVPixelBufferUnlockBaseAddress(image_buffer, 0);
417             CFRelease(ctx->current_frame);
418             ctx->current_frame = nil;
419         } else {
420             pkt->data = NULL;
421             pthread_cond_wait(&ctx->frame_wait_cond, &ctx->frame_lock);
422         }
423
424         unlock_frames(ctx);
425     } while (!pkt->data);
426
427     return 0;
428 }
429
430 static int avf_close(AVFormatContext *s)
431 {
432     AVFContext* ctx = (AVFContext*)s->priv_data;
433     destroy_context(ctx);
434     return 0;
435 }
436
437 static const AVOption options[] = {
438     { "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 },
439     { "list_devices", "list available devices", offsetof(AVFContext, list_devices), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
440     { "true", "", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
441     { "false", "", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
442     { "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 },
443     { "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},
444     { NULL },
445 };
446
447 static const AVClass avf_class = {
448     .class_name = "AVFoundation input device",
449     .item_name  = av_default_item_name,
450     .option     = options,
451     .version    = LIBAVUTIL_VERSION_INT,
452 };
453
454 AVInputFormat ff_avfoundation_demuxer = {
455     .name           = "avfoundation",
456     .long_name      = NULL_IF_CONFIG_SMALL("AVFoundation input device"),
457     .priv_data_size = sizeof(AVFContext),
458     .read_header    = avf_read_header,
459     .read_packet    = avf_read_packet,
460     .read_close     = avf_close,
461     .flags          = AVFMT_NOFILE,
462     .priv_class     = &avf_class,
463 };