You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

464 lines
16KB

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