avfoundation.m 45 KB

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