qtkit.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. /*
  2. * QTKit input device
  3. * Copyright (c) 2013 Vadim Kalinsky <vadim@kalinsky.ru>
  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. * QTKit input device
  24. * @author Vadim Kalinsky <vadim@kalinsky.ru>
  25. */
  26. #if defined(__clang__)
  27. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  28. #endif
  29. #import <QTKit/QTKit.h>
  30. #include <pthread.h>
  31. #include "libavutil/pixdesc.h"
  32. #include "libavutil/opt.h"
  33. #include "libavformat/internal.h"
  34. #include "libavutil/internal.h"
  35. #include "libavutil/time.h"
  36. #include "avdevice.h"
  37. #define QTKIT_TIMEBASE 100
  38. static const AVRational kQTKitTimeBase_q = {
  39. .num = 1,
  40. .den = QTKIT_TIMEBASE
  41. };
  42. typedef struct
  43. {
  44. AVClass* class;
  45. float frame_rate;
  46. int frames_captured;
  47. int64_t first_pts;
  48. pthread_mutex_t frame_lock;
  49. pthread_cond_t frame_wait_cond;
  50. id qt_delegate;
  51. int list_devices;
  52. int video_device_index;
  53. QTCaptureSession* capture_session;
  54. QTCaptureDecompressedVideoOutput* video_output;
  55. CVImageBufferRef current_frame;
  56. } CaptureContext;
  57. static void lock_frames(CaptureContext* ctx)
  58. {
  59. pthread_mutex_lock(&ctx->frame_lock);
  60. }
  61. static void unlock_frames(CaptureContext* ctx)
  62. {
  63. pthread_mutex_unlock(&ctx->frame_lock);
  64. }
  65. /** FrameReciever class - delegate for QTCaptureSession
  66. */
  67. @interface FFMPEG_FrameReceiver : NSObject
  68. {
  69. CaptureContext* _context;
  70. }
  71. - (id)initWithContext:(CaptureContext*)context;
  72. - (void)captureOutput:(QTCaptureOutput *)captureOutput
  73. didOutputVideoFrame:(CVImageBufferRef)videoFrame
  74. withSampleBuffer:(QTSampleBuffer *)sampleBuffer
  75. fromConnection:(QTCaptureConnection *)connection;
  76. @end
  77. @implementation FFMPEG_FrameReceiver
  78. - (id)initWithContext:(CaptureContext*)context
  79. {
  80. if (self = [super init]) {
  81. _context = context;
  82. }
  83. return self;
  84. }
  85. - (void)captureOutput:(QTCaptureOutput *)captureOutput
  86. didOutputVideoFrame:(CVImageBufferRef)videoFrame
  87. withSampleBuffer:(QTSampleBuffer *)sampleBuffer
  88. fromConnection:(QTCaptureConnection *)connection
  89. {
  90. lock_frames(_context);
  91. if (_context->current_frame != nil) {
  92. CVBufferRelease(_context->current_frame);
  93. }
  94. _context->current_frame = CVBufferRetain(videoFrame);
  95. pthread_cond_signal(&_context->frame_wait_cond);
  96. unlock_frames(_context);
  97. ++_context->frames_captured;
  98. }
  99. @end
  100. static void destroy_context(CaptureContext* ctx)
  101. {
  102. [ctx->capture_session stopRunning];
  103. [ctx->capture_session release];
  104. [ctx->video_output release];
  105. [ctx->qt_delegate release];
  106. ctx->capture_session = NULL;
  107. ctx->video_output = NULL;
  108. ctx->qt_delegate = NULL;
  109. pthread_mutex_destroy(&ctx->frame_lock);
  110. pthread_cond_destroy(&ctx->frame_wait_cond);
  111. if (ctx->current_frame)
  112. CVBufferRelease(ctx->current_frame);
  113. }
  114. static int qtkit_read_header(AVFormatContext *s)
  115. {
  116. NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
  117. CaptureContext* ctx = (CaptureContext*)s->priv_data;
  118. ctx->first_pts = av_gettime();
  119. pthread_mutex_init(&ctx->frame_lock, NULL);
  120. pthread_cond_init(&ctx->frame_wait_cond, NULL);
  121. // List devices if requested
  122. if (ctx->list_devices) {
  123. av_log(ctx, AV_LOG_INFO, "QTKit video devices:\n");
  124. NSArray *devices = [QTCaptureDevice inputDevicesWithMediaType:QTMediaTypeVideo];
  125. for (QTCaptureDevice *device in devices) {
  126. const char *name = [[device localizedDisplayName] UTF8String];
  127. int index = [devices indexOfObject:device];
  128. av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
  129. }
  130. goto fail;
  131. }
  132. // Find capture device
  133. QTCaptureDevice *video_device = nil;
  134. // check for device index given in filename
  135. if (ctx->video_device_index == -1) {
  136. sscanf(s->filename, "%d", &ctx->video_device_index);
  137. }
  138. if (ctx->video_device_index >= 0) {
  139. NSArray *devices = [QTCaptureDevice inputDevicesWithMediaType:QTMediaTypeVideo];
  140. if (ctx->video_device_index >= [devices count]) {
  141. av_log(ctx, AV_LOG_ERROR, "Invalid device index\n");
  142. goto fail;
  143. }
  144. video_device = [devices objectAtIndex:ctx->video_device_index];
  145. } else if (strncmp(s->filename, "", 1) &&
  146. strncmp(s->filename, "default", 7)) {
  147. NSArray *devices = [QTCaptureDevice inputDevicesWithMediaType:QTMediaTypeVideo];
  148. for (QTCaptureDevice *device in devices) {
  149. if (!strncmp(s->filename, [[device localizedDisplayName] UTF8String], strlen(s->filename))) {
  150. video_device = device;
  151. break;
  152. }
  153. }
  154. if (!video_device) {
  155. av_log(ctx, AV_LOG_ERROR, "Video device not found\n");
  156. goto fail;
  157. }
  158. } else {
  159. video_device = [QTCaptureDevice defaultInputDeviceWithMediaType:QTMediaTypeMuxed];
  160. }
  161. BOOL success = [video_device open:nil];
  162. // Video capture device not found, looking for QTMediaTypeVideo
  163. if (!success) {
  164. video_device = [QTCaptureDevice defaultInputDeviceWithMediaType:QTMediaTypeVideo];
  165. success = [video_device open:nil];
  166. if (!success) {
  167. av_log(s, AV_LOG_ERROR, "No QT capture device found\n");
  168. goto fail;
  169. }
  170. }
  171. NSString* dev_display_name = [video_device localizedDisplayName];
  172. av_log (s, AV_LOG_DEBUG, "'%s' opened\n", [dev_display_name UTF8String]);
  173. // Initialize capture session
  174. ctx->capture_session = [[QTCaptureSession alloc] init];
  175. QTCaptureDeviceInput* capture_dev_input = [[[QTCaptureDeviceInput alloc] initWithDevice:video_device] autorelease];
  176. success = [ctx->capture_session addInput:capture_dev_input error:nil];
  177. if (!success) {
  178. av_log (s, AV_LOG_ERROR, "Failed to add QT capture device to session\n");
  179. goto fail;
  180. }
  181. // Attaching output
  182. // FIXME: Allow for a user defined pixel format
  183. ctx->video_output = [[QTCaptureDecompressedVideoOutput alloc] init];
  184. NSDictionary *captureDictionary = [NSDictionary dictionaryWithObject:
  185. [NSNumber numberWithUnsignedInt:kCVPixelFormatType_24RGB]
  186. forKey:(id)kCVPixelBufferPixelFormatTypeKey];
  187. [ctx->video_output setPixelBufferAttributes:captureDictionary];
  188. ctx->qt_delegate = [[FFMPEG_FrameReceiver alloc] initWithContext:ctx];
  189. [ctx->video_output setDelegate:ctx->qt_delegate];
  190. [ctx->video_output setAutomaticallyDropsLateVideoFrames:YES];
  191. [ctx->video_output setMinimumVideoFrameInterval:1.0/ctx->frame_rate];
  192. success = [ctx->capture_session addOutput:ctx->video_output error:nil];
  193. if (!success) {
  194. av_log (s, AV_LOG_ERROR, "can't add video output to capture session\n");
  195. goto fail;
  196. }
  197. [ctx->capture_session startRunning];
  198. // Take stream info from the first frame.
  199. while (ctx->frames_captured < 1) {
  200. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
  201. }
  202. lock_frames(ctx);
  203. AVStream* stream = avformat_new_stream(s, NULL);
  204. if (!stream) {
  205. goto fail;
  206. }
  207. avpriv_set_pts_info(stream, 64, 1, QTKIT_TIMEBASE);
  208. stream->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
  209. stream->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  210. stream->codec->width = (int)CVPixelBufferGetWidth (ctx->current_frame);
  211. stream->codec->height = (int)CVPixelBufferGetHeight(ctx->current_frame);
  212. stream->codec->pix_fmt = AV_PIX_FMT_RGB24;
  213. CVBufferRelease(ctx->current_frame);
  214. ctx->current_frame = nil;
  215. unlock_frames(ctx);
  216. [pool release];
  217. return 0;
  218. fail:
  219. [pool release];
  220. destroy_context(ctx);
  221. return AVERROR(EIO);
  222. }
  223. static int qtkit_read_packet(AVFormatContext *s, AVPacket *pkt)
  224. {
  225. CaptureContext* ctx = (CaptureContext*)s->priv_data;
  226. do {
  227. lock_frames(ctx);
  228. if (ctx->current_frame != nil) {
  229. if (av_new_packet(pkt, (int)CVPixelBufferGetDataSize(ctx->current_frame)) < 0) {
  230. return AVERROR(EIO);
  231. }
  232. pkt->pts = pkt->dts = av_rescale_q(av_gettime() - ctx->first_pts, AV_TIME_BASE_Q, kQTKitTimeBase_q);
  233. pkt->stream_index = 0;
  234. pkt->flags |= AV_PKT_FLAG_KEY;
  235. CVPixelBufferLockBaseAddress(ctx->current_frame, 0);
  236. void* data = CVPixelBufferGetBaseAddress(ctx->current_frame);
  237. memcpy(pkt->data, data, pkt->size);
  238. CVPixelBufferUnlockBaseAddress(ctx->current_frame, 0);
  239. CVBufferRelease(ctx->current_frame);
  240. ctx->current_frame = nil;
  241. } else {
  242. pkt->data = NULL;
  243. pthread_cond_wait(&ctx->frame_wait_cond, &ctx->frame_lock);
  244. }
  245. unlock_frames(ctx);
  246. } while (!pkt->data);
  247. return 0;
  248. }
  249. static int qtkit_close(AVFormatContext *s)
  250. {
  251. CaptureContext* ctx = (CaptureContext*)s->priv_data;
  252. destroy_context(ctx);
  253. return 0;
  254. }
  255. static const AVOption options[] = {
  256. { "frame_rate", "set frame rate", offsetof(CaptureContext, frame_rate), AV_OPT_TYPE_FLOAT, { .dbl = 30.0 }, 0.1, 30.0, AV_OPT_TYPE_VIDEO_RATE, NULL },
  257. { "list_devices", "list available devices", offsetof(CaptureContext, list_devices), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
  258. { "true", "", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
  259. { "false", "", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
  260. { "video_device_index", "select video device by index for devices with same name (starts at 0)", offsetof(CaptureContext, video_device_index), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
  261. { NULL },
  262. };
  263. static const AVClass qtkit_class = {
  264. .class_name = "QTKit input device",
  265. .item_name = av_default_item_name,
  266. .option = options,
  267. .version = LIBAVUTIL_VERSION_INT,
  268. .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
  269. };
  270. AVInputFormat ff_qtkit_demuxer = {
  271. .name = "qtkit",
  272. .long_name = NULL_IF_CONFIG_SMALL("QTKit input device"),
  273. .priv_data_size = sizeof(CaptureContext),
  274. .read_header = qtkit_read_header,
  275. .read_packet = qtkit_read_packet,
  276. .read_close = qtkit_close,
  277. .flags = AVFMT_NOFILE,
  278. .priv_class = &qtkit_class,
  279. };