avfoundation.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. * @file
  23. * AVFoundation input device
  24. * @author Thilo Borgmann <thilo.borgmann@mail.de>
  25. */
  26. #import <AVFoundation/AVFoundation.h>
  27. #include <pthread.h>
  28. #include "libavutil/pixdesc.h"
  29. #include "libavutil/opt.h"
  30. #include "libavformat/internal.h"
  31. #include "libavutil/internal.h"
  32. #include "libavutil/time.h"
  33. #include "avdevice.h"
  34. static const int avf_time_base = 100;
  35. static const AVRational avf_time_base_q = {
  36. .num = 1,
  37. .den = avf_time_base
  38. };
  39. typedef struct
  40. {
  41. AVClass* class;
  42. float frame_rate;
  43. int frames_captured;
  44. int64_t first_pts;
  45. pthread_mutex_t frame_lock;
  46. pthread_cond_t frame_wait_cond;
  47. id avf_delegate;
  48. int list_devices;
  49. int video_device_index;
  50. AVCaptureSession *capture_session;
  51. AVCaptureVideoDataOutput *video_output;
  52. CMSampleBufferRef current_frame;
  53. } AVFContext;
  54. static void lock_frames(AVFContext* ctx)
  55. {
  56. pthread_mutex_lock(&ctx->frame_lock);
  57. }
  58. static void unlock_frames(AVFContext* ctx)
  59. {
  60. pthread_mutex_unlock(&ctx->frame_lock);
  61. }
  62. /** FrameReciever class - delegate for AVCaptureSession
  63. */
  64. @interface AVFFrameReceiver : NSObject
  65. {
  66. AVFContext* _context;
  67. }
  68. - (id)initWithContext:(AVFContext*)context;
  69. - (void) captureOutput:(AVCaptureOutput *)captureOutput
  70. didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
  71. fromConnection:(AVCaptureConnection *)connection;
  72. @end
  73. @implementation AVFFrameReceiver
  74. - (id)initWithContext:(AVFContext*)context
  75. {
  76. if (self = [super init]) {
  77. _context = context;
  78. }
  79. return self;
  80. }
  81. - (void) captureOutput:(AVCaptureOutput *)captureOutput
  82. didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
  83. fromConnection:(AVCaptureConnection *)connection
  84. {
  85. lock_frames(_context);
  86. if (_context->current_frame != nil) {
  87. CFRelease(_context->current_frame);
  88. }
  89. _context->current_frame = (CMSampleBufferRef)CFRetain(videoFrame);
  90. pthread_cond_signal(&_context->frame_wait_cond);
  91. unlock_frames(_context);
  92. ++_context->frames_captured;
  93. }
  94. @end
  95. static void destroy_context(AVFContext* ctx)
  96. {
  97. [ctx->capture_session stopRunning];
  98. [ctx->capture_session release];
  99. [ctx->video_output release];
  100. [ctx->avf_delegate release];
  101. ctx->capture_session = NULL;
  102. ctx->video_output = NULL;
  103. ctx->avf_delegate = NULL;
  104. pthread_mutex_destroy(&ctx->frame_lock);
  105. pthread_cond_destroy(&ctx->frame_wait_cond);
  106. if (ctx->current_frame) {
  107. CFRelease(ctx->current_frame);
  108. }
  109. }
  110. static int avf_read_header(AVFormatContext *s)
  111. {
  112. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  113. AVFContext *ctx = (AVFContext*)s->priv_data;
  114. ctx->first_pts = av_gettime();
  115. pthread_mutex_init(&ctx->frame_lock, NULL);
  116. pthread_cond_init(&ctx->frame_wait_cond, NULL);
  117. // List devices if requested
  118. if (ctx->list_devices) {
  119. av_log(ctx, AV_LOG_INFO, "AVFoundation video devices:\n");
  120. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  121. for (AVCaptureDevice *device in devices) {
  122. const char *name = [[device localizedName] UTF8String];
  123. int index = [devices indexOfObject:device];
  124. av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
  125. }
  126. goto fail;
  127. }
  128. // Find capture device
  129. AVCaptureDevice *video_device = nil;
  130. // check for device index given in filename
  131. if (ctx->video_device_index == -1) {
  132. sscanf(s->filename, "%d", &ctx->video_device_index);
  133. }
  134. if (ctx->video_device_index >= 0) {
  135. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  136. if (ctx->video_device_index >= [devices count]) {
  137. av_log(ctx, AV_LOG_ERROR, "Invalid device index\n");
  138. goto fail;
  139. }
  140. video_device = [devices objectAtIndex:ctx->video_device_index];
  141. } else if (strncmp(s->filename, "", 1) &&
  142. strncmp(s->filename, "default", 7)) {
  143. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  144. for (AVCaptureDevice *device in devices) {
  145. if (!strncmp(s->filename, [[device localizedName] UTF8String], strlen(s->filename))) {
  146. video_device = device;
  147. break;
  148. }
  149. }
  150. if (!video_device) {
  151. av_log(ctx, AV_LOG_ERROR, "Video device not found\n");
  152. goto fail;
  153. }
  154. } else {
  155. video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeMuxed];
  156. }
  157. // Video capture device not found, looking for AVMediaTypeVideo
  158. if (!video_device) {
  159. video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  160. if (!video_device) {
  161. av_log(s, AV_LOG_ERROR, "No AV capture device found\n");
  162. goto fail;
  163. }
  164. }
  165. NSString* dev_display_name = [video_device localizedName];
  166. av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [dev_display_name UTF8String]);
  167. // Initialize capture session
  168. ctx->capture_session = [[AVCaptureSession alloc] init];
  169. NSError *error = nil;
  170. AVCaptureDeviceInput* capture_dev_input = [[[AVCaptureDeviceInput alloc] initWithDevice:video_device error:&error] autorelease];
  171. if (!capture_dev_input) {
  172. av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
  173. [[error localizedDescription] UTF8String]);
  174. goto fail;
  175. }
  176. if (!capture_dev_input) {
  177. av_log(s, AV_LOG_ERROR, "Failed to add AV capture input device to session: %s\n",
  178. [[error localizedDescription] UTF8String]);
  179. goto fail;
  180. }
  181. if ([ctx->capture_session canAddInput:capture_dev_input]) {
  182. [ctx->capture_session addInput:capture_dev_input];
  183. } else {
  184. av_log(s, AV_LOG_ERROR, "can't add video input to capture session\n");
  185. goto fail;
  186. }
  187. // Attaching output
  188. // FIXME: Allow for a user defined pixel format
  189. ctx->video_output = [[AVCaptureVideoDataOutput alloc] init];
  190. if (!ctx->video_output) {
  191. av_log(s, AV_LOG_ERROR, "Failed to init AV video output\n");
  192. goto fail;
  193. }
  194. NSNumber *pixel_format = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_24RGB];
  195. NSDictionary *capture_dict = [NSDictionary dictionaryWithObject:pixel_format
  196. forKey:(id)kCVPixelBufferPixelFormatTypeKey];
  197. [ctx->video_output setVideoSettings:capture_dict];
  198. [ctx->video_output setAlwaysDiscardsLateVideoFrames:YES];
  199. ctx->avf_delegate = [[AVFFrameReceiver alloc] initWithContext:ctx];
  200. dispatch_queue_t queue = dispatch_queue_create("avf_queue", NULL);
  201. [ctx->video_output setSampleBufferDelegate:ctx->avf_delegate queue:queue];
  202. dispatch_release(queue);
  203. if ([ctx->capture_session canAddOutput:ctx->video_output]) {
  204. [ctx->capture_session addOutput:ctx->video_output];
  205. } else {
  206. av_log(s, AV_LOG_ERROR, "can't add video output to capture session\n");
  207. goto fail;
  208. }
  209. [ctx->capture_session startRunning];
  210. // Take stream info from the first frame.
  211. while (ctx->frames_captured < 1) {
  212. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
  213. }
  214. lock_frames(ctx);
  215. AVStream* stream = avformat_new_stream(s, NULL);
  216. if (!stream) {
  217. goto fail;
  218. }
  219. avpriv_set_pts_info(stream, 64, 1, avf_time_base);
  220. CVImageBufferRef image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
  221. CGSize image_buffer_size = CVImageBufferGetEncodedSize(image_buffer);
  222. stream->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
  223. stream->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  224. stream->codec->width = (int)image_buffer_size.width;
  225. stream->codec->height = (int)image_buffer_size.height;
  226. stream->codec->pix_fmt = AV_PIX_FMT_RGB24;
  227. CFRelease(ctx->current_frame);
  228. ctx->current_frame = nil;
  229. unlock_frames(ctx);
  230. [pool release];
  231. return 0;
  232. fail:
  233. [pool release];
  234. destroy_context(ctx);
  235. return AVERROR(EIO);
  236. }
  237. static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
  238. {
  239. AVFContext* ctx = (AVFContext*)s->priv_data;
  240. do {
  241. lock_frames(ctx);
  242. CVImageBufferRef image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
  243. if (ctx->current_frame != nil) {
  244. if (av_new_packet(pkt, (int)CVPixelBufferGetDataSize(image_buffer)) < 0) {
  245. return AVERROR(EIO);
  246. }
  247. pkt->pts = pkt->dts = av_rescale_q(av_gettime() - ctx->first_pts,
  248. AV_TIME_BASE_Q,
  249. avf_time_base_q);
  250. pkt->stream_index = 0;
  251. pkt->flags |= AV_PKT_FLAG_KEY;
  252. CVPixelBufferLockBaseAddress(image_buffer, 0);
  253. void* data = CVPixelBufferGetBaseAddress(image_buffer);
  254. memcpy(pkt->data, data, pkt->size);
  255. CVPixelBufferUnlockBaseAddress(image_buffer, 0);
  256. CFRelease(ctx->current_frame);
  257. ctx->current_frame = nil;
  258. } else {
  259. pkt->data = NULL;
  260. pthread_cond_wait(&ctx->frame_wait_cond, &ctx->frame_lock);
  261. }
  262. unlock_frames(ctx);
  263. } while (!pkt->data);
  264. return 0;
  265. }
  266. static int avf_close(AVFormatContext *s)
  267. {
  268. AVFContext* ctx = (AVFContext*)s->priv_data;
  269. destroy_context(ctx);
  270. return 0;
  271. }
  272. static const AVOption options[] = {
  273. { "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 },
  274. { "list_devices", "list available devices", offsetof(AVFContext, list_devices), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
  275. { "true", "", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
  276. { "false", "", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
  277. { "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 },
  278. { NULL },
  279. };
  280. static const AVClass avf_class = {
  281. .class_name = "AVFoundation input device",
  282. .item_name = av_default_item_name,
  283. .option = options,
  284. .version = LIBAVUTIL_VERSION_INT,
  285. };
  286. AVInputFormat ff_avfoundation_demuxer = {
  287. .name = "avfoundation",
  288. .long_name = NULL_IF_CONFIG_SMALL("AVFoundation input device"),
  289. .priv_data_size = sizeof(AVFContext),
  290. .read_header = avf_read_header,
  291. .read_packet = avf_read_packet,
  292. .read_close = avf_close,
  293. .flags = AVFMT_NOFILE,
  294. .priv_class = &avf_class,
  295. };