2 * Directshow capture interface
3 * Copyright (c) 2010 Ramiro Polla
5 * This file is part of FFmpeg.
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.
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.
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
22 #include "libavformat/timefilter.h"
32 IBaseFilter *device_filter[2];
34 libAVFilter *capture_filter[2];
35 libAVPin *capture_pin[2];
41 unsigned int curbufsize;
42 unsigned int video_frame_num;
44 IMediaControl *control;
46 TimeFilter *timefilter;
49 static enum PixelFormat dshow_pixfmt(DWORD biCompression, WORD biBitCount)
51 switch(biCompression) {
52 case MKTAG('U', 'Y', 'V', 'Y'):
53 return PIX_FMT_UYVY422;
54 case MKTAG('Y', 'U', 'Y', '2'):
55 return PIX_FMT_YUYV422;
56 case MKTAG('I', '4', '2', '0'):
57 return PIX_FMT_YUV420P;
59 switch(biBitCount) { /* 1-8 are untested */
61 return PIX_FMT_MONOWHITE;
67 return PIX_FMT_RGB555;
77 static enum CodecID dshow_codecid(DWORD biCompression)
79 switch(biCompression) {
80 case MKTAG('d', 'v', 's', 'd'):
81 return CODEC_ID_DVVIDEO;
82 case MKTAG('M', 'J', 'P', 'G'):
83 case MKTAG('m', 'j', 'p', 'g'):
84 return CODEC_ID_MJPEG;
90 dshow_read_close(AVFormatContext *s)
92 struct dshow_ctx *ctx = s->priv_data;
96 IMediaControl_Stop(ctx->control);
97 IMediaControl_Release(ctx->control);
100 IGraphBuilder_Release(ctx->graph);
102 /* FIXME remove filters from graph */
103 /* FIXME disconnect pins */
104 if (ctx->capture_pin[VideoDevice])
105 libAVPin_Release(ctx->capture_pin[VideoDevice]);
106 if (ctx->capture_pin[AudioDevice])
107 libAVPin_Release(ctx->capture_pin[AudioDevice]);
108 if (ctx->capture_filter[VideoDevice])
109 libAVFilter_Release(ctx->capture_filter[VideoDevice]);
110 if (ctx->capture_filter[AudioDevice])
111 libAVFilter_Release(ctx->capture_filter[AudioDevice]);
113 if (ctx->device_pin[VideoDevice])
114 IPin_Release(ctx->device_pin[VideoDevice]);
115 if (ctx->device_pin[AudioDevice])
116 IPin_Release(ctx->device_pin[AudioDevice]);
117 if (ctx->device_filter[VideoDevice])
118 IBaseFilter_Release(ctx->device_filter[VideoDevice]);
119 if (ctx->device_filter[AudioDevice])
120 IBaseFilter_Release(ctx->device_filter[AudioDevice]);
122 if (ctx->device_name[0])
123 av_free(ctx->device_name[0]);
124 if (ctx->device_name[1])
125 av_free(ctx->device_name[1]);
128 CloseHandle(ctx->mutex);
130 CloseHandle(ctx->event);
134 AVPacketList *next = pktl->next;
135 av_destruct_packet(&pktl->pkt);
143 static char *dup_wchar_to_utf8(wchar_t *w)
146 int l = WideCharToMultiByte(CP_UTF8, 0, w, -1, 0, 0, 0, 0);
149 WideCharToMultiByte(CP_UTF8, 0, w, -1, s, l, 0, 0);
153 static int shall_we_drop(AVFormatContext *s)
155 struct dshow_ctx *ctx = s->priv_data;
156 const uint8_t dropscore[] = {62, 75, 87, 100};
157 const int ndropscores = FF_ARRAY_ELEMS(dropscore);
158 unsigned int buffer_fullness = (ctx->curbufsize*100)/s->max_picture_buffer;
160 if(dropscore[++ctx->video_frame_num%ndropscores] <= buffer_fullness) {
161 av_log(s, AV_LOG_ERROR,
162 "real-time buffer %d%% full! frame dropped!\n", buffer_fullness);
170 callback(void *priv_data, int index, uint8_t *buf, int buf_size, int64_t time)
172 AVFormatContext *s = priv_data;
173 struct dshow_ctx *ctx = s->priv_data;
174 AVPacketList **ppktl, *pktl_next;
176 // dump_videohdr(s, vdhdr);
181 WaitForSingleObject(ctx->mutex, INFINITE);
183 pktl_next = av_mallocz(sizeof(AVPacketList));
187 if(av_new_packet(&pktl_next->pkt, buf_size) < 0) {
192 pktl_next->pkt.stream_index = index;
193 pktl_next->pkt.pts = time;
194 memcpy(pktl_next->pkt.data, buf, buf_size);
196 for(ppktl = &ctx->pktl ; *ppktl ; ppktl = &(*ppktl)->next);
199 ctx->curbufsize += buf_size;
201 SetEvent(ctx->event);
202 ReleaseMutex(ctx->mutex);
206 ReleaseMutex(ctx->mutex);
211 dshow_open_device(AVFormatContext *avctx, ICreateDevEnum *devenum,
212 enum dshowDeviceType devtype)
214 struct dshow_ctx *ctx = avctx->priv_data;
215 IBaseFilter *device_filter = NULL;
216 IEnumMoniker *classenum = NULL;
217 IGraphBuilder *graph = ctx->graph;
220 IPin *device_pin = NULL;
221 libAVPin *capture_pin = NULL;
222 libAVFilter *capture_filter = NULL;
223 const char *device_name = ctx->device_name[devtype];
224 int ret = AVERROR(EIO);
228 const GUID *device_guid[2] = { &CLSID_VideoInputDeviceCategory,
229 &CLSID_AudioInputDeviceCategory };
230 const GUID *mediatype[2] = { &MEDIATYPE_Video, &MEDIATYPE_Audio };
231 const char *devtypename = (devtype == VideoDevice) ? "video" : "audio";
232 const wchar_t *filter_name[2] = { L"Audio capture filter", L"Video capture filter" };
234 r = ICreateDevEnum_CreateClassEnumerator(devenum, device_guid[devtype],
235 (IEnumMoniker **) &classenum, 0);
237 av_log(avctx, AV_LOG_ERROR, "Could not enumerate %s devices.\n",
242 while (IEnumMoniker_Next(classenum, 1, &m, NULL) == S_OK && !device_filter) {
243 IPropertyBag *bag = NULL;
247 r = IMoniker_BindToStorage(m, 0, 0, &IID_IPropertyBag, (void *) &bag);
252 r = IPropertyBag_Read(bag, L"FriendlyName", &var, NULL);
256 buf = dup_wchar_to_utf8(var.bstrVal);
258 if (strcmp(device_name, buf))
261 IMoniker_BindToObject(m, 0, 0, &IID_IBaseFilter, (void *) &device_filter);
267 IPropertyBag_Release(bag);
271 if (!device_filter) {
272 av_log(avctx, AV_LOG_ERROR, "Could not find %s device.\n",
276 ctx->device_filter [devtype] = device_filter;
278 r = IGraphBuilder_AddFilter(graph, device_filter, NULL);
280 av_log(avctx, AV_LOG_ERROR, "Could not add device filter to graph.\n");
284 r = IBaseFilter_EnumPins(device_filter, &pins);
286 av_log(avctx, AV_LOG_ERROR, "Could not enumerate pins.\n");
291 while (IEnumPins_Next(pins, 1, &pin, NULL) == S_OK && !device_pin) {
292 IKsPropertySet *p = NULL;
293 IEnumMediaTypes *types;
299 IPin_QueryPinInfo(pin, &info);
300 IBaseFilter_Release(info.pFilter);
302 if (info.dir != PINDIR_OUTPUT)
304 if (IPin_QueryInterface(pin, &IID_IKsPropertySet, (void **) &p) != S_OK)
306 if (IKsPropertySet_Get(p, &ROPSETID_Pin, AMPROPERTY_PIN_CATEGORY,
307 NULL, 0, &category, sizeof(GUID), &r2) != S_OK)
309 if (!IsEqualGUID(&category, &PIN_CATEGORY_CAPTURE))
312 if (IPin_EnumMediaTypes(pin, &types) != S_OK)
315 IEnumMediaTypes_Reset(types);
316 while (IEnumMediaTypes_Next(types, 1, &type, NULL) == S_OK && !device_pin) {
317 if (IsEqualGUID(&type->majortype, mediatype[devtype])) {
326 IEnumMediaTypes_Release(types);
328 IKsPropertySet_Release(p);
329 if (device_pin != pin)
334 av_log(avctx, AV_LOG_ERROR,
335 "Could not find output pin from %s capture device.\n", devtypename);
338 ctx->device_pin[devtype] = device_pin;
340 capture_filter = libAVFilter_Create(avctx, callback, devtype);
341 if (!capture_filter) {
342 av_log(avctx, AV_LOG_ERROR, "Could not create grabber filter.\n");
345 ctx->capture_filter[devtype] = capture_filter;
347 r = IGraphBuilder_AddFilter(graph, (IBaseFilter *) capture_filter,
348 filter_name[devtype]);
350 av_log(avctx, AV_LOG_ERROR, "Could not add capture filter to graph\n");
354 libAVPin_AddRef(capture_filter->pin);
355 capture_pin = capture_filter->pin;
356 ctx->capture_pin[devtype] = capture_pin;
358 r = IGraphBuilder_ConnectDirect(graph, device_pin, (IPin *) capture_pin, NULL);
360 av_log(avctx, AV_LOG_ERROR, "Could not connect pins\n");
368 IEnumPins_Release(pins);
370 IEnumMoniker_Release(classenum);
375 static enum CodecID waveform_codec_id(enum AVSampleFormat sample_fmt)
377 switch (sample_fmt) {
378 case AV_SAMPLE_FMT_U8: return CODEC_ID_PCM_U8;
379 case AV_SAMPLE_FMT_S16: return CODEC_ID_PCM_S16LE;
380 case AV_SAMPLE_FMT_S32: return CODEC_ID_PCM_S32LE;
381 default: return CODEC_ID_NONE; /* Should never happen. */
385 static enum SampleFormat sample_fmt_bits_per_sample(int bits)
388 case 8: return AV_SAMPLE_FMT_U8;
389 case 16: return AV_SAMPLE_FMT_S16;
390 case 32: return AV_SAMPLE_FMT_S32;
391 default: return AV_SAMPLE_FMT_NONE; /* Should never happen. */
396 dshow_add_device(AVFormatContext *avctx, AVFormatParameters *ap,
397 enum dshowDeviceType devtype)
399 struct dshow_ctx *ctx = avctx->priv_data;
401 AVCodecContext *codec;
403 int ret = AVERROR(EIO);
405 st = av_new_stream(avctx, devtype);
407 ret = AVERROR(ENOMEM);
411 ctx->capture_filter[devtype]->stream_index = st->index;
413 libAVPin_ConnectionMediaType(ctx->capture_pin[devtype], &type);
416 if (devtype == VideoDevice) {
417 BITMAPINFOHEADER *bih = NULL;
419 if (IsEqualGUID(&type.formattype, &FORMAT_VideoInfo)) {
420 VIDEOINFOHEADER *v = (void *) type.pbFormat;
422 } else if (IsEqualGUID(&type.formattype, &FORMAT_VideoInfo2)) {
423 VIDEOINFOHEADER2 *v = (void *) type.pbFormat;
427 av_log(avctx, AV_LOG_ERROR, "Could not get media type.\n");
431 codec->time_base = ap->time_base;
432 codec->codec_type = AVMEDIA_TYPE_VIDEO;
433 codec->width = bih->biWidth;
434 codec->height = bih->biHeight;
435 codec->pix_fmt = dshow_pixfmt(bih->biCompression, bih->biBitCount);
436 if (codec->pix_fmt == PIX_FMT_NONE) {
437 codec->codec_id = dshow_codecid(bih->biCompression);
438 if (codec->codec_id == CODEC_ID_NONE) {
439 av_log(avctx, AV_LOG_ERROR, "Unknown compression type. "
440 "Please report verbose (-v 9) debug information.\n");
441 dshow_read_close(avctx);
442 return AVERROR_PATCHWELCOME;
444 codec->bits_per_coded_sample = bih->biBitCount;
446 codec->codec_id = CODEC_ID_RAWVIDEO;
447 if (bih->biCompression == BI_RGB) {
448 codec->bits_per_coded_sample = bih->biBitCount;
449 codec->extradata = av_malloc(9 + FF_INPUT_BUFFER_PADDING_SIZE);
450 if (codec->extradata) {
451 codec->extradata_size = 9;
452 memcpy(codec->extradata, "BottomUp", 9);
457 WAVEFORMATEX *fx = NULL;
459 if (IsEqualGUID(&type.formattype, &FORMAT_WaveFormatEx)) {
460 fx = (void *) type.pbFormat;
463 av_log(avctx, AV_LOG_ERROR, "Could not get media type.\n");
467 codec->codec_type = AVMEDIA_TYPE_AUDIO;
468 codec->sample_fmt = sample_fmt_bits_per_sample(fx->wBitsPerSample);
469 codec->codec_id = waveform_codec_id(codec->sample_fmt);
470 codec->sample_rate = fx->nSamplesPerSec;
471 codec->channels = fx->nChannels;
474 av_set_pts_info(st, 64, 1, 10000000);
482 static int parse_device_name(AVFormatContext *avctx)
484 struct dshow_ctx *ctx = avctx->priv_data;
485 char **device_name = ctx->device_name;
486 char *name = av_strdup(avctx->filename);
491 while ((type = strtok(tmp, "="))) {
492 char *token = strtok(NULL, ":");
495 if (!strcmp(type, "video")) {
496 device_name[0] = token;
497 } else if (!strcmp(type, "audio")) {
498 device_name[1] = token;
500 device_name[0] = NULL;
501 device_name[1] = NULL;
506 if (!device_name[0] && !device_name[1]) {
510 device_name[0] = av_strdup(device_name[0]);
512 device_name[1] = av_strdup(device_name[1]);
519 static int dshow_read_header(AVFormatContext *avctx, AVFormatParameters *ap)
521 struct dshow_ctx *ctx = avctx->priv_data;
522 IGraphBuilder *graph = NULL;
523 ICreateDevEnum *devenum = NULL;
524 IMediaControl *control = NULL;
525 int ret = AVERROR(EIO);
528 if (!parse_device_name(avctx)) {
529 av_log(avctx, AV_LOG_ERROR, "Malformed dshow input string.\n");
535 r = CoCreateInstance(&CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
536 &IID_IGraphBuilder, (void **) &graph);
538 av_log(avctx, AV_LOG_ERROR, "Could not create capture graph.\n");
543 r = CoCreateInstance(&CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
544 &IID_ICreateDevEnum, (void **) &devenum);
546 av_log(avctx, AV_LOG_ERROR, "Could not enumerate system devices.\n");
550 if (ctx->device_name[VideoDevice]) {
551 ret = dshow_open_device(avctx, devenum, VideoDevice);
554 ret = dshow_add_device(avctx, ap, VideoDevice);
558 if (ctx->device_name[AudioDevice]) {
559 ret = dshow_open_device(avctx, devenum, AudioDevice);
562 ret = dshow_add_device(avctx, ap, AudioDevice);
567 ctx->mutex = CreateMutex(NULL, 0, NULL);
569 av_log(avctx, AV_LOG_ERROR, "Could not create Mutex\n");
572 ctx->event = CreateEvent(NULL, 1, 0, NULL);
574 av_log(avctx, AV_LOG_ERROR, "Could not create Event\n");
578 r = IGraphBuilder_QueryInterface(graph, &IID_IMediaControl, (void **) &control);
580 av_log(avctx, AV_LOG_ERROR, "Could not get media control.\n");
583 ctx->control = control;
585 r = IMediaControl_Run(control);
588 r = IMediaControl_GetState(control, 0, &pfs);
591 av_log(avctx, AV_LOG_ERROR, "Could not run filter\n");
600 dshow_read_close(avctx);
603 ICreateDevEnum_Release(devenum);
608 static int dshow_read_packet(AVFormatContext *s, AVPacket *pkt)
610 struct dshow_ctx *ctx = s->priv_data;
611 AVPacketList *pktl = NULL;
614 WaitForSingleObject(ctx->mutex, INFINITE);
617 *pkt = ctx->pktl->pkt;
618 ctx->pktl = ctx->pktl->next;
621 ResetEvent(ctx->event);
622 ReleaseMutex(ctx->mutex);
624 if (s->flags & AVFMT_FLAG_NONBLOCK) {
625 return AVERROR(EAGAIN);
627 WaitForSingleObject(ctx->event, INFINITE);
632 ctx->curbufsize -= pkt->size;
637 AVInputFormat ff_dshow_demuxer = {
639 NULL_IF_CONFIG_SMALL("DirectShow capture"),
640 sizeof(struct dshow_ctx),
645 .flags = AVFMT_NOFILE,