avfoundation.m 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  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 "libavutil/avstring.h"
  31. #include "libavformat/internal.h"
  32. #include "libavutil/internal.h"
  33. #include "libavutil/parseutils.h"
  34. #include "libavutil/time.h"
  35. #include "libavutil/imgutils.h"
  36. #include "avdevice.h"
  37. static const int avf_time_base = 1000000;
  38. static const AVRational avf_time_base_q = {
  39. .num = 1,
  40. .den = avf_time_base
  41. };
  42. struct AVFPixelFormatSpec {
  43. enum AVPixelFormat ff_id;
  44. OSType avf_id;
  45. };
  46. static const struct AVFPixelFormatSpec avf_pixel_formats[] = {
  47. { AV_PIX_FMT_MONOBLACK, kCVPixelFormatType_1Monochrome },
  48. { AV_PIX_FMT_RGB555BE, kCVPixelFormatType_16BE555 },
  49. { AV_PIX_FMT_RGB555LE, kCVPixelFormatType_16LE555 },
  50. { AV_PIX_FMT_RGB565BE, kCVPixelFormatType_16BE565 },
  51. { AV_PIX_FMT_RGB565LE, kCVPixelFormatType_16LE565 },
  52. { AV_PIX_FMT_RGB24, kCVPixelFormatType_24RGB },
  53. { AV_PIX_FMT_BGR24, kCVPixelFormatType_24BGR },
  54. { AV_PIX_FMT_0RGB, kCVPixelFormatType_32ARGB },
  55. { AV_PIX_FMT_BGR0, kCVPixelFormatType_32BGRA },
  56. { AV_PIX_FMT_0BGR, kCVPixelFormatType_32ABGR },
  57. { AV_PIX_FMT_RGB0, kCVPixelFormatType_32RGBA },
  58. { AV_PIX_FMT_BGR48BE, kCVPixelFormatType_48RGB },
  59. { AV_PIX_FMT_UYVY422, kCVPixelFormatType_422YpCbCr8 },
  60. { AV_PIX_FMT_YUVA444P, kCVPixelFormatType_4444YpCbCrA8R },
  61. { AV_PIX_FMT_YUVA444P16LE, kCVPixelFormatType_4444AYpCbCr16 },
  62. { AV_PIX_FMT_YUV444P, kCVPixelFormatType_444YpCbCr8 },
  63. { AV_PIX_FMT_YUV422P16, kCVPixelFormatType_422YpCbCr16 },
  64. { AV_PIX_FMT_YUV422P10, kCVPixelFormatType_422YpCbCr10 },
  65. { AV_PIX_FMT_YUV444P10, kCVPixelFormatType_444YpCbCr10 },
  66. { AV_PIX_FMT_YUV420P, kCVPixelFormatType_420YpCbCr8Planar },
  67. { AV_PIX_FMT_NV12, kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange },
  68. { AV_PIX_FMT_YUYV422, kCVPixelFormatType_422YpCbCr8_yuvs },
  69. #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
  70. { AV_PIX_FMT_GRAY8, kCVPixelFormatType_OneComponent8 },
  71. #endif
  72. { AV_PIX_FMT_NONE, 0 }
  73. };
  74. typedef struct
  75. {
  76. AVClass* class;
  77. int frames_captured;
  78. int audio_frames_captured;
  79. int64_t first_pts;
  80. int64_t first_audio_pts;
  81. pthread_mutex_t frame_lock;
  82. pthread_cond_t frame_wait_cond;
  83. id avf_delegate;
  84. id avf_audio_delegate;
  85. AVRational framerate;
  86. int width, height;
  87. int capture_cursor;
  88. int capture_mouse_clicks;
  89. int capture_raw_data;
  90. int video_is_muxed;
  91. int list_devices;
  92. int video_device_index;
  93. int video_stream_index;
  94. int audio_device_index;
  95. int audio_stream_index;
  96. char *video_filename;
  97. char *audio_filename;
  98. int num_video_devices;
  99. int audio_channels;
  100. int audio_bits_per_sample;
  101. int audio_float;
  102. int audio_be;
  103. int audio_signed_integer;
  104. int audio_packed;
  105. int audio_non_interleaved;
  106. int32_t *audio_buffer;
  107. int audio_buffer_size;
  108. enum AVPixelFormat pixel_format;
  109. AVCaptureSession *capture_session;
  110. AVCaptureVideoDataOutput *video_output;
  111. AVCaptureAudioDataOutput *audio_output;
  112. CMSampleBufferRef current_frame;
  113. CMSampleBufferRef current_audio_frame;
  114. } AVFContext;
  115. static void lock_frames(AVFContext* ctx)
  116. {
  117. pthread_mutex_lock(&ctx->frame_lock);
  118. }
  119. static void unlock_frames(AVFContext* ctx)
  120. {
  121. pthread_mutex_unlock(&ctx->frame_lock);
  122. }
  123. /** FrameReciever class - delegate for AVCaptureSession
  124. */
  125. @interface AVFFrameReceiver : NSObject
  126. {
  127. AVFContext* _context;
  128. }
  129. - (id)initWithContext:(AVFContext*)context;
  130. - (void) captureOutput:(AVCaptureOutput *)captureOutput
  131. didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
  132. fromConnection:(AVCaptureConnection *)connection;
  133. @end
  134. @implementation AVFFrameReceiver
  135. - (id)initWithContext:(AVFContext*)context
  136. {
  137. if (self = [super init]) {
  138. _context = context;
  139. }
  140. return self;
  141. }
  142. - (void) captureOutput:(AVCaptureOutput *)captureOutput
  143. didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
  144. fromConnection:(AVCaptureConnection *)connection
  145. {
  146. lock_frames(_context);
  147. if (_context->current_frame != nil) {
  148. CFRelease(_context->current_frame);
  149. }
  150. _context->current_frame = (CMSampleBufferRef)CFRetain(videoFrame);
  151. pthread_cond_signal(&_context->frame_wait_cond);
  152. unlock_frames(_context);
  153. ++_context->frames_captured;
  154. }
  155. @end
  156. /** AudioReciever class - delegate for AVCaptureSession
  157. */
  158. @interface AVFAudioReceiver : NSObject
  159. {
  160. AVFContext* _context;
  161. }
  162. - (id)initWithContext:(AVFContext*)context;
  163. - (void) captureOutput:(AVCaptureOutput *)captureOutput
  164. didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
  165. fromConnection:(AVCaptureConnection *)connection;
  166. @end
  167. @implementation AVFAudioReceiver
  168. - (id)initWithContext:(AVFContext*)context
  169. {
  170. if (self = [super init]) {
  171. _context = context;
  172. }
  173. return self;
  174. }
  175. - (void) captureOutput:(AVCaptureOutput *)captureOutput
  176. didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
  177. fromConnection:(AVCaptureConnection *)connection
  178. {
  179. lock_frames(_context);
  180. if (_context->current_audio_frame != nil) {
  181. CFRelease(_context->current_audio_frame);
  182. }
  183. _context->current_audio_frame = (CMSampleBufferRef)CFRetain(audioFrame);
  184. pthread_cond_signal(&_context->frame_wait_cond);
  185. unlock_frames(_context);
  186. ++_context->audio_frames_captured;
  187. }
  188. @end
  189. static void destroy_context(AVFContext* ctx)
  190. {
  191. [ctx->capture_session stopRunning];
  192. [ctx->capture_session release];
  193. [ctx->video_output release];
  194. [ctx->audio_output release];
  195. [ctx->avf_delegate release];
  196. [ctx->avf_audio_delegate release];
  197. ctx->capture_session = NULL;
  198. ctx->video_output = NULL;
  199. ctx->audio_output = NULL;
  200. ctx->avf_delegate = NULL;
  201. ctx->avf_audio_delegate = NULL;
  202. av_freep(&ctx->audio_buffer);
  203. pthread_mutex_destroy(&ctx->frame_lock);
  204. pthread_cond_destroy(&ctx->frame_wait_cond);
  205. if (ctx->current_frame) {
  206. CFRelease(ctx->current_frame);
  207. }
  208. }
  209. static void parse_device_name(AVFormatContext *s)
  210. {
  211. AVFContext *ctx = (AVFContext*)s->priv_data;
  212. char *tmp = av_strdup(s->url);
  213. char *save;
  214. if (tmp[0] != ':') {
  215. ctx->video_filename = av_strtok(tmp, ":", &save);
  216. ctx->audio_filename = av_strtok(NULL, ":", &save);
  217. } else {
  218. ctx->audio_filename = av_strtok(tmp, ":", &save);
  219. }
  220. }
  221. /**
  222. * Configure the video device.
  223. *
  224. * Configure the video device using a run-time approach to access properties
  225. * since formats, activeFormat are available since iOS >= 7.0 or OSX >= 10.7
  226. * and activeVideoMaxFrameDuration is available since i0S >= 7.0 and OSX >= 10.9.
  227. *
  228. * The NSUndefinedKeyException must be handled by the caller of this function.
  229. *
  230. */
  231. static int configure_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
  232. {
  233. AVFContext *ctx = (AVFContext*)s->priv_data;
  234. double framerate = av_q2d(ctx->framerate);
  235. NSObject *range = nil;
  236. NSObject *format = nil;
  237. NSObject *selected_range = nil;
  238. NSObject *selected_format = nil;
  239. // try to configure format by formats list
  240. // might raise an exception if no format list is given
  241. // (then fallback to default, no configuration)
  242. @try {
  243. for (format in [video_device valueForKey:@"formats"]) {
  244. CMFormatDescriptionRef formatDescription;
  245. CMVideoDimensions dimensions;
  246. formatDescription = (CMFormatDescriptionRef) [format performSelector:@selector(formatDescription)];
  247. dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
  248. if ((ctx->width == 0 && ctx->height == 0) ||
  249. (dimensions.width == ctx->width && dimensions.height == ctx->height)) {
  250. selected_format = format;
  251. for (range in [format valueForKey:@"videoSupportedFrameRateRanges"]) {
  252. double max_framerate;
  253. [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
  254. if (fabs (framerate - max_framerate) < 0.01) {
  255. selected_range = range;
  256. break;
  257. }
  258. }
  259. }
  260. }
  261. if (!selected_format) {
  262. av_log(s, AV_LOG_ERROR, "Selected video size (%dx%d) is not supported by the device.\n",
  263. ctx->width, ctx->height);
  264. goto unsupported_format;
  265. }
  266. if (!selected_range) {
  267. av_log(s, AV_LOG_ERROR, "Selected framerate (%f) is not supported by the device.\n",
  268. framerate);
  269. if (ctx->video_is_muxed) {
  270. av_log(s, AV_LOG_ERROR, "Falling back to default.\n");
  271. } else {
  272. goto unsupported_format;
  273. }
  274. }
  275. if ([video_device lockForConfiguration:NULL] == YES) {
  276. if (selected_format) {
  277. [video_device setValue:selected_format forKey:@"activeFormat"];
  278. }
  279. if (selected_range) {
  280. NSValue *min_frame_duration = [selected_range valueForKey:@"minFrameDuration"];
  281. [video_device setValue:min_frame_duration forKey:@"activeVideoMinFrameDuration"];
  282. [video_device setValue:min_frame_duration forKey:@"activeVideoMaxFrameDuration"];
  283. }
  284. } else {
  285. av_log(s, AV_LOG_ERROR, "Could not lock device for configuration.\n");
  286. return AVERROR(EINVAL);
  287. }
  288. } @catch(NSException *e) {
  289. av_log(ctx, AV_LOG_WARNING, "Configuration of video device failed, falling back to default.\n");
  290. }
  291. return 0;
  292. unsupported_format:
  293. av_log(s, AV_LOG_ERROR, "Supported modes:\n");
  294. for (format in [video_device valueForKey:@"formats"]) {
  295. CMFormatDescriptionRef formatDescription;
  296. CMVideoDimensions dimensions;
  297. formatDescription = (CMFormatDescriptionRef) [format performSelector:@selector(formatDescription)];
  298. dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
  299. for (range in [format valueForKey:@"videoSupportedFrameRateRanges"]) {
  300. double min_framerate;
  301. double max_framerate;
  302. [[range valueForKey:@"minFrameRate"] getValue:&min_framerate];
  303. [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
  304. av_log(s, AV_LOG_ERROR, " %dx%d@[%f %f]fps\n",
  305. dimensions.width, dimensions.height,
  306. min_framerate, max_framerate);
  307. }
  308. }
  309. return AVERROR(EINVAL);
  310. }
  311. static int add_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
  312. {
  313. AVFContext *ctx = (AVFContext*)s->priv_data;
  314. int ret;
  315. NSError *error = nil;
  316. AVCaptureInput* capture_input = nil;
  317. struct AVFPixelFormatSpec pxl_fmt_spec;
  318. NSNumber *pixel_format;
  319. NSDictionary *capture_dict;
  320. dispatch_queue_t queue;
  321. if (ctx->video_device_index < ctx->num_video_devices) {
  322. capture_input = (AVCaptureInput*) [[[AVCaptureDeviceInput alloc] initWithDevice:video_device error:&error] autorelease];
  323. } else {
  324. capture_input = (AVCaptureInput*) video_device;
  325. }
  326. if (!capture_input) {
  327. av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
  328. [[error localizedDescription] UTF8String]);
  329. return 1;
  330. }
  331. if ([ctx->capture_session canAddInput:capture_input]) {
  332. [ctx->capture_session addInput:capture_input];
  333. } else {
  334. av_log(s, AV_LOG_ERROR, "can't add video input to capture session\n");
  335. return 1;
  336. }
  337. // Attaching output
  338. ctx->video_output = [[AVCaptureVideoDataOutput alloc] init];
  339. if (!ctx->video_output) {
  340. av_log(s, AV_LOG_ERROR, "Failed to init AV video output\n");
  341. return 1;
  342. }
  343. // Configure device framerate and video size
  344. @try {
  345. if ((ret = configure_video_device(s, video_device)) < 0) {
  346. return ret;
  347. }
  348. } @catch (NSException *exception) {
  349. if (![[exception name] isEqualToString:NSUndefinedKeyException]) {
  350. av_log (s, AV_LOG_ERROR, "An error occurred: %s", [exception.reason UTF8String]);
  351. return AVERROR_EXTERNAL;
  352. }
  353. }
  354. // select pixel format
  355. pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
  356. for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
  357. if (ctx->pixel_format == avf_pixel_formats[i].ff_id) {
  358. pxl_fmt_spec = avf_pixel_formats[i];
  359. break;
  360. }
  361. }
  362. // check if selected pixel format is supported by AVFoundation
  363. if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
  364. av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by AVFoundation.\n",
  365. av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
  366. return 1;
  367. }
  368. // check if the pixel format is available for this device
  369. if ([[ctx->video_output availableVideoCVPixelFormatTypes] indexOfObject:[NSNumber numberWithInt:pxl_fmt_spec.avf_id]] == NSNotFound) {
  370. av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by the input device.\n",
  371. av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
  372. pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
  373. av_log(s, AV_LOG_ERROR, "Supported pixel formats:\n");
  374. for (NSNumber *pxl_fmt in [ctx->video_output availableVideoCVPixelFormatTypes]) {
  375. struct AVFPixelFormatSpec pxl_fmt_dummy;
  376. pxl_fmt_dummy.ff_id = AV_PIX_FMT_NONE;
  377. for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
  378. if ([pxl_fmt intValue] == avf_pixel_formats[i].avf_id) {
  379. pxl_fmt_dummy = avf_pixel_formats[i];
  380. break;
  381. }
  382. }
  383. if (pxl_fmt_dummy.ff_id != AV_PIX_FMT_NONE) {
  384. av_log(s, AV_LOG_ERROR, " %s\n", av_get_pix_fmt_name(pxl_fmt_dummy.ff_id));
  385. // select first supported pixel format instead of user selected (or default) pixel format
  386. if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
  387. pxl_fmt_spec = pxl_fmt_dummy;
  388. }
  389. }
  390. }
  391. // fail if there is no appropriate pixel format or print a warning about overriding the pixel format
  392. if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
  393. return 1;
  394. } else {
  395. av_log(s, AV_LOG_WARNING, "Overriding selected pixel format to use %s instead.\n",
  396. av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
  397. }
  398. }
  399. // set videoSettings to an empty dict for receiving raw data of muxed devices
  400. if (ctx->capture_raw_data) {
  401. ctx->pixel_format = pxl_fmt_spec.ff_id;
  402. ctx->video_output.videoSettings = @{ };
  403. } else {
  404. ctx->pixel_format = pxl_fmt_spec.ff_id;
  405. pixel_format = [NSNumber numberWithUnsignedInt:pxl_fmt_spec.avf_id];
  406. capture_dict = [NSDictionary dictionaryWithObject:pixel_format
  407. forKey:(id)kCVPixelBufferPixelFormatTypeKey];
  408. [ctx->video_output setVideoSettings:capture_dict];
  409. }
  410. [ctx->video_output setAlwaysDiscardsLateVideoFrames:YES];
  411. ctx->avf_delegate = [[AVFFrameReceiver alloc] initWithContext:ctx];
  412. queue = dispatch_queue_create("avf_queue", NULL);
  413. [ctx->video_output setSampleBufferDelegate:ctx->avf_delegate queue:queue];
  414. dispatch_release(queue);
  415. if ([ctx->capture_session canAddOutput:ctx->video_output]) {
  416. [ctx->capture_session addOutput:ctx->video_output];
  417. } else {
  418. av_log(s, AV_LOG_ERROR, "can't add video output to capture session\n");
  419. return 1;
  420. }
  421. return 0;
  422. }
  423. static int add_audio_device(AVFormatContext *s, AVCaptureDevice *audio_device)
  424. {
  425. AVFContext *ctx = (AVFContext*)s->priv_data;
  426. NSError *error = nil;
  427. AVCaptureDeviceInput* audio_dev_input = [[[AVCaptureDeviceInput alloc] initWithDevice:audio_device error:&error] autorelease];
  428. dispatch_queue_t queue;
  429. if (!audio_dev_input) {
  430. av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
  431. [[error localizedDescription] UTF8String]);
  432. return 1;
  433. }
  434. if ([ctx->capture_session canAddInput:audio_dev_input]) {
  435. [ctx->capture_session addInput:audio_dev_input];
  436. } else {
  437. av_log(s, AV_LOG_ERROR, "can't add audio input to capture session\n");
  438. return 1;
  439. }
  440. // Attaching output
  441. ctx->audio_output = [[AVCaptureAudioDataOutput alloc] init];
  442. if (!ctx->audio_output) {
  443. av_log(s, AV_LOG_ERROR, "Failed to init AV audio output\n");
  444. return 1;
  445. }
  446. ctx->avf_audio_delegate = [[AVFAudioReceiver alloc] initWithContext:ctx];
  447. queue = dispatch_queue_create("avf_audio_queue", NULL);
  448. [ctx->audio_output setSampleBufferDelegate:ctx->avf_audio_delegate queue:queue];
  449. dispatch_release(queue);
  450. if ([ctx->capture_session canAddOutput:ctx->audio_output]) {
  451. [ctx->capture_session addOutput:ctx->audio_output];
  452. } else {
  453. av_log(s, AV_LOG_ERROR, "adding audio output to capture session failed\n");
  454. return 1;
  455. }
  456. return 0;
  457. }
  458. static int get_video_config(AVFormatContext *s)
  459. {
  460. AVFContext *ctx = (AVFContext*)s->priv_data;
  461. CVImageBufferRef image_buffer;
  462. CMBlockBufferRef block_buffer;
  463. CGSize image_buffer_size;
  464. AVStream* stream = avformat_new_stream(s, NULL);
  465. if (!stream) {
  466. return 1;
  467. }
  468. // Take stream info from the first frame.
  469. while (ctx->frames_captured < 1) {
  470. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
  471. }
  472. lock_frames(ctx);
  473. ctx->video_stream_index = stream->index;
  474. avpriv_set_pts_info(stream, 64, 1, avf_time_base);
  475. image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
  476. block_buffer = CMSampleBufferGetDataBuffer(ctx->current_frame);
  477. if (image_buffer) {
  478. image_buffer_size = CVImageBufferGetEncodedSize(image_buffer);
  479. stream->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
  480. stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  481. stream->codecpar->width = (int)image_buffer_size.width;
  482. stream->codecpar->height = (int)image_buffer_size.height;
  483. stream->codecpar->format = ctx->pixel_format;
  484. } else {
  485. stream->codecpar->codec_id = AV_CODEC_ID_DVVIDEO;
  486. stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  487. stream->codecpar->format = ctx->pixel_format;
  488. }
  489. CFRelease(ctx->current_frame);
  490. ctx->current_frame = nil;
  491. unlock_frames(ctx);
  492. return 0;
  493. }
  494. static int get_audio_config(AVFormatContext *s)
  495. {
  496. AVFContext *ctx = (AVFContext*)s->priv_data;
  497. CMFormatDescriptionRef format_desc;
  498. AVStream* stream = avformat_new_stream(s, NULL);
  499. if (!stream) {
  500. return 1;
  501. }
  502. // Take stream info from the first frame.
  503. while (ctx->audio_frames_captured < 1) {
  504. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
  505. }
  506. lock_frames(ctx);
  507. ctx->audio_stream_index = stream->index;
  508. avpriv_set_pts_info(stream, 64, 1, avf_time_base);
  509. format_desc = CMSampleBufferGetFormatDescription(ctx->current_audio_frame);
  510. const AudioStreamBasicDescription *basic_desc = CMAudioFormatDescriptionGetStreamBasicDescription(format_desc);
  511. if (!basic_desc) {
  512. av_log(s, AV_LOG_ERROR, "audio format not available\n");
  513. return 1;
  514. }
  515. stream->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  516. stream->codecpar->sample_rate = basic_desc->mSampleRate;
  517. stream->codecpar->channels = basic_desc->mChannelsPerFrame;
  518. stream->codecpar->channel_layout = av_get_default_channel_layout(stream->codecpar->channels);
  519. ctx->audio_channels = basic_desc->mChannelsPerFrame;
  520. ctx->audio_bits_per_sample = basic_desc->mBitsPerChannel;
  521. ctx->audio_float = basic_desc->mFormatFlags & kAudioFormatFlagIsFloat;
  522. ctx->audio_be = basic_desc->mFormatFlags & kAudioFormatFlagIsBigEndian;
  523. ctx->audio_signed_integer = basic_desc->mFormatFlags & kAudioFormatFlagIsSignedInteger;
  524. ctx->audio_packed = basic_desc->mFormatFlags & kAudioFormatFlagIsPacked;
  525. ctx->audio_non_interleaved = basic_desc->mFormatFlags & kAudioFormatFlagIsNonInterleaved;
  526. if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
  527. ctx->audio_float &&
  528. ctx->audio_bits_per_sample == 32 &&
  529. ctx->audio_packed) {
  530. stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
  531. } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
  532. ctx->audio_signed_integer &&
  533. ctx->audio_bits_per_sample == 16 &&
  534. ctx->audio_packed) {
  535. stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
  536. } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
  537. ctx->audio_signed_integer &&
  538. ctx->audio_bits_per_sample == 24 &&
  539. ctx->audio_packed) {
  540. stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
  541. } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
  542. ctx->audio_signed_integer &&
  543. ctx->audio_bits_per_sample == 32 &&
  544. ctx->audio_packed) {
  545. stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
  546. } else {
  547. av_log(s, AV_LOG_ERROR, "audio format is not supported\n");
  548. return 1;
  549. }
  550. if (ctx->audio_non_interleaved) {
  551. CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
  552. ctx->audio_buffer_size = CMBlockBufferGetDataLength(block_buffer);
  553. ctx->audio_buffer = av_malloc(ctx->audio_buffer_size);
  554. if (!ctx->audio_buffer) {
  555. av_log(s, AV_LOG_ERROR, "error allocating audio buffer\n");
  556. return 1;
  557. }
  558. }
  559. CFRelease(ctx->current_audio_frame);
  560. ctx->current_audio_frame = nil;
  561. unlock_frames(ctx);
  562. return 0;
  563. }
  564. static int avf_read_header(AVFormatContext *s)
  565. {
  566. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  567. int capture_screen = 0;
  568. uint32_t num_screens = 0;
  569. AVFContext *ctx = (AVFContext*)s->priv_data;
  570. AVCaptureDevice *video_device = nil;
  571. AVCaptureDevice *audio_device = nil;
  572. // Find capture device
  573. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  574. NSArray *devices_muxed = [AVCaptureDevice devicesWithMediaType:AVMediaTypeMuxed];
  575. ctx->num_video_devices = [devices count] + [devices_muxed count];
  576. ctx->first_pts = av_gettime();
  577. ctx->first_audio_pts = av_gettime();
  578. pthread_mutex_init(&ctx->frame_lock, NULL);
  579. pthread_cond_init(&ctx->frame_wait_cond, NULL);
  580. #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
  581. CGGetActiveDisplayList(0, NULL, &num_screens);
  582. #endif
  583. // List devices if requested
  584. if (ctx->list_devices) {
  585. int index = 0;
  586. av_log(ctx, AV_LOG_INFO, "AVFoundation video devices:\n");
  587. for (AVCaptureDevice *device in devices) {
  588. const char *name = [[device localizedName] UTF8String];
  589. index = [devices indexOfObject:device];
  590. av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
  591. }
  592. for (AVCaptureDevice *device in devices_muxed) {
  593. const char *name = [[device localizedName] UTF8String];
  594. index = [devices count] + [devices_muxed indexOfObject:device];
  595. av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
  596. }
  597. #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
  598. if (num_screens > 0) {
  599. CGDirectDisplayID screens[num_screens];
  600. CGGetActiveDisplayList(num_screens, screens, &num_screens);
  601. for (int i = 0; i < num_screens; i++) {
  602. av_log(ctx, AV_LOG_INFO, "[%d] Capture screen %d\n", ctx->num_video_devices + i, i);
  603. }
  604. }
  605. #endif
  606. av_log(ctx, AV_LOG_INFO, "AVFoundation audio devices:\n");
  607. devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
  608. for (AVCaptureDevice *device in devices) {
  609. const char *name = [[device localizedName] UTF8String];
  610. int index = [devices indexOfObject:device];
  611. av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
  612. }
  613. goto fail;
  614. }
  615. // parse input filename for video and audio device
  616. parse_device_name(s);
  617. // check for device index given in filename
  618. if (ctx->video_device_index == -1 && ctx->video_filename) {
  619. sscanf(ctx->video_filename, "%d", &ctx->video_device_index);
  620. }
  621. if (ctx->audio_device_index == -1 && ctx->audio_filename) {
  622. sscanf(ctx->audio_filename, "%d", &ctx->audio_device_index);
  623. }
  624. if (ctx->video_device_index >= 0) {
  625. if (ctx->video_device_index < ctx->num_video_devices) {
  626. if (ctx->video_device_index < [devices count]) {
  627. video_device = [devices objectAtIndex:ctx->video_device_index];
  628. } else {
  629. video_device = [devices_muxed objectAtIndex:(ctx->video_device_index - [devices count])];
  630. ctx->video_is_muxed = 1;
  631. }
  632. } else if (ctx->video_device_index < ctx->num_video_devices + num_screens) {
  633. #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
  634. CGDirectDisplayID screens[num_screens];
  635. CGGetActiveDisplayList(num_screens, screens, &num_screens);
  636. AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[ctx->video_device_index - ctx->num_video_devices]] autorelease];
  637. if (ctx->framerate.num > 0) {
  638. capture_screen_input.minFrameDuration = CMTimeMake(ctx->framerate.den, ctx->framerate.num);
  639. }
  640. #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
  641. if (ctx->capture_cursor) {
  642. capture_screen_input.capturesCursor = YES;
  643. } else {
  644. capture_screen_input.capturesCursor = NO;
  645. }
  646. #endif
  647. if (ctx->capture_mouse_clicks) {
  648. capture_screen_input.capturesMouseClicks = YES;
  649. } else {
  650. capture_screen_input.capturesMouseClicks = NO;
  651. }
  652. video_device = (AVCaptureDevice*) capture_screen_input;
  653. capture_screen = 1;
  654. #endif
  655. } else {
  656. av_log(ctx, AV_LOG_ERROR, "Invalid device index\n");
  657. goto fail;
  658. }
  659. } else if (ctx->video_filename &&
  660. strncmp(ctx->video_filename, "none", 4)) {
  661. if (!strncmp(ctx->video_filename, "default", 7)) {
  662. video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  663. } else {
  664. // looking for video inputs
  665. for (AVCaptureDevice *device in devices) {
  666. if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
  667. video_device = device;
  668. break;
  669. }
  670. }
  671. // looking for muxed inputs
  672. for (AVCaptureDevice *device in devices_muxed) {
  673. if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
  674. video_device = device;
  675. ctx->video_is_muxed = 1;
  676. break;
  677. }
  678. }
  679. #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
  680. // looking for screen inputs
  681. if (!video_device) {
  682. int idx;
  683. if(sscanf(ctx->video_filename, "Capture screen %d", &idx) && idx < num_screens) {
  684. CGDirectDisplayID screens[num_screens];
  685. CGGetActiveDisplayList(num_screens, screens, &num_screens);
  686. AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[idx]] autorelease];
  687. video_device = (AVCaptureDevice*) capture_screen_input;
  688. ctx->video_device_index = ctx->num_video_devices + idx;
  689. capture_screen = 1;
  690. if (ctx->framerate.num > 0) {
  691. capture_screen_input.minFrameDuration = CMTimeMake(ctx->framerate.den, ctx->framerate.num);
  692. }
  693. #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
  694. if (ctx->capture_cursor) {
  695. capture_screen_input.capturesCursor = YES;
  696. } else {
  697. capture_screen_input.capturesCursor = NO;
  698. }
  699. #endif
  700. if (ctx->capture_mouse_clicks) {
  701. capture_screen_input.capturesMouseClicks = YES;
  702. } else {
  703. capture_screen_input.capturesMouseClicks = NO;
  704. }
  705. }
  706. }
  707. #endif
  708. }
  709. if (!video_device) {
  710. av_log(ctx, AV_LOG_ERROR, "Video device not found\n");
  711. goto fail;
  712. }
  713. }
  714. // get audio device
  715. if (ctx->audio_device_index >= 0) {
  716. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
  717. if (ctx->audio_device_index >= [devices count]) {
  718. av_log(ctx, AV_LOG_ERROR, "Invalid audio device index\n");
  719. goto fail;
  720. }
  721. audio_device = [devices objectAtIndex:ctx->audio_device_index];
  722. } else if (ctx->audio_filename &&
  723. strncmp(ctx->audio_filename, "none", 4)) {
  724. if (!strncmp(ctx->audio_filename, "default", 7)) {
  725. audio_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
  726. } else {
  727. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
  728. for (AVCaptureDevice *device in devices) {
  729. if (!strncmp(ctx->audio_filename, [[device localizedName] UTF8String], strlen(ctx->audio_filename))) {
  730. audio_device = device;
  731. break;
  732. }
  733. }
  734. }
  735. if (!audio_device) {
  736. av_log(ctx, AV_LOG_ERROR, "Audio device not found\n");
  737. goto fail;
  738. }
  739. }
  740. // Video nor Audio capture device not found, looking for AVMediaTypeVideo/Audio
  741. if (!video_device && !audio_device) {
  742. av_log(s, AV_LOG_ERROR, "No AV capture device found\n");
  743. goto fail;
  744. }
  745. if (video_device) {
  746. if (ctx->video_device_index < ctx->num_video_devices) {
  747. av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device localizedName] UTF8String]);
  748. } else {
  749. av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device description] UTF8String]);
  750. }
  751. }
  752. if (audio_device) {
  753. av_log(s, AV_LOG_DEBUG, "audio device '%s' opened\n", [[audio_device localizedName] UTF8String]);
  754. }
  755. // Initialize capture session
  756. ctx->capture_session = [[AVCaptureSession alloc] init];
  757. if (video_device && add_video_device(s, video_device)) {
  758. goto fail;
  759. }
  760. if (audio_device && add_audio_device(s, audio_device)) {
  761. }
  762. [ctx->capture_session startRunning];
  763. /* Unlock device configuration only after the session is started so it
  764. * does not reset the capture formats */
  765. if (!capture_screen) {
  766. [video_device unlockForConfiguration];
  767. }
  768. if (video_device && get_video_config(s)) {
  769. goto fail;
  770. }
  771. // set audio stream
  772. if (audio_device && get_audio_config(s)) {
  773. goto fail;
  774. }
  775. [pool release];
  776. return 0;
  777. fail:
  778. [pool release];
  779. destroy_context(ctx);
  780. return AVERROR(EIO);
  781. }
  782. static int copy_cvpixelbuffer(AVFormatContext *s,
  783. CVPixelBufferRef image_buffer,
  784. AVPacket *pkt)
  785. {
  786. AVFContext *ctx = s->priv_data;
  787. int src_linesize[4];
  788. const uint8_t *src_data[4];
  789. int width = CVPixelBufferGetWidth(image_buffer);
  790. int height = CVPixelBufferGetHeight(image_buffer);
  791. int status;
  792. memset(src_linesize, 0, sizeof(src_linesize));
  793. memset(src_data, 0, sizeof(src_data));
  794. status = CVPixelBufferLockBaseAddress(image_buffer, 0);
  795. if (status != kCVReturnSuccess) {
  796. av_log(s, AV_LOG_ERROR, "Could not lock base address: %d (%dx%d)\n", status, width, height);
  797. return AVERROR_EXTERNAL;
  798. }
  799. if (CVPixelBufferIsPlanar(image_buffer)) {
  800. size_t plane_count = CVPixelBufferGetPlaneCount(image_buffer);
  801. int i;
  802. for(i = 0; i < plane_count; i++){
  803. src_linesize[i] = CVPixelBufferGetBytesPerRowOfPlane(image_buffer, i);
  804. src_data[i] = CVPixelBufferGetBaseAddressOfPlane(image_buffer, i);
  805. }
  806. } else {
  807. src_linesize[0] = CVPixelBufferGetBytesPerRow(image_buffer);
  808. src_data[0] = CVPixelBufferGetBaseAddress(image_buffer);
  809. }
  810. status = av_image_copy_to_buffer(pkt->data, pkt->size,
  811. src_data, src_linesize,
  812. ctx->pixel_format, width, height, 1);
  813. CVPixelBufferUnlockBaseAddress(image_buffer, 0);
  814. return status;
  815. }
  816. static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
  817. {
  818. AVFContext* ctx = (AVFContext*)s->priv_data;
  819. do {
  820. CVImageBufferRef image_buffer;
  821. CMBlockBufferRef block_buffer;
  822. lock_frames(ctx);
  823. if (ctx->current_frame != nil) {
  824. int status;
  825. int length = 0;
  826. image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
  827. block_buffer = CMSampleBufferGetDataBuffer(ctx->current_frame);
  828. if (image_buffer != nil) {
  829. length = (int)CVPixelBufferGetDataSize(image_buffer);
  830. } else if (block_buffer != nil) {
  831. length = (int)CMBlockBufferGetDataLength(block_buffer);
  832. } else {
  833. return AVERROR(EINVAL);
  834. }
  835. if (av_new_packet(pkt, length) < 0) {
  836. return AVERROR(EIO);
  837. }
  838. CMItemCount count;
  839. CMSampleTimingInfo timing_info;
  840. if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_frame, 1, &timing_info, &count) == noErr) {
  841. AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
  842. pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
  843. }
  844. pkt->stream_index = ctx->video_stream_index;
  845. pkt->flags |= AV_PKT_FLAG_KEY;
  846. if (image_buffer) {
  847. status = copy_cvpixelbuffer(s, image_buffer, pkt);
  848. } else {
  849. status = 0;
  850. OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
  851. if (ret != kCMBlockBufferNoErr) {
  852. status = AVERROR(EIO);
  853. }
  854. }
  855. CFRelease(ctx->current_frame);
  856. ctx->current_frame = nil;
  857. if (status < 0)
  858. return status;
  859. } else if (ctx->current_audio_frame != nil) {
  860. CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
  861. int block_buffer_size = CMBlockBufferGetDataLength(block_buffer);
  862. if (!block_buffer || !block_buffer_size) {
  863. return AVERROR(EIO);
  864. }
  865. if (ctx->audio_non_interleaved && block_buffer_size > ctx->audio_buffer_size) {
  866. return AVERROR_BUFFER_TOO_SMALL;
  867. }
  868. if (av_new_packet(pkt, block_buffer_size) < 0) {
  869. return AVERROR(EIO);
  870. }
  871. CMItemCount count;
  872. CMSampleTimingInfo timing_info;
  873. if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_audio_frame, 1, &timing_info, &count) == noErr) {
  874. AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
  875. pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
  876. }
  877. pkt->stream_index = ctx->audio_stream_index;
  878. pkt->flags |= AV_PKT_FLAG_KEY;
  879. if (ctx->audio_non_interleaved) {
  880. int sample, c, shift, num_samples;
  881. OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, ctx->audio_buffer);
  882. if (ret != kCMBlockBufferNoErr) {
  883. return AVERROR(EIO);
  884. }
  885. num_samples = pkt->size / (ctx->audio_channels * (ctx->audio_bits_per_sample >> 3));
  886. // transform decoded frame into output format
  887. #define INTERLEAVE_OUTPUT(bps) \
  888. { \
  889. int##bps##_t **src; \
  890. int##bps##_t *dest; \
  891. src = av_malloc(ctx->audio_channels * sizeof(int##bps##_t*)); \
  892. if (!src) return AVERROR(EIO); \
  893. for (c = 0; c < ctx->audio_channels; c++) { \
  894. src[c] = ((int##bps##_t*)ctx->audio_buffer) + c * num_samples; \
  895. } \
  896. dest = (int##bps##_t*)pkt->data; \
  897. shift = bps - ctx->audio_bits_per_sample; \
  898. for (sample = 0; sample < num_samples; sample++) \
  899. for (c = 0; c < ctx->audio_channels; c++) \
  900. *dest++ = src[c][sample] << shift; \
  901. av_freep(&src); \
  902. }
  903. if (ctx->audio_bits_per_sample <= 16) {
  904. INTERLEAVE_OUTPUT(16)
  905. } else {
  906. INTERLEAVE_OUTPUT(32)
  907. }
  908. } else {
  909. OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
  910. if (ret != kCMBlockBufferNoErr) {
  911. return AVERROR(EIO);
  912. }
  913. }
  914. CFRelease(ctx->current_audio_frame);
  915. ctx->current_audio_frame = nil;
  916. } else {
  917. pkt->data = NULL;
  918. pthread_cond_wait(&ctx->frame_wait_cond, &ctx->frame_lock);
  919. }
  920. unlock_frames(ctx);
  921. } while (!pkt->data);
  922. return 0;
  923. }
  924. static int avf_close(AVFormatContext *s)
  925. {
  926. AVFContext* ctx = (AVFContext*)s->priv_data;
  927. destroy_context(ctx);
  928. return 0;
  929. }
  930. static const AVOption options[] = {
  931. { "list_devices", "list available devices", offsetof(AVFContext, list_devices), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
  932. { "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 },
  933. { "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 },
  934. { "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},
  935. { "framerate", "set frame rate", offsetof(AVFContext, framerate), AV_OPT_TYPE_VIDEO_RATE, {.str = "ntsc"}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
  936. { "video_size", "set video size", offsetof(AVFContext, width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, AV_OPT_FLAG_DECODING_PARAM },
  937. { "capture_cursor", "capture the screen cursor", offsetof(AVFContext, capture_cursor), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
  938. { "capture_mouse_clicks", "capture the screen mouse clicks", offsetof(AVFContext, capture_mouse_clicks), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
  939. { "capture_raw_data", "capture the raw data from device connection", offsetof(AVFContext, capture_raw_data), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
  940. { NULL },
  941. };
  942. static const AVClass avf_class = {
  943. .class_name = "AVFoundation indev",
  944. .item_name = av_default_item_name,
  945. .option = options,
  946. .version = LIBAVUTIL_VERSION_INT,
  947. .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
  948. };
  949. AVInputFormat ff_avfoundation_demuxer = {
  950. .name = "avfoundation",
  951. .long_name = NULL_IF_CONFIG_SMALL("AVFoundation input device"),
  952. .priv_data_size = sizeof(AVFContext),
  953. .read_header = avf_read_header,
  954. .read_packet = avf_read_packet,
  955. .read_close = avf_close,
  956. .flags = AVFMT_NOFILE,
  957. .priv_class = &avf_class,
  958. };