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.

802 lines
27KB

  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 = 1000000;
  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. int audio_frames_captured;
  77. int64_t first_pts;
  78. int64_t first_audio_pts;
  79. pthread_mutex_t frame_lock;
  80. pthread_cond_t frame_wait_cond;
  81. id avf_delegate;
  82. id avf_audio_delegate;
  83. int list_devices;
  84. int video_device_index;
  85. int video_stream_index;
  86. int audio_device_index;
  87. int audio_stream_index;
  88. char *video_filename;
  89. char *audio_filename;
  90. int audio_channels;
  91. int audio_bits_per_sample;
  92. int audio_float;
  93. int audio_be;
  94. int audio_signed_integer;
  95. int audio_packed;
  96. int audio_non_interleaved;
  97. int32_t *audio_buffer;
  98. int audio_buffer_size;
  99. enum AVPixelFormat pixel_format;
  100. AVCaptureSession *capture_session;
  101. AVCaptureVideoDataOutput *video_output;
  102. AVCaptureAudioDataOutput *audio_output;
  103. CMSampleBufferRef current_frame;
  104. CMSampleBufferRef current_audio_frame;
  105. } AVFContext;
  106. static void lock_frames(AVFContext* ctx)
  107. {
  108. pthread_mutex_lock(&ctx->frame_lock);
  109. }
  110. static void unlock_frames(AVFContext* ctx)
  111. {
  112. pthread_mutex_unlock(&ctx->frame_lock);
  113. }
  114. /** FrameReciever class - delegate for AVCaptureSession
  115. */
  116. @interface AVFFrameReceiver : NSObject
  117. {
  118. AVFContext* _context;
  119. }
  120. - (id)initWithContext:(AVFContext*)context;
  121. - (void) captureOutput:(AVCaptureOutput *)captureOutput
  122. didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
  123. fromConnection:(AVCaptureConnection *)connection;
  124. @end
  125. @implementation AVFFrameReceiver
  126. - (id)initWithContext:(AVFContext*)context
  127. {
  128. if (self = [super init]) {
  129. _context = context;
  130. }
  131. return self;
  132. }
  133. - (void) captureOutput:(AVCaptureOutput *)captureOutput
  134. didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
  135. fromConnection:(AVCaptureConnection *)connection
  136. {
  137. lock_frames(_context);
  138. if (_context->current_frame != nil) {
  139. CFRelease(_context->current_frame);
  140. }
  141. _context->current_frame = (CMSampleBufferRef)CFRetain(videoFrame);
  142. pthread_cond_signal(&_context->frame_wait_cond);
  143. unlock_frames(_context);
  144. ++_context->frames_captured;
  145. }
  146. @end
  147. /** AudioReciever class - delegate for AVCaptureSession
  148. */
  149. @interface AVFAudioReceiver : NSObject
  150. {
  151. AVFContext* _context;
  152. }
  153. - (id)initWithContext:(AVFContext*)context;
  154. - (void) captureOutput:(AVCaptureOutput *)captureOutput
  155. didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
  156. fromConnection:(AVCaptureConnection *)connection;
  157. @end
  158. @implementation AVFAudioReceiver
  159. - (id)initWithContext:(AVFContext*)context
  160. {
  161. if (self = [super init]) {
  162. _context = context;
  163. }
  164. return self;
  165. }
  166. - (void) captureOutput:(AVCaptureOutput *)captureOutput
  167. didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
  168. fromConnection:(AVCaptureConnection *)connection
  169. {
  170. lock_frames(_context);
  171. if (_context->current_audio_frame != nil) {
  172. CFRelease(_context->current_audio_frame);
  173. }
  174. _context->current_audio_frame = (CMSampleBufferRef)CFRetain(audioFrame);
  175. pthread_cond_signal(&_context->frame_wait_cond);
  176. unlock_frames(_context);
  177. ++_context->audio_frames_captured;
  178. }
  179. @end
  180. static void destroy_context(AVFContext* ctx)
  181. {
  182. [ctx->capture_session stopRunning];
  183. [ctx->capture_session release];
  184. [ctx->video_output release];
  185. [ctx->audio_output release];
  186. [ctx->avf_delegate release];
  187. [ctx->avf_audio_delegate release];
  188. ctx->capture_session = NULL;
  189. ctx->video_output = NULL;
  190. ctx->audio_output = NULL;
  191. ctx->avf_delegate = NULL;
  192. ctx->avf_audio_delegate = NULL;
  193. av_freep(&ctx->audio_buffer);
  194. pthread_mutex_destroy(&ctx->frame_lock);
  195. pthread_cond_destroy(&ctx->frame_wait_cond);
  196. if (ctx->current_frame) {
  197. CFRelease(ctx->current_frame);
  198. }
  199. }
  200. static void parse_device_name(AVFormatContext *s)
  201. {
  202. AVFContext *ctx = (AVFContext*)s->priv_data;
  203. char *tmp = av_strdup(s->filename);
  204. if (tmp[0] != ':') {
  205. ctx->video_filename = strtok(tmp, ":");
  206. ctx->audio_filename = strtok(NULL, ":");
  207. } else {
  208. ctx->audio_filename = strtok(tmp, ":");
  209. }
  210. }
  211. static int add_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
  212. {
  213. AVFContext *ctx = (AVFContext*)s->priv_data;
  214. NSError *error = nil;
  215. AVCaptureDeviceInput* capture_dev_input = [[[AVCaptureDeviceInput alloc] initWithDevice:video_device error:&error] autorelease];
  216. if (!capture_dev_input) {
  217. av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
  218. [[error localizedDescription] UTF8String]);
  219. return 1;
  220. }
  221. if ([ctx->capture_session canAddInput:capture_dev_input]) {
  222. [ctx->capture_session addInput:capture_dev_input];
  223. } else {
  224. av_log(s, AV_LOG_ERROR, "can't add video input to capture session\n");
  225. return 1;
  226. }
  227. // Attaching output
  228. ctx->video_output = [[AVCaptureVideoDataOutput alloc] init];
  229. if (!ctx->video_output) {
  230. av_log(s, AV_LOG_ERROR, "Failed to init AV video output\n");
  231. return 1;
  232. }
  233. // select pixel format
  234. struct AVFPixelFormatSpec pxl_fmt_spec;
  235. pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
  236. for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
  237. if (ctx->pixel_format == avf_pixel_formats[i].ff_id) {
  238. pxl_fmt_spec = avf_pixel_formats[i];
  239. break;
  240. }
  241. }
  242. // check if selected pixel format is supported by AVFoundation
  243. if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
  244. av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by AVFoundation.\n",
  245. av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
  246. return 1;
  247. }
  248. // check if the pixel format is available for this device
  249. if ([[ctx->video_output availableVideoCVPixelFormatTypes] indexOfObject:[NSNumber numberWithInt:pxl_fmt_spec.avf_id]] == NSNotFound) {
  250. av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by the input device.\n",
  251. av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
  252. pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
  253. av_log(s, AV_LOG_ERROR, "Supported pixel formats:\n");
  254. for (NSNumber *pxl_fmt in [ctx->video_output availableVideoCVPixelFormatTypes]) {
  255. struct AVFPixelFormatSpec pxl_fmt_dummy;
  256. pxl_fmt_dummy.ff_id = AV_PIX_FMT_NONE;
  257. for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
  258. if ([pxl_fmt intValue] == avf_pixel_formats[i].avf_id) {
  259. pxl_fmt_dummy = avf_pixel_formats[i];
  260. break;
  261. }
  262. }
  263. if (pxl_fmt_dummy.ff_id != AV_PIX_FMT_NONE) {
  264. av_log(s, AV_LOG_ERROR, " %s\n", av_get_pix_fmt_name(pxl_fmt_dummy.ff_id));
  265. // select first supported pixel format instead of user selected (or default) pixel format
  266. if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
  267. pxl_fmt_spec = pxl_fmt_dummy;
  268. }
  269. }
  270. }
  271. // fail if there is no appropriate pixel format or print a warning about overriding the pixel format
  272. if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
  273. return 1;
  274. } else {
  275. av_log(s, AV_LOG_WARNING, "Overriding selected pixel format to use %s instead.\n",
  276. av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
  277. }
  278. }
  279. ctx->pixel_format = pxl_fmt_spec.ff_id;
  280. NSNumber *pixel_format = [NSNumber numberWithUnsignedInt:pxl_fmt_spec.avf_id];
  281. NSDictionary *capture_dict = [NSDictionary dictionaryWithObject:pixel_format
  282. forKey:(id)kCVPixelBufferPixelFormatTypeKey];
  283. [ctx->video_output setVideoSettings:capture_dict];
  284. [ctx->video_output setAlwaysDiscardsLateVideoFrames:YES];
  285. ctx->avf_delegate = [[AVFFrameReceiver alloc] initWithContext:ctx];
  286. dispatch_queue_t queue = dispatch_queue_create("avf_queue", NULL);
  287. [ctx->video_output setSampleBufferDelegate:ctx->avf_delegate queue:queue];
  288. dispatch_release(queue);
  289. if ([ctx->capture_session canAddOutput:ctx->video_output]) {
  290. [ctx->capture_session addOutput:ctx->video_output];
  291. } else {
  292. av_log(s, AV_LOG_ERROR, "can't add video output to capture session\n");
  293. return 1;
  294. }
  295. return 0;
  296. }
  297. static int add_audio_device(AVFormatContext *s, AVCaptureDevice *audio_device)
  298. {
  299. AVFContext *ctx = (AVFContext*)s->priv_data;
  300. NSError *error = nil;
  301. AVCaptureDeviceInput* audio_dev_input = [[[AVCaptureDeviceInput alloc] initWithDevice:audio_device error:&error] autorelease];
  302. if (!audio_dev_input) {
  303. av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
  304. [[error localizedDescription] UTF8String]);
  305. return 1;
  306. }
  307. if ([ctx->capture_session canAddInput:audio_dev_input]) {
  308. [ctx->capture_session addInput:audio_dev_input];
  309. } else {
  310. av_log(s, AV_LOG_ERROR, "can't add audio input to capture session\n");
  311. return 1;
  312. }
  313. // Attaching output
  314. ctx->audio_output = [[AVCaptureAudioDataOutput alloc] init];
  315. if (!ctx->audio_output) {
  316. av_log(s, AV_LOG_ERROR, "Failed to init AV audio output\n");
  317. return 1;
  318. }
  319. ctx->avf_audio_delegate = [[AVFAudioReceiver alloc] initWithContext:ctx];
  320. dispatch_queue_t queue = dispatch_queue_create("avf_audio_queue", NULL);
  321. [ctx->audio_output setSampleBufferDelegate:ctx->avf_audio_delegate queue:queue];
  322. dispatch_release(queue);
  323. if ([ctx->capture_session canAddOutput:ctx->audio_output]) {
  324. [ctx->capture_session addOutput:ctx->audio_output];
  325. } else {
  326. av_log(s, AV_LOG_ERROR, "adding audio output to capture session failed\n");
  327. return 1;
  328. }
  329. return 0;
  330. }
  331. static int get_video_config(AVFormatContext *s)
  332. {
  333. AVFContext *ctx = (AVFContext*)s->priv_data;
  334. // Take stream info from the first frame.
  335. while (ctx->frames_captured < 1) {
  336. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
  337. }
  338. lock_frames(ctx);
  339. AVStream* stream = avformat_new_stream(s, NULL);
  340. if (!stream) {
  341. return 1;
  342. }
  343. ctx->video_stream_index = stream->index;
  344. avpriv_set_pts_info(stream, 64, 1, avf_time_base);
  345. CVImageBufferRef image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
  346. CGSize image_buffer_size = CVImageBufferGetEncodedSize(image_buffer);
  347. stream->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
  348. stream->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  349. stream->codec->width = (int)image_buffer_size.width;
  350. stream->codec->height = (int)image_buffer_size.height;
  351. stream->codec->pix_fmt = ctx->pixel_format;
  352. CFRelease(ctx->current_frame);
  353. ctx->current_frame = nil;
  354. unlock_frames(ctx);
  355. return 0;
  356. }
  357. static int get_audio_config(AVFormatContext *s)
  358. {
  359. AVFContext *ctx = (AVFContext*)s->priv_data;
  360. // Take stream info from the first frame.
  361. while (ctx->audio_frames_captured < 1) {
  362. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
  363. }
  364. lock_frames(ctx);
  365. AVStream* stream = avformat_new_stream(s, NULL);
  366. if (!stream) {
  367. return 1;
  368. }
  369. ctx->audio_stream_index = stream->index;
  370. avpriv_set_pts_info(stream, 64, 1, avf_time_base);
  371. CMFormatDescriptionRef format_desc = CMSampleBufferGetFormatDescription(ctx->current_audio_frame);
  372. const AudioStreamBasicDescription *basic_desc = CMAudioFormatDescriptionGetStreamBasicDescription(format_desc);
  373. if (!basic_desc) {
  374. av_log(s, AV_LOG_ERROR, "audio format not available\n");
  375. return 1;
  376. }
  377. stream->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  378. stream->codec->sample_rate = basic_desc->mSampleRate;
  379. stream->codec->channels = basic_desc->mChannelsPerFrame;
  380. stream->codec->channel_layout = av_get_default_channel_layout(stream->codec->channels);
  381. ctx->audio_channels = basic_desc->mChannelsPerFrame;
  382. ctx->audio_bits_per_sample = basic_desc->mBitsPerChannel;
  383. ctx->audio_float = basic_desc->mFormatFlags & kAudioFormatFlagIsFloat;
  384. ctx->audio_be = basic_desc->mFormatFlags & kAudioFormatFlagIsBigEndian;
  385. ctx->audio_signed_integer = basic_desc->mFormatFlags & kAudioFormatFlagIsSignedInteger;
  386. ctx->audio_packed = basic_desc->mFormatFlags & kAudioFormatFlagIsPacked;
  387. ctx->audio_non_interleaved = basic_desc->mFormatFlags & kAudioFormatFlagIsNonInterleaved;
  388. if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
  389. ctx->audio_float &&
  390. ctx->audio_packed) {
  391. stream->codec->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
  392. } else {
  393. av_log(s, AV_LOG_ERROR, "audio format is not supported\n");
  394. return 1;
  395. }
  396. if (ctx->audio_non_interleaved) {
  397. CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
  398. ctx->audio_buffer_size = CMBlockBufferGetDataLength(block_buffer);
  399. ctx->audio_buffer = av_malloc(ctx->audio_buffer_size);
  400. if (!ctx->audio_buffer) {
  401. av_log(s, AV_LOG_ERROR, "error allocating audio buffer\n");
  402. return 1;
  403. }
  404. }
  405. CFRelease(ctx->current_audio_frame);
  406. ctx->current_audio_frame = nil;
  407. unlock_frames(ctx);
  408. return 0;
  409. }
  410. static int avf_read_header(AVFormatContext *s)
  411. {
  412. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  413. AVFContext *ctx = (AVFContext*)s->priv_data;
  414. ctx->first_pts = av_gettime();
  415. ctx->first_audio_pts = av_gettime();
  416. pthread_mutex_init(&ctx->frame_lock, NULL);
  417. pthread_cond_init(&ctx->frame_wait_cond, NULL);
  418. // List devices if requested
  419. if (ctx->list_devices) {
  420. av_log(ctx, AV_LOG_INFO, "AVFoundation video devices:\n");
  421. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  422. for (AVCaptureDevice *device in devices) {
  423. const char *name = [[device localizedName] UTF8String];
  424. int index = [devices indexOfObject:device];
  425. av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
  426. }
  427. av_log(ctx, AV_LOG_INFO, "AVFoundation audio devices:\n");
  428. devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
  429. for (AVCaptureDevice *device in devices) {
  430. const char *name = [[device localizedName] UTF8String];
  431. int index = [devices indexOfObject:device];
  432. av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
  433. }
  434. goto fail;
  435. }
  436. // Find capture device
  437. AVCaptureDevice *video_device = nil;
  438. AVCaptureDevice *audio_device = nil;
  439. // parse input filename for video and audio device
  440. parse_device_name(s);
  441. // check for device index given in filename
  442. if (ctx->video_device_index == -1 && ctx->video_filename) {
  443. sscanf(ctx->video_filename, "%d", &ctx->video_device_index);
  444. }
  445. if (ctx->audio_device_index == -1 && ctx->audio_filename) {
  446. sscanf(ctx->audio_filename, "%d", &ctx->audio_device_index);
  447. }
  448. if (ctx->video_device_index >= 0) {
  449. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  450. if (ctx->video_device_index >= [devices count]) {
  451. av_log(ctx, AV_LOG_ERROR, "Invalid device index\n");
  452. goto fail;
  453. }
  454. video_device = [devices objectAtIndex:ctx->video_device_index];
  455. } else if (ctx->video_filename &&
  456. strncmp(ctx->video_filename, "default", 7)) {
  457. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  458. for (AVCaptureDevice *device in devices) {
  459. if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
  460. video_device = device;
  461. break;
  462. }
  463. }
  464. if (!video_device) {
  465. av_log(ctx, AV_LOG_ERROR, "Video device not found\n");
  466. goto fail;
  467. }
  468. } else {
  469. video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  470. }
  471. // get audio device
  472. if (ctx->audio_device_index >= 0) {
  473. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
  474. if (ctx->audio_device_index >= [devices count]) {
  475. av_log(ctx, AV_LOG_ERROR, "Invalid audio device index\n");
  476. goto fail;
  477. }
  478. audio_device = [devices objectAtIndex:ctx->audio_device_index];
  479. } else if (ctx->audio_filename &&
  480. strncmp(ctx->audio_filename, "default", 7)) {
  481. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
  482. for (AVCaptureDevice *device in devices) {
  483. if (!strncmp(ctx->audio_filename, [[device localizedName] UTF8String], strlen(ctx->audio_filename))) {
  484. audio_device = device;
  485. break;
  486. }
  487. }
  488. if (!audio_device) {
  489. av_log(ctx, AV_LOG_ERROR, "Audio device not found\n");
  490. goto fail;
  491. }
  492. } else {
  493. audio_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
  494. }
  495. // Video nor Audio capture device not found, looking for AVMediaTypeVideo/Audio
  496. if (!video_device && !audio_device) {
  497. av_log(s, AV_LOG_ERROR, "No AV capture device found\n");
  498. goto fail;
  499. }
  500. if (video_device) {
  501. av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device localizedName] UTF8String]);
  502. }
  503. if (audio_device) {
  504. av_log(s, AV_LOG_DEBUG, "audio device '%s' opened\n", [[audio_device localizedName] UTF8String]);
  505. }
  506. // Initialize capture session
  507. ctx->capture_session = [[AVCaptureSession alloc] init];
  508. if (video_device && add_video_device(s, video_device)) {
  509. goto fail;
  510. }
  511. if (audio_device && add_audio_device(s, audio_device)) {
  512. }
  513. [ctx->capture_session startRunning];
  514. if (video_device && get_video_config(s)) {
  515. goto fail;
  516. }
  517. // set audio stream
  518. if (audio_device && get_audio_config(s)) {
  519. goto fail;
  520. }
  521. [pool release];
  522. return 0;
  523. fail:
  524. [pool release];
  525. destroy_context(ctx);
  526. return AVERROR(EIO);
  527. }
  528. static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
  529. {
  530. AVFContext* ctx = (AVFContext*)s->priv_data;
  531. do {
  532. lock_frames(ctx);
  533. CVImageBufferRef image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
  534. if (ctx->current_frame != nil) {
  535. if (av_new_packet(pkt, (int)CVPixelBufferGetDataSize(image_buffer)) < 0) {
  536. return AVERROR(EIO);
  537. }
  538. pkt->pts = pkt->dts = av_rescale_q(av_gettime() - ctx->first_pts,
  539. AV_TIME_BASE_Q,
  540. avf_time_base_q);
  541. pkt->stream_index = ctx->video_stream_index;
  542. pkt->flags |= AV_PKT_FLAG_KEY;
  543. CVPixelBufferLockBaseAddress(image_buffer, 0);
  544. void* data = CVPixelBufferGetBaseAddress(image_buffer);
  545. memcpy(pkt->data, data, pkt->size);
  546. CVPixelBufferUnlockBaseAddress(image_buffer, 0);
  547. CFRelease(ctx->current_frame);
  548. ctx->current_frame = nil;
  549. } else if (ctx->current_audio_frame != nil) {
  550. CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
  551. int block_buffer_size = CMBlockBufferGetDataLength(block_buffer);
  552. if (!block_buffer || !block_buffer_size) {
  553. return AVERROR(EIO);
  554. }
  555. if (ctx->audio_non_interleaved && block_buffer_size > ctx->audio_buffer_size) {
  556. return AVERROR_BUFFER_TOO_SMALL;
  557. }
  558. if (av_new_packet(pkt, block_buffer_size) < 0) {
  559. return AVERROR(EIO);
  560. }
  561. pkt->pts = pkt->dts = av_rescale_q(av_gettime() - ctx->first_audio_pts,
  562. AV_TIME_BASE_Q,
  563. avf_time_base_q);
  564. pkt->stream_index = ctx->audio_stream_index;
  565. pkt->flags |= AV_PKT_FLAG_KEY;
  566. if (ctx->audio_non_interleaved) {
  567. int sample, c, shift;
  568. OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, ctx->audio_buffer);
  569. if (ret != kCMBlockBufferNoErr) {
  570. return AVERROR(EIO);
  571. }
  572. int num_samples = pkt->size / (ctx->audio_channels * (ctx->audio_bits_per_sample >> 3));
  573. // transform decoded frame into output format
  574. #define INTERLEAVE_OUTPUT(bps) \
  575. { \
  576. int##bps##_t **src; \
  577. int##bps##_t *dest; \
  578. src = av_malloc(ctx->audio_channels * sizeof(int##bps##_t*)); \
  579. if (!src) return AVERROR(EIO); \
  580. for (c = 0; c < ctx->audio_channels; c++) { \
  581. src[c] = ((int##bps##_t*)ctx->audio_buffer) + c * num_samples; \
  582. } \
  583. dest = (int##bps##_t*)pkt->data; \
  584. shift = bps - ctx->audio_bits_per_sample; \
  585. for (sample = 0; sample < num_samples; sample++) \
  586. for (c = 0; c < ctx->audio_channels; c++) \
  587. *dest++ = src[c][sample] << shift; \
  588. av_freep(&src); \
  589. }
  590. if (ctx->audio_bits_per_sample <= 16) {
  591. INTERLEAVE_OUTPUT(16)
  592. } else {
  593. INTERLEAVE_OUTPUT(32)
  594. }
  595. } else {
  596. OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
  597. if (ret != kCMBlockBufferNoErr) {
  598. return AVERROR(EIO);
  599. }
  600. }
  601. CFRelease(ctx->current_audio_frame);
  602. ctx->current_audio_frame = nil;
  603. } else {
  604. pkt->data = NULL;
  605. pthread_cond_wait(&ctx->frame_wait_cond, &ctx->frame_lock);
  606. }
  607. unlock_frames(ctx);
  608. } while (!pkt->data);
  609. return 0;
  610. }
  611. static int avf_close(AVFormatContext *s)
  612. {
  613. AVFContext* ctx = (AVFContext*)s->priv_data;
  614. destroy_context(ctx);
  615. return 0;
  616. }
  617. static const AVOption options[] = {
  618. { "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 },
  619. { "list_devices", "list available devices", offsetof(AVFContext, list_devices), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
  620. { "true", "", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
  621. { "false", "", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
  622. { "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 },
  623. { "audio_device_index", "select audio device by index for devices with same name (starts at 0)", offsetof(AVFContext, audio_device_index), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
  624. { "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},
  625. { NULL },
  626. };
  627. static const AVClass avf_class = {
  628. .class_name = "AVFoundation input device",
  629. .item_name = av_default_item_name,
  630. .option = options,
  631. .version = LIBAVUTIL_VERSION_INT,
  632. .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
  633. };
  634. AVInputFormat ff_avfoundation_demuxer = {
  635. .name = "avfoundation",
  636. .long_name = NULL_IF_CONFIG_SMALL("AVFoundation input device"),
  637. .priv_data_size = sizeof(AVFContext),
  638. .read_header = avf_read_header,
  639. .read_packet = avf_read_packet,
  640. .read_close = avf_close,
  641. .flags = AVFMT_NOFILE,
  642. .priv_class = &avf_class,
  643. };