avfoundation.m 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  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. id avf_delegate;
  83. id avf_audio_delegate;
  84. AVRational framerate;
  85. int width, height;
  86. int capture_cursor;
  87. int capture_mouse_clicks;
  88. int capture_raw_data;
  89. int drop_late_frames;
  90. int video_is_muxed;
  91. int video_is_screen;
  92. int list_devices;
  93. int video_device_index;
  94. int video_stream_index;
  95. int audio_device_index;
  96. int audio_stream_index;
  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->audio_buffer);
  250. pthread_mutex_destroy(&ctx->frame_lock);
  251. if (ctx->current_frame) {
  252. CFRelease(ctx->current_frame);
  253. }
  254. }
  255. static void parse_device_name(AVFormatContext *s)
  256. {
  257. AVFContext *ctx = (AVFContext*)s->priv_data;
  258. char *tmp = av_strdup(s->url);
  259. char *save;
  260. if (tmp[0] != ':') {
  261. ctx->video_filename = av_strtok(tmp, ":", &save);
  262. ctx->audio_filename = av_strtok(NULL, ":", &save);
  263. } else {
  264. ctx->audio_filename = av_strtok(tmp, ":", &save);
  265. }
  266. }
  267. /**
  268. * Configure the video device.
  269. *
  270. * Configure the video device using a run-time approach to access properties
  271. * since formats, activeFormat are available since iOS >= 7.0 or OSX >= 10.7
  272. * and activeVideoMaxFrameDuration is available since i0S >= 7.0 and OSX >= 10.9.
  273. *
  274. * The NSUndefinedKeyException must be handled by the caller of this function.
  275. *
  276. */
  277. static int configure_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
  278. {
  279. AVFContext *ctx = (AVFContext*)s->priv_data;
  280. double framerate = av_q2d(ctx->framerate);
  281. NSObject *range = nil;
  282. NSObject *format = nil;
  283. NSObject *selected_range = nil;
  284. NSObject *selected_format = nil;
  285. // try to configure format by formats list
  286. // might raise an exception if no format list is given
  287. // (then fallback to default, no configuration)
  288. @try {
  289. for (format in [video_device valueForKey:@"formats"]) {
  290. CMFormatDescriptionRef formatDescription;
  291. CMVideoDimensions dimensions;
  292. formatDescription = (CMFormatDescriptionRef) [format performSelector:@selector(formatDescription)];
  293. dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
  294. if ((ctx->width == 0 && ctx->height == 0) ||
  295. (dimensions.width == ctx->width && dimensions.height == ctx->height)) {
  296. selected_format = format;
  297. for (range in [format valueForKey:@"videoSupportedFrameRateRanges"]) {
  298. double max_framerate;
  299. [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
  300. if (fabs (framerate - max_framerate) < 0.01) {
  301. selected_range = range;
  302. break;
  303. }
  304. }
  305. }
  306. }
  307. if (!selected_format) {
  308. av_log(s, AV_LOG_ERROR, "Selected video size (%dx%d) is not supported by the device.\n",
  309. ctx->width, ctx->height);
  310. goto unsupported_format;
  311. }
  312. if (!selected_range) {
  313. av_log(s, AV_LOG_ERROR, "Selected framerate (%f) is not supported by the device.\n",
  314. framerate);
  315. if (ctx->video_is_muxed) {
  316. av_log(s, AV_LOG_ERROR, "Falling back to default.\n");
  317. } else {
  318. goto unsupported_format;
  319. }
  320. }
  321. if ([video_device lockForConfiguration:NULL] == YES) {
  322. if (selected_format) {
  323. [video_device setValue:selected_format forKey:@"activeFormat"];
  324. }
  325. if (selected_range) {
  326. NSValue *min_frame_duration = [selected_range valueForKey:@"minFrameDuration"];
  327. [video_device setValue:min_frame_duration forKey:@"activeVideoMinFrameDuration"];
  328. [video_device setValue:min_frame_duration forKey:@"activeVideoMaxFrameDuration"];
  329. }
  330. } else {
  331. av_log(s, AV_LOG_ERROR, "Could not lock device for configuration.\n");
  332. return AVERROR(EINVAL);
  333. }
  334. } @catch(NSException *e) {
  335. av_log(ctx, AV_LOG_WARNING, "Configuration of video device failed, falling back to default.\n");
  336. }
  337. return 0;
  338. unsupported_format:
  339. av_log(s, AV_LOG_ERROR, "Supported modes:\n");
  340. for (format in [video_device valueForKey:@"formats"]) {
  341. CMFormatDescriptionRef formatDescription;
  342. CMVideoDimensions dimensions;
  343. formatDescription = (CMFormatDescriptionRef) [format performSelector:@selector(formatDescription)];
  344. dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
  345. for (range in [format valueForKey:@"videoSupportedFrameRateRanges"]) {
  346. double min_framerate;
  347. double max_framerate;
  348. [[range valueForKey:@"minFrameRate"] getValue:&min_framerate];
  349. [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
  350. av_log(s, AV_LOG_ERROR, " %dx%d@[%f %f]fps\n",
  351. dimensions.width, dimensions.height,
  352. min_framerate, max_framerate);
  353. }
  354. }
  355. return AVERROR(EINVAL);
  356. }
  357. static int add_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
  358. {
  359. AVFContext *ctx = (AVFContext*)s->priv_data;
  360. int ret;
  361. NSError *error = nil;
  362. AVCaptureInput* capture_input = nil;
  363. struct AVFPixelFormatSpec pxl_fmt_spec;
  364. NSNumber *pixel_format;
  365. NSDictionary *capture_dict;
  366. dispatch_queue_t queue;
  367. if (ctx->video_device_index < ctx->num_video_devices) {
  368. capture_input = (AVCaptureInput*) [[[AVCaptureDeviceInput alloc] initWithDevice:video_device error:&error] autorelease];
  369. } else {
  370. capture_input = (AVCaptureInput*) video_device;
  371. }
  372. if (!capture_input) {
  373. av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
  374. [[error localizedDescription] UTF8String]);
  375. return 1;
  376. }
  377. if ([ctx->capture_session canAddInput:capture_input]) {
  378. [ctx->capture_session addInput:capture_input];
  379. } else {
  380. av_log(s, AV_LOG_ERROR, "can't add video input to capture session\n");
  381. return 1;
  382. }
  383. // Attaching output
  384. ctx->video_output = [[AVCaptureVideoDataOutput alloc] init];
  385. if (!ctx->video_output) {
  386. av_log(s, AV_LOG_ERROR, "Failed to init AV video output\n");
  387. return 1;
  388. }
  389. // Configure device framerate and video size
  390. @try {
  391. if ((ret = configure_video_device(s, video_device)) < 0) {
  392. return ret;
  393. }
  394. } @catch (NSException *exception) {
  395. if (![[exception name] isEqualToString:NSUndefinedKeyException]) {
  396. av_log (s, AV_LOG_ERROR, "An error occurred: %s", [exception.reason UTF8String]);
  397. return AVERROR_EXTERNAL;
  398. }
  399. }
  400. // select pixel format
  401. pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
  402. for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
  403. if (ctx->pixel_format == avf_pixel_formats[i].ff_id) {
  404. pxl_fmt_spec = avf_pixel_formats[i];
  405. break;
  406. }
  407. }
  408. // check if selected pixel format is supported by AVFoundation
  409. if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
  410. av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by AVFoundation.\n",
  411. av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
  412. return 1;
  413. }
  414. // check if the pixel format is available for this device
  415. if ([[ctx->video_output availableVideoCVPixelFormatTypes] indexOfObject:[NSNumber numberWithInt:pxl_fmt_spec.avf_id]] == NSNotFound) {
  416. av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by the input device.\n",
  417. av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
  418. pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
  419. av_log(s, AV_LOG_ERROR, "Supported pixel formats:\n");
  420. for (NSNumber *pxl_fmt in [ctx->video_output availableVideoCVPixelFormatTypes]) {
  421. struct AVFPixelFormatSpec pxl_fmt_dummy;
  422. pxl_fmt_dummy.ff_id = AV_PIX_FMT_NONE;
  423. for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
  424. if ([pxl_fmt intValue] == avf_pixel_formats[i].avf_id) {
  425. pxl_fmt_dummy = avf_pixel_formats[i];
  426. break;
  427. }
  428. }
  429. if (pxl_fmt_dummy.ff_id != AV_PIX_FMT_NONE) {
  430. av_log(s, AV_LOG_ERROR, " %s\n", av_get_pix_fmt_name(pxl_fmt_dummy.ff_id));
  431. // select first supported pixel format instead of user selected (or default) pixel format
  432. if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
  433. pxl_fmt_spec = pxl_fmt_dummy;
  434. }
  435. }
  436. }
  437. // fail if there is no appropriate pixel format or print a warning about overriding the pixel format
  438. if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
  439. return 1;
  440. } else {
  441. av_log(s, AV_LOG_WARNING, "Overriding selected pixel format to use %s instead.\n",
  442. av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
  443. }
  444. }
  445. // set videoSettings to an empty dict for receiving raw data of muxed devices
  446. if (ctx->capture_raw_data) {
  447. ctx->pixel_format = pxl_fmt_spec.ff_id;
  448. ctx->video_output.videoSettings = @{ };
  449. } else {
  450. ctx->pixel_format = pxl_fmt_spec.ff_id;
  451. pixel_format = [NSNumber numberWithUnsignedInt:pxl_fmt_spec.avf_id];
  452. capture_dict = [NSDictionary dictionaryWithObject:pixel_format
  453. forKey:(id)kCVPixelBufferPixelFormatTypeKey];
  454. [ctx->video_output setVideoSettings:capture_dict];
  455. }
  456. [ctx->video_output setAlwaysDiscardsLateVideoFrames:ctx->drop_late_frames];
  457. #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
  458. // check for transport control support and set observer device if supported
  459. if (!ctx->video_is_screen) {
  460. int trans_ctrl = [video_device transportControlsSupported];
  461. AVCaptureDeviceTransportControlsPlaybackMode trans_mode = [video_device transportControlsPlaybackMode];
  462. if (trans_ctrl) {
  463. ctx->observed_mode = trans_mode;
  464. ctx->observed_device = video_device;
  465. }
  466. }
  467. #endif
  468. ctx->avf_delegate = [[AVFFrameReceiver alloc] initWithContext:ctx];
  469. queue = dispatch_queue_create("avf_queue", NULL);
  470. [ctx->video_output setSampleBufferDelegate:ctx->avf_delegate queue:queue];
  471. dispatch_release(queue);
  472. if ([ctx->capture_session canAddOutput:ctx->video_output]) {
  473. [ctx->capture_session addOutput:ctx->video_output];
  474. } else {
  475. av_log(s, AV_LOG_ERROR, "can't add video output to capture session\n");
  476. return 1;
  477. }
  478. return 0;
  479. }
  480. static int add_audio_device(AVFormatContext *s, AVCaptureDevice *audio_device)
  481. {
  482. AVFContext *ctx = (AVFContext*)s->priv_data;
  483. NSError *error = nil;
  484. AVCaptureDeviceInput* audio_dev_input = [[[AVCaptureDeviceInput alloc] initWithDevice:audio_device error:&error] autorelease];
  485. dispatch_queue_t queue;
  486. if (!audio_dev_input) {
  487. av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
  488. [[error localizedDescription] UTF8String]);
  489. return 1;
  490. }
  491. if ([ctx->capture_session canAddInput:audio_dev_input]) {
  492. [ctx->capture_session addInput:audio_dev_input];
  493. } else {
  494. av_log(s, AV_LOG_ERROR, "can't add audio input to capture session\n");
  495. return 1;
  496. }
  497. // Attaching output
  498. ctx->audio_output = [[AVCaptureAudioDataOutput alloc] init];
  499. if (!ctx->audio_output) {
  500. av_log(s, AV_LOG_ERROR, "Failed to init AV audio output\n");
  501. return 1;
  502. }
  503. ctx->avf_audio_delegate = [[AVFAudioReceiver alloc] initWithContext:ctx];
  504. queue = dispatch_queue_create("avf_audio_queue", NULL);
  505. [ctx->audio_output setSampleBufferDelegate:ctx->avf_audio_delegate queue:queue];
  506. dispatch_release(queue);
  507. if ([ctx->capture_session canAddOutput:ctx->audio_output]) {
  508. [ctx->capture_session addOutput:ctx->audio_output];
  509. } else {
  510. av_log(s, AV_LOG_ERROR, "adding audio output to capture session failed\n");
  511. return 1;
  512. }
  513. return 0;
  514. }
  515. static int get_video_config(AVFormatContext *s)
  516. {
  517. AVFContext *ctx = (AVFContext*)s->priv_data;
  518. CVImageBufferRef image_buffer;
  519. CMBlockBufferRef block_buffer;
  520. CGSize image_buffer_size;
  521. AVStream* stream = avformat_new_stream(s, NULL);
  522. if (!stream) {
  523. return 1;
  524. }
  525. // Take stream info from the first frame.
  526. while (ctx->frames_captured < 1) {
  527. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
  528. }
  529. lock_frames(ctx);
  530. ctx->video_stream_index = stream->index;
  531. avpriv_set_pts_info(stream, 64, 1, avf_time_base);
  532. image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
  533. block_buffer = CMSampleBufferGetDataBuffer(ctx->current_frame);
  534. if (image_buffer) {
  535. image_buffer_size = CVImageBufferGetEncodedSize(image_buffer);
  536. stream->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
  537. stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  538. stream->codecpar->width = (int)image_buffer_size.width;
  539. stream->codecpar->height = (int)image_buffer_size.height;
  540. stream->codecpar->format = ctx->pixel_format;
  541. } else {
  542. stream->codecpar->codec_id = AV_CODEC_ID_DVVIDEO;
  543. stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  544. stream->codecpar->format = ctx->pixel_format;
  545. }
  546. CFRelease(ctx->current_frame);
  547. ctx->current_frame = nil;
  548. unlock_frames(ctx);
  549. return 0;
  550. }
  551. static int get_audio_config(AVFormatContext *s)
  552. {
  553. AVFContext *ctx = (AVFContext*)s->priv_data;
  554. CMFormatDescriptionRef format_desc;
  555. AVStream* stream = avformat_new_stream(s, NULL);
  556. if (!stream) {
  557. return 1;
  558. }
  559. // Take stream info from the first frame.
  560. while (ctx->audio_frames_captured < 1) {
  561. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
  562. }
  563. lock_frames(ctx);
  564. ctx->audio_stream_index = stream->index;
  565. avpriv_set_pts_info(stream, 64, 1, avf_time_base);
  566. format_desc = CMSampleBufferGetFormatDescription(ctx->current_audio_frame);
  567. const AudioStreamBasicDescription *basic_desc = CMAudioFormatDescriptionGetStreamBasicDescription(format_desc);
  568. if (!basic_desc) {
  569. av_log(s, AV_LOG_ERROR, "audio format not available\n");
  570. return 1;
  571. }
  572. stream->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  573. stream->codecpar->sample_rate = basic_desc->mSampleRate;
  574. stream->codecpar->channels = basic_desc->mChannelsPerFrame;
  575. stream->codecpar->channel_layout = av_get_default_channel_layout(stream->codecpar->channels);
  576. ctx->audio_channels = basic_desc->mChannelsPerFrame;
  577. ctx->audio_bits_per_sample = basic_desc->mBitsPerChannel;
  578. ctx->audio_float = basic_desc->mFormatFlags & kAudioFormatFlagIsFloat;
  579. ctx->audio_be = basic_desc->mFormatFlags & kAudioFormatFlagIsBigEndian;
  580. ctx->audio_signed_integer = basic_desc->mFormatFlags & kAudioFormatFlagIsSignedInteger;
  581. ctx->audio_packed = basic_desc->mFormatFlags & kAudioFormatFlagIsPacked;
  582. ctx->audio_non_interleaved = basic_desc->mFormatFlags & kAudioFormatFlagIsNonInterleaved;
  583. if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
  584. ctx->audio_float &&
  585. ctx->audio_bits_per_sample == 32 &&
  586. ctx->audio_packed) {
  587. stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
  588. } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
  589. ctx->audio_signed_integer &&
  590. ctx->audio_bits_per_sample == 16 &&
  591. ctx->audio_packed) {
  592. stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
  593. } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
  594. ctx->audio_signed_integer &&
  595. ctx->audio_bits_per_sample == 24 &&
  596. ctx->audio_packed) {
  597. stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
  598. } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
  599. ctx->audio_signed_integer &&
  600. ctx->audio_bits_per_sample == 32 &&
  601. ctx->audio_packed) {
  602. stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
  603. } else {
  604. av_log(s, AV_LOG_ERROR, "audio format is not supported\n");
  605. return 1;
  606. }
  607. if (ctx->audio_non_interleaved) {
  608. CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
  609. ctx->audio_buffer_size = CMBlockBufferGetDataLength(block_buffer);
  610. ctx->audio_buffer = av_malloc(ctx->audio_buffer_size);
  611. if (!ctx->audio_buffer) {
  612. av_log(s, AV_LOG_ERROR, "error allocating audio buffer\n");
  613. return 1;
  614. }
  615. }
  616. CFRelease(ctx->current_audio_frame);
  617. ctx->current_audio_frame = nil;
  618. unlock_frames(ctx);
  619. return 0;
  620. }
  621. static int avf_read_header(AVFormatContext *s)
  622. {
  623. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  624. uint32_t num_screens = 0;
  625. AVFContext *ctx = (AVFContext*)s->priv_data;
  626. AVCaptureDevice *video_device = nil;
  627. AVCaptureDevice *audio_device = nil;
  628. // Find capture device
  629. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
  630. NSArray *devices_muxed = [AVCaptureDevice devicesWithMediaType:AVMediaTypeMuxed];
  631. ctx->num_video_devices = [devices count] + [devices_muxed count];
  632. ctx->first_pts = av_gettime();
  633. ctx->first_audio_pts = av_gettime();
  634. pthread_mutex_init(&ctx->frame_lock, NULL);
  635. #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
  636. CGGetActiveDisplayList(0, NULL, &num_screens);
  637. #endif
  638. // List devices if requested
  639. if (ctx->list_devices) {
  640. int index = 0;
  641. av_log(ctx, AV_LOG_INFO, "AVFoundation video devices:\n");
  642. for (AVCaptureDevice *device in devices) {
  643. const char *name = [[device localizedName] UTF8String];
  644. index = [devices indexOfObject:device];
  645. av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
  646. }
  647. for (AVCaptureDevice *device in devices_muxed) {
  648. const char *name = [[device localizedName] UTF8String];
  649. index = [devices count] + [devices_muxed indexOfObject:device];
  650. av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
  651. }
  652. #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
  653. if (num_screens > 0) {
  654. CGDirectDisplayID screens[num_screens];
  655. CGGetActiveDisplayList(num_screens, screens, &num_screens);
  656. for (int i = 0; i < num_screens; i++) {
  657. av_log(ctx, AV_LOG_INFO, "[%d] Capture screen %d\n", ctx->num_video_devices + i, i);
  658. }
  659. }
  660. #endif
  661. av_log(ctx, AV_LOG_INFO, "AVFoundation audio devices:\n");
  662. devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
  663. for (AVCaptureDevice *device in devices) {
  664. const char *name = [[device localizedName] UTF8String];
  665. int index = [devices indexOfObject:device];
  666. av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
  667. }
  668. goto fail;
  669. }
  670. // parse input filename for video and audio device
  671. parse_device_name(s);
  672. // check for device index given in filename
  673. if (ctx->video_device_index == -1 && ctx->video_filename) {
  674. sscanf(ctx->video_filename, "%d", &ctx->video_device_index);
  675. }
  676. if (ctx->audio_device_index == -1 && ctx->audio_filename) {
  677. sscanf(ctx->audio_filename, "%d", &ctx->audio_device_index);
  678. }
  679. if (ctx->video_device_index >= 0) {
  680. if (ctx->video_device_index < ctx->num_video_devices) {
  681. if (ctx->video_device_index < [devices count]) {
  682. video_device = [devices objectAtIndex:ctx->video_device_index];
  683. } else {
  684. video_device = [devices_muxed objectAtIndex:(ctx->video_device_index - [devices count])];
  685. ctx->video_is_muxed = 1;
  686. }
  687. } else if (ctx->video_device_index < ctx->num_video_devices + num_screens) {
  688. #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
  689. CGDirectDisplayID screens[num_screens];
  690. CGGetActiveDisplayList(num_screens, screens, &num_screens);
  691. AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[ctx->video_device_index - ctx->num_video_devices]] autorelease];
  692. if (ctx->framerate.num > 0) {
  693. capture_screen_input.minFrameDuration = CMTimeMake(ctx->framerate.den, ctx->framerate.num);
  694. }
  695. #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
  696. if (ctx->capture_cursor) {
  697. capture_screen_input.capturesCursor = YES;
  698. } else {
  699. capture_screen_input.capturesCursor = NO;
  700. }
  701. #endif
  702. if (ctx->capture_mouse_clicks) {
  703. capture_screen_input.capturesMouseClicks = YES;
  704. } else {
  705. capture_screen_input.capturesMouseClicks = NO;
  706. }
  707. video_device = (AVCaptureDevice*) capture_screen_input;
  708. ctx->video_is_screen = 1;
  709. #endif
  710. } else {
  711. av_log(ctx, AV_LOG_ERROR, "Invalid device index\n");
  712. goto fail;
  713. }
  714. } else if (ctx->video_filename &&
  715. strncmp(ctx->video_filename, "none", 4)) {
  716. if (!strncmp(ctx->video_filename, "default", 7)) {
  717. video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  718. } else {
  719. // looking for video inputs
  720. for (AVCaptureDevice *device in devices) {
  721. if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
  722. video_device = device;
  723. break;
  724. }
  725. }
  726. // looking for muxed inputs
  727. for (AVCaptureDevice *device in devices_muxed) {
  728. if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
  729. video_device = device;
  730. ctx->video_is_muxed = 1;
  731. break;
  732. }
  733. }
  734. #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
  735. // looking for screen inputs
  736. if (!video_device) {
  737. int idx;
  738. if(sscanf(ctx->video_filename, "Capture screen %d", &idx) && idx < num_screens) {
  739. CGDirectDisplayID screens[num_screens];
  740. CGGetActiveDisplayList(num_screens, screens, &num_screens);
  741. AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[idx]] autorelease];
  742. video_device = (AVCaptureDevice*) capture_screen_input;
  743. ctx->video_device_index = ctx->num_video_devices + idx;
  744. ctx->video_is_screen = 1;
  745. if (ctx->framerate.num > 0) {
  746. capture_screen_input.minFrameDuration = CMTimeMake(ctx->framerate.den, ctx->framerate.num);
  747. }
  748. #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
  749. if (ctx->capture_cursor) {
  750. capture_screen_input.capturesCursor = YES;
  751. } else {
  752. capture_screen_input.capturesCursor = NO;
  753. }
  754. #endif
  755. if (ctx->capture_mouse_clicks) {
  756. capture_screen_input.capturesMouseClicks = YES;
  757. } else {
  758. capture_screen_input.capturesMouseClicks = NO;
  759. }
  760. }
  761. }
  762. #endif
  763. }
  764. if (!video_device) {
  765. av_log(ctx, AV_LOG_ERROR, "Video device not found\n");
  766. goto fail;
  767. }
  768. }
  769. // get audio device
  770. if (ctx->audio_device_index >= 0) {
  771. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
  772. if (ctx->audio_device_index >= [devices count]) {
  773. av_log(ctx, AV_LOG_ERROR, "Invalid audio device index\n");
  774. goto fail;
  775. }
  776. audio_device = [devices objectAtIndex:ctx->audio_device_index];
  777. } else if (ctx->audio_filename &&
  778. strncmp(ctx->audio_filename, "none", 4)) {
  779. if (!strncmp(ctx->audio_filename, "default", 7)) {
  780. audio_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
  781. } else {
  782. NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
  783. for (AVCaptureDevice *device in devices) {
  784. if (!strncmp(ctx->audio_filename, [[device localizedName] UTF8String], strlen(ctx->audio_filename))) {
  785. audio_device = device;
  786. break;
  787. }
  788. }
  789. }
  790. if (!audio_device) {
  791. av_log(ctx, AV_LOG_ERROR, "Audio device not found\n");
  792. goto fail;
  793. }
  794. }
  795. // Video nor Audio capture device not found, looking for AVMediaTypeVideo/Audio
  796. if (!video_device && !audio_device) {
  797. av_log(s, AV_LOG_ERROR, "No AV capture device found\n");
  798. goto fail;
  799. }
  800. if (video_device) {
  801. if (ctx->video_device_index < ctx->num_video_devices) {
  802. av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device localizedName] UTF8String]);
  803. } else {
  804. av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device description] UTF8String]);
  805. }
  806. }
  807. if (audio_device) {
  808. av_log(s, AV_LOG_DEBUG, "audio device '%s' opened\n", [[audio_device localizedName] UTF8String]);
  809. }
  810. // Initialize capture session
  811. ctx->capture_session = [[AVCaptureSession alloc] init];
  812. if (video_device && add_video_device(s, video_device)) {
  813. goto fail;
  814. }
  815. if (audio_device && add_audio_device(s, audio_device)) {
  816. }
  817. [ctx->capture_session startRunning];
  818. /* Unlock device configuration only after the session is started so it
  819. * does not reset the capture formats */
  820. if (!ctx->video_is_screen) {
  821. [video_device unlockForConfiguration];
  822. }
  823. if (video_device && get_video_config(s)) {
  824. goto fail;
  825. }
  826. // set audio stream
  827. if (audio_device && get_audio_config(s)) {
  828. goto fail;
  829. }
  830. [pool release];
  831. return 0;
  832. fail:
  833. [pool release];
  834. destroy_context(ctx);
  835. return AVERROR(EIO);
  836. }
  837. static int copy_cvpixelbuffer(AVFormatContext *s,
  838. CVPixelBufferRef image_buffer,
  839. AVPacket *pkt)
  840. {
  841. AVFContext *ctx = s->priv_data;
  842. int src_linesize[4];
  843. const uint8_t *src_data[4];
  844. int width = CVPixelBufferGetWidth(image_buffer);
  845. int height = CVPixelBufferGetHeight(image_buffer);
  846. int status;
  847. memset(src_linesize, 0, sizeof(src_linesize));
  848. memset(src_data, 0, sizeof(src_data));
  849. status = CVPixelBufferLockBaseAddress(image_buffer, 0);
  850. if (status != kCVReturnSuccess) {
  851. av_log(s, AV_LOG_ERROR, "Could not lock base address: %d (%dx%d)\n", status, width, height);
  852. return AVERROR_EXTERNAL;
  853. }
  854. if (CVPixelBufferIsPlanar(image_buffer)) {
  855. size_t plane_count = CVPixelBufferGetPlaneCount(image_buffer);
  856. int i;
  857. for(i = 0; i < plane_count; i++){
  858. src_linesize[i] = CVPixelBufferGetBytesPerRowOfPlane(image_buffer, i);
  859. src_data[i] = CVPixelBufferGetBaseAddressOfPlane(image_buffer, i);
  860. }
  861. } else {
  862. src_linesize[0] = CVPixelBufferGetBytesPerRow(image_buffer);
  863. src_data[0] = CVPixelBufferGetBaseAddress(image_buffer);
  864. }
  865. status = av_image_copy_to_buffer(pkt->data, pkt->size,
  866. src_data, src_linesize,
  867. ctx->pixel_format, width, height, 1);
  868. CVPixelBufferUnlockBaseAddress(image_buffer, 0);
  869. return status;
  870. }
  871. static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
  872. {
  873. AVFContext* ctx = (AVFContext*)s->priv_data;
  874. do {
  875. CVImageBufferRef image_buffer;
  876. CMBlockBufferRef block_buffer;
  877. lock_frames(ctx);
  878. if (ctx->current_frame != nil) {
  879. int status;
  880. int length = 0;
  881. image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
  882. block_buffer = CMSampleBufferGetDataBuffer(ctx->current_frame);
  883. if (image_buffer != nil) {
  884. length = (int)CVPixelBufferGetDataSize(image_buffer);
  885. } else if (block_buffer != nil) {
  886. length = (int)CMBlockBufferGetDataLength(block_buffer);
  887. } else {
  888. return AVERROR(EINVAL);
  889. }
  890. if (av_new_packet(pkt, length) < 0) {
  891. return AVERROR(EIO);
  892. }
  893. CMItemCount count;
  894. CMSampleTimingInfo timing_info;
  895. if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_frame, 1, &timing_info, &count) == noErr) {
  896. AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
  897. pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
  898. }
  899. pkt->stream_index = ctx->video_stream_index;
  900. pkt->flags |= AV_PKT_FLAG_KEY;
  901. if (image_buffer) {
  902. status = copy_cvpixelbuffer(s, image_buffer, pkt);
  903. } else {
  904. status = 0;
  905. OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
  906. if (ret != kCMBlockBufferNoErr) {
  907. status = AVERROR(EIO);
  908. }
  909. }
  910. CFRelease(ctx->current_frame);
  911. ctx->current_frame = nil;
  912. if (status < 0)
  913. return status;
  914. } else if (ctx->current_audio_frame != nil) {
  915. CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
  916. int block_buffer_size = CMBlockBufferGetDataLength(block_buffer);
  917. if (!block_buffer || !block_buffer_size) {
  918. return AVERROR(EIO);
  919. }
  920. if (ctx->audio_non_interleaved && block_buffer_size > ctx->audio_buffer_size) {
  921. return AVERROR_BUFFER_TOO_SMALL;
  922. }
  923. if (av_new_packet(pkt, block_buffer_size) < 0) {
  924. return AVERROR(EIO);
  925. }
  926. CMItemCount count;
  927. CMSampleTimingInfo timing_info;
  928. if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_audio_frame, 1, &timing_info, &count) == noErr) {
  929. AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
  930. pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
  931. }
  932. pkt->stream_index = ctx->audio_stream_index;
  933. pkt->flags |= AV_PKT_FLAG_KEY;
  934. if (ctx->audio_non_interleaved) {
  935. int sample, c, shift, num_samples;
  936. OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, ctx->audio_buffer);
  937. if (ret != kCMBlockBufferNoErr) {
  938. return AVERROR(EIO);
  939. }
  940. num_samples = pkt->size / (ctx->audio_channels * (ctx->audio_bits_per_sample >> 3));
  941. // transform decoded frame into output format
  942. #define INTERLEAVE_OUTPUT(bps) \
  943. { \
  944. int##bps##_t **src; \
  945. int##bps##_t *dest; \
  946. src = av_malloc(ctx->audio_channels * sizeof(int##bps##_t*)); \
  947. if (!src) return AVERROR(EIO); \
  948. for (c = 0; c < ctx->audio_channels; c++) { \
  949. src[c] = ((int##bps##_t*)ctx->audio_buffer) + c * num_samples; \
  950. } \
  951. dest = (int##bps##_t*)pkt->data; \
  952. shift = bps - ctx->audio_bits_per_sample; \
  953. for (sample = 0; sample < num_samples; sample++) \
  954. for (c = 0; c < ctx->audio_channels; c++) \
  955. *dest++ = src[c][sample] << shift; \
  956. av_freep(&src); \
  957. }
  958. if (ctx->audio_bits_per_sample <= 16) {
  959. INTERLEAVE_OUTPUT(16)
  960. } else {
  961. INTERLEAVE_OUTPUT(32)
  962. }
  963. } else {
  964. OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
  965. if (ret != kCMBlockBufferNoErr) {
  966. return AVERROR(EIO);
  967. }
  968. }
  969. CFRelease(ctx->current_audio_frame);
  970. ctx->current_audio_frame = nil;
  971. } else {
  972. pkt->data = NULL;
  973. unlock_frames(ctx);
  974. if (ctx->observed_quit) {
  975. return AVERROR_EOF;
  976. } else {
  977. return AVERROR(EAGAIN);
  978. }
  979. }
  980. unlock_frames(ctx);
  981. } while (!pkt->data);
  982. return 0;
  983. }
  984. static int avf_close(AVFormatContext *s)
  985. {
  986. AVFContext* ctx = (AVFContext*)s->priv_data;
  987. destroy_context(ctx);
  988. return 0;
  989. }
  990. static const AVOption options[] = {
  991. { "list_devices", "list available devices", offsetof(AVFContext, list_devices), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
  992. { "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 },
  993. { "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 },
  994. { "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},
  995. { "framerate", "set frame rate", offsetof(AVFContext, framerate), AV_OPT_TYPE_VIDEO_RATE, {.str = "ntsc"}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
  996. { "video_size", "set video size", offsetof(AVFContext, width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, AV_OPT_FLAG_DECODING_PARAM },
  997. { "capture_cursor", "capture the screen cursor", offsetof(AVFContext, capture_cursor), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
  998. { "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 },
  999. { "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 },
  1000. { "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 },
  1001. { NULL },
  1002. };
  1003. static const AVClass avf_class = {
  1004. .class_name = "AVFoundation indev",
  1005. .item_name = av_default_item_name,
  1006. .option = options,
  1007. .version = LIBAVUTIL_VERSION_INT,
  1008. .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
  1009. };
  1010. AVInputFormat ff_avfoundation_demuxer = {
  1011. .name = "avfoundation",
  1012. .long_name = NULL_IF_CONFIG_SMALL("AVFoundation input device"),
  1013. .priv_data_size = sizeof(AVFContext),
  1014. .read_header = avf_read_header,
  1015. .read_packet = avf_read_packet,
  1016. .read_close = avf_close,
  1017. .flags = AVFMT_NOFILE,
  1018. .priv_class = &avf_class,
  1019. };