qtkit.m 11 KB

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