avfoundation.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. struct AVFPixelFormatSpec {
  40. enum AVPixelFormat ff_id;
  41. OSType avf_id;
  42. };
  43. static const struct AVFPixelFormatSpec avf_pixel_formats[] = {
  44. { AV_PIX_FMT_MONOBLACK, kCVPixelFormatType_1Monochrome },
  45. { AV_PIX_FMT_RGB555BE, kCVPixelFormatType_16BE555 },
  46. { AV_PIX_FMT_RGB555LE, kCVPixelFormatType_16LE555 },
  47. { AV_PIX_FMT_RGB565BE, kCVPixelFormatType_16BE565 },
  48. { AV_PIX_FMT_RGB565LE, kCVPixelFormatType_16LE565 },
  49. { AV_PIX_FMT_RGB24, kCVPixelFormatType_24RGB },
  50. { AV_PIX_FMT_BGR24, kCVPixelFormatType_24BGR },
  51. { AV_PIX_FMT_0RGB, kCVPixelFormatType_32ARGB },
  52. { AV_PIX_FMT_BGR0, kCVPixelFormatType_32BGRA },
  53. { AV_PIX_FMT_0BGR, kCVPixelFormatType_32ABGR },
  54. { AV_PIX_FMT_RGB0, kCVPixelFormatType_32RGBA },
  55. { AV_PIX_FMT_BGR48BE, kCVPixelFormatType_48RGB },
  56. { AV_PIX_FMT_UYVY422, kCVPixelFormatType_422YpCbCr8 },
  57. { AV_PIX_FMT_YUVA444P, kCVPixelFormatType_4444YpCbCrA8R },
  58. { AV_PIX_FMT_YUVA444P16LE, kCVPixelFormatType_4444AYpCbCr16 },
  59. { AV_PIX_FMT_YUV444P, kCVPixelFormatType_444YpCbCr8 },
  60. { AV_PIX_FMT_YUV422P16, kCVPixelFormatType_422YpCbCr16 },
  61. { AV_PIX_FMT_YUV422P10, kCVPixelFormatType_422YpCbCr10 },
  62. { AV_PIX_FMT_YUV444P10, kCVPixelFormatType_444YpCbCr10 },
  63. { AV_PIX_FMT_YUV420P, kCVPixelFormatType_420YpCbCr8Planar },
  64. { AV_PIX_FMT_NV12, kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange },
  65. { AV_PIX_FMT_YUYV422, kCVPixelFormatType_422YpCbCr8_yuvs },
  66. #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
  67. { AV_PIX_FMT_GRAY8, kCVPixelFormatType_OneComponent8 },
  68. #endif
  69. { AV_PIX_FMT_NONE, 0 }
  70. };
  71. typedef struct
  72. {
  73. AVClass* class;
  74. float frame_rate;
  75. int frames_captured;
  76. int64_t first_pts;
  77. pthread_mutex_t frame_lock;
  78. pthread_cond_t frame_wait_cond;
  79. id avf_delegate;
  80. int list_devices;
  81. int video_device_index;
  82. enum AVPixelFormat pixel_format;
  83. AVCaptureSession *capture_session;
  84. AVCaptureVideoDataOutput *video_output;
  85. CMSampleBufferRef current_frame;
  86. } AVFContext;
  87. static void lock_frames(AVFContext* ctx)
  88. {
  89. pthread_mutex_lock(&ctx->frame_lock);
  90. }
  91. static void unlock_frames(AVFContext* ctx)
  92. {
  93. pthread_mutex_unlock(&ctx->frame_lock);
  94. }
  95. /** FrameReciever class - delegate for AVCaptureSession
  96. */
  97. @interface AVFFrameReceiver : NSObject
  98. {
  99. AVFContext* _context;
  100. }
  101. - (id)initWithContext:(AVFContext*)context;
  102. - (void) captureOutput:(AVCaptureOutput *)captureOutput
  103. didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
  104. fromConnection:(AVCaptureConnection *)connection;
  105. @end
  106. @implementation AVFFrameReceiver
  107. - (id)initWithContext:(AVFContext*)context
  108. {
  109. if (self = [super init]) {
  110. _context = context;
  111. }
  112. return self;
  113. }
  114. - (void) captureOutput:(AVCaptureOutput *)captureOutput
  115. didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
  116. fromConnection:(AVCaptureConnection *)connection
  117. {
  118. lock_frames(_context);
  119. if (_context->current_frame != nil) {
  120. CFRelease(_context->current_frame);
  121. }
  122. _context->current_frame = (CMSampleBufferRef)CFRetain(videoFrame);
  123. pthread_cond_signal(&_context->frame_wait_cond);
  124. unlock_frames(_context);
  125. ++_context->frames_captured;
  126. }
  127. @end
  128. static void destroy_context(AVFContext* ctx)
  129. {
  130. [ctx->capture_session stopRunning];
  131. [ctx->capture_session release];
  132. [ctx->video_output release];
  133. [ctx->avf_delegate release];
  134. ctx->capture_session = NULL;
  135. ctx->video_output = NULL;
  136. ctx->avf_delegate = NULL;
  137. pthread_mutex_destroy(&ctx->frame_lock);
  138. pthread_cond_destroy(&ctx->frame_wait_cond);
  139. if (ctx->current_frame) {
  140. CFRelease(ctx->current_frame);
  141. }
  142. }
  143. static int avf_read_header(AVFormatContext *s)
  144. {
  145. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  146. AVFContext *ctx = (AVFContext*)s->priv_data;
  147. ctx->first_pts = av_gettime();
  148. pthread_mutex_init(&ctx->frame_lock, NULL);
  149. pthread_cond_init(&ctx->frame_wait_cond, NULL);
  150. // List devices if requested
  151. if (ctx->list_devices) {
  152. av_log(ctx, AV_LOG_INFO, "AVFoundation video devices:\n");
  153. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  154. for (AVCaptureDevice *device in devices) {
  155. const char *name = [[device localizedName] UTF8String];
  156. int index = [devices indexOfObject:device];
  157. av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
  158. }
  159. goto fail;
  160. }
  161. // Find capture device
  162. AVCaptureDevice *video_device = nil;
  163. // check for device index given in filename
  164. if (ctx->video_device_index == -1) {
  165. sscanf(s->filename, "%d", &ctx->video_device_index);
  166. }
  167. if (ctx->video_device_index >= 0) {
  168. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  169. if (ctx->video_device_index >= [devices count]) {
  170. av_log(ctx, AV_LOG_ERROR, "Invalid device index\n");
  171. goto fail;
  172. }
  173. video_device = [devices objectAtIndex:ctx->video_device_index];
  174. } else if (strncmp(s->filename, "", 1) &&
  175. strncmp(s->filename, "default", 7)) {
  176. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  177. for (AVCaptureDevice *device in devices) {
  178. if (!strncmp(s->filename, [[device localizedName] UTF8String], strlen(s->filename))) {
  179. video_device = device;
  180. break;
  181. }
  182. }
  183. if (!video_device) {
  184. av_log(ctx, AV_LOG_ERROR, "Video device not found\n");
  185. goto fail;
  186. }
  187. } else {
  188. video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeMuxed];
  189. }
  190. // Video capture device not found, looking for AVMediaTypeVideo
  191. if (!video_device) {
  192. video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  193. if (!video_device) {
  194. av_log(s, AV_LOG_ERROR, "No AV capture device found\n");
  195. goto fail;
  196. }
  197. }
  198. NSString* dev_display_name = [video_device localizedName];
  199. av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [dev_display_name UTF8String]);
  200. // Initialize capture session
  201. ctx->capture_session = [[AVCaptureSession alloc] init];
  202. NSError *error = nil;
  203. AVCaptureDeviceInput* capture_dev_input = [[[AVCaptureDeviceInput alloc] initWithDevice:video_device error:&error] autorelease];
  204. if (!capture_dev_input) {
  205. av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
  206. [[error localizedDescription] UTF8String]);
  207. goto fail;
  208. }
  209. if (!capture_dev_input) {
  210. av_log(s, AV_LOG_ERROR, "Failed to add AV capture input device to session: %s\n",
  211. [[error localizedDescription] UTF8String]);
  212. goto fail;
  213. }
  214. if ([ctx->capture_session canAddInput:capture_dev_input]) {
  215. [ctx->capture_session addInput:capture_dev_input];
  216. } else {
  217. av_log(s, AV_LOG_ERROR, "can't add video input to capture session\n");
  218. goto fail;
  219. }
  220. // Attaching output
  221. ctx->video_output = [[AVCaptureVideoDataOutput alloc] init];
  222. if (!ctx->video_output) {
  223. av_log(s, AV_LOG_ERROR, "Failed to init AV video output\n");
  224. goto fail;
  225. }
  226. // select pixel format
  227. struct AVFPixelFormatSpec pxl_fmt_spec;
  228. pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
  229. for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
  230. if (ctx->pixel_format == avf_pixel_formats[i].ff_id) {
  231. pxl_fmt_spec = avf_pixel_formats[i];
  232. break;
  233. }
  234. }
  235. // check if selected pixel format is supported by AVFoundation
  236. if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
  237. av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by AVFoundation.\n",
  238. av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
  239. goto fail;
  240. }
  241. // check if the pixel format is available for this device
  242. if ([[ctx->video_output availableVideoCVPixelFormatTypes] indexOfObject:[NSNumber numberWithInt:pxl_fmt_spec.avf_id]] == NSNotFound) {
  243. av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by the input device.\n",
  244. av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
  245. pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
  246. av_log(s, AV_LOG_ERROR, "Supported pixel formats:\n");
  247. for (NSNumber *pxl_fmt in [ctx->video_output availableVideoCVPixelFormatTypes]) {
  248. struct AVFPixelFormatSpec pxl_fmt_dummy;
  249. pxl_fmt_dummy.ff_id = AV_PIX_FMT_NONE;
  250. for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
  251. if ([pxl_fmt intValue] == avf_pixel_formats[i].avf_id) {
  252. pxl_fmt_dummy = avf_pixel_formats[i];
  253. break;
  254. }
  255. }
  256. if (pxl_fmt_dummy.ff_id != AV_PIX_FMT_NONE) {
  257. av_log(s, AV_LOG_ERROR, " %s\n", av_get_pix_fmt_name(pxl_fmt_dummy.ff_id));
  258. // select first supported pixel format instead of user selected (or default) pixel format
  259. if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
  260. pxl_fmt_spec = pxl_fmt_dummy;
  261. }
  262. }
  263. }
  264. // fail if there is no appropriate pixel format or print a warning about overriding the pixel format
  265. if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
  266. goto fail;
  267. } else {
  268. av_log(s, AV_LOG_WARNING, "Overriding selected pixel format to use %s instead.\n",
  269. av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
  270. }
  271. }
  272. NSNumber *pixel_format = [NSNumber numberWithUnsignedInt:pxl_fmt_spec.avf_id];
  273. NSDictionary *capture_dict = [NSDictionary dictionaryWithObject:pixel_format
  274. forKey:(id)kCVPixelBufferPixelFormatTypeKey];
  275. [ctx->video_output setVideoSettings:capture_dict];
  276. [ctx->video_output setAlwaysDiscardsLateVideoFrames:YES];
  277. ctx->avf_delegate = [[AVFFrameReceiver alloc] initWithContext:ctx];
  278. dispatch_queue_t queue = dispatch_queue_create("avf_queue", NULL);
  279. [ctx->video_output setSampleBufferDelegate:ctx->avf_delegate queue:queue];
  280. dispatch_release(queue);
  281. if ([ctx->capture_session canAddOutput:ctx->video_output]) {
  282. [ctx->capture_session addOutput:ctx->video_output];
  283. } else {
  284. av_log(s, AV_LOG_ERROR, "can't add video output to capture session\n");
  285. goto fail;
  286. }
  287. [ctx->capture_session startRunning];
  288. // Take stream info from the first frame.
  289. while (ctx->frames_captured < 1) {
  290. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
  291. }
  292. lock_frames(ctx);
  293. AVStream* stream = avformat_new_stream(s, NULL);
  294. if (!stream) {
  295. goto fail;
  296. }
  297. avpriv_set_pts_info(stream, 64, 1, avf_time_base);
  298. CVImageBufferRef image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
  299. CGSize image_buffer_size = CVImageBufferGetEncodedSize(image_buffer);
  300. stream->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
  301. stream->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  302. stream->codec->width = (int)image_buffer_size.width;
  303. stream->codec->height = (int)image_buffer_size.height;
  304. stream->codec->pix_fmt = pxl_fmt_spec.ff_id;
  305. CFRelease(ctx->current_frame);
  306. ctx->current_frame = nil;
  307. unlock_frames(ctx);
  308. [pool release];
  309. return 0;
  310. fail:
  311. [pool release];
  312. destroy_context(ctx);
  313. return AVERROR(EIO);
  314. }
  315. static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
  316. {
  317. AVFContext* ctx = (AVFContext*)s->priv_data;
  318. do {
  319. lock_frames(ctx);
  320. CVImageBufferRef image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
  321. if (ctx->current_frame != nil) {
  322. if (av_new_packet(pkt, (int)CVPixelBufferGetDataSize(image_buffer)) < 0) {
  323. return AVERROR(EIO);
  324. }
  325. pkt->pts = pkt->dts = av_rescale_q(av_gettime() - ctx->first_pts,
  326. AV_TIME_BASE_Q,
  327. avf_time_base_q);
  328. pkt->stream_index = 0;
  329. pkt->flags |= AV_PKT_FLAG_KEY;
  330. CVPixelBufferLockBaseAddress(image_buffer, 0);
  331. void* data = CVPixelBufferGetBaseAddress(image_buffer);
  332. memcpy(pkt->data, data, pkt->size);
  333. CVPixelBufferUnlockBaseAddress(image_buffer, 0);
  334. CFRelease(ctx->current_frame);
  335. ctx->current_frame = nil;
  336. } else {
  337. pkt->data = NULL;
  338. pthread_cond_wait(&ctx->frame_wait_cond, &ctx->frame_lock);
  339. }
  340. unlock_frames(ctx);
  341. } while (!pkt->data);
  342. return 0;
  343. }
  344. static int avf_close(AVFormatContext *s)
  345. {
  346. AVFContext* ctx = (AVFContext*)s->priv_data;
  347. destroy_context(ctx);
  348. return 0;
  349. }
  350. static const AVOption options[] = {
  351. { "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 },
  352. { "list_devices", "list available devices", offsetof(AVFContext, list_devices), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
  353. { "true", "", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
  354. { "false", "", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
  355. { "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 },
  356. { "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},
  357. { NULL },
  358. };
  359. static const AVClass avf_class = {
  360. .class_name = "AVFoundation input device",
  361. .item_name = av_default_item_name,
  362. .option = options,
  363. .version = LIBAVUTIL_VERSION_INT,
  364. .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
  365. };
  366. AVInputFormat ff_avfoundation_demuxer = {
  367. .name = "avfoundation",
  368. .long_name = NULL_IF_CONFIG_SMALL("AVFoundation input device"),
  369. .priv_data_size = sizeof(AVFContext),
  370. .read_header = avf_read_header,
  371. .read_packet = avf_read_packet,
  372. .read_close = avf_close,
  373. .flags = AVFMT_NOFILE,
  374. .priv_class = &avf_class,
  375. };