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 "libavutil/opt.h"
36 IBaseFilter *device_filter[2];
38 libAVFilter *capture_filter[2];
39 libAVPin *capture_pin[2];
45 unsigned int curbufsize;
46 unsigned int video_frame_num;
48 IMediaControl *control;
51 static enum PixelFormat dshow_pixfmt(DWORD biCompression, WORD biBitCount)
53 switch(biCompression) {
54 case MKTAG('U', 'Y', 'V', 'Y'):
55 return PIX_FMT_UYVY422;
56 case MKTAG('Y', 'U', 'Y', '2'):
57 return PIX_FMT_YUYV422;
58 case MKTAG('I', '4', '2', '0'):
59 return PIX_FMT_YUV420P;
61 switch(biBitCount) { /* 1-8 are untested */
63 return PIX_FMT_MONOWHITE;
69 return PIX_FMT_RGB555;
79 static enum CodecID dshow_codecid(DWORD biCompression)
81 switch(biCompression) {
82 case MKTAG('d', 'v', 's', 'd'):
83 return CODEC_ID_DVVIDEO;
84 case MKTAG('M', 'J', 'P', 'G'):
85 case MKTAG('m', 'j', 'p', 'g'):
86 return CODEC_ID_MJPEG;
92 dshow_read_close(AVFormatContext *s)
94 struct dshow_ctx *ctx = s->priv_data;
98 IMediaControl_Stop(ctx->control);
99 IMediaControl_Release(ctx->control);
102 if (ctx->capture_pin[VideoDevice])
103 libAVPin_Release(ctx->capture_pin[VideoDevice]);
104 if (ctx->capture_pin[AudioDevice])
105 libAVPin_Release(ctx->capture_pin[AudioDevice]);
106 if (ctx->capture_filter[VideoDevice])
107 libAVFilter_Release(ctx->capture_filter[VideoDevice]);
108 if (ctx->capture_filter[AudioDevice])
109 libAVFilter_Release(ctx->capture_filter[AudioDevice]);
111 if (ctx->device_pin[VideoDevice])
112 IPin_Release(ctx->device_pin[VideoDevice]);
113 if (ctx->device_pin[AudioDevice])
114 IPin_Release(ctx->device_pin[AudioDevice]);
115 if (ctx->device_filter[VideoDevice])
116 IBaseFilter_Release(ctx->device_filter[VideoDevice]);
117 if (ctx->device_filter[AudioDevice])
118 IBaseFilter_Release(ctx->device_filter[AudioDevice]);
123 r = IGraphBuilder_EnumFilters(ctx->graph, &fenum);
126 IEnumFilters_Reset(fenum);
127 while (IEnumFilters_Next(fenum, 1, &f, NULL) == S_OK)
128 IGraphBuilder_RemoveFilter(ctx->graph, f);
129 IEnumFilters_Release(fenum);
131 IGraphBuilder_Release(ctx->graph);
134 if (ctx->device_name[0])
135 av_free(ctx->device_name[0]);
136 if (ctx->device_name[1])
137 av_free(ctx->device_name[1]);
140 CloseHandle(ctx->mutex);
142 CloseHandle(ctx->event);
146 AVPacketList *next = pktl->next;
147 av_destruct_packet(&pktl->pkt);
155 static char *dup_wchar_to_utf8(wchar_t *w)
158 int l = WideCharToMultiByte(CP_UTF8, 0, w, -1, 0, 0, 0, 0);
161 WideCharToMultiByte(CP_UTF8, 0, w, -1, s, l, 0, 0);
165 static int shall_we_drop(AVFormatContext *s)
167 struct dshow_ctx *ctx = s->priv_data;
168 const uint8_t dropscore[] = {62, 75, 87, 100};
169 const int ndropscores = FF_ARRAY_ELEMS(dropscore);
170 unsigned int buffer_fullness = (ctx->curbufsize*100)/s->max_picture_buffer;
172 if(dropscore[++ctx->video_frame_num%ndropscores] <= buffer_fullness) {
173 av_log(s, AV_LOG_ERROR,
174 "real-time buffer %d%% full! frame dropped!\n", buffer_fullness);
182 callback(void *priv_data, int index, uint8_t *buf, int buf_size, int64_t time)
184 AVFormatContext *s = priv_data;
185 struct dshow_ctx *ctx = s->priv_data;
186 AVPacketList **ppktl, *pktl_next;
188 // dump_videohdr(s, vdhdr);
193 WaitForSingleObject(ctx->mutex, INFINITE);
195 pktl_next = av_mallocz(sizeof(AVPacketList));
199 if(av_new_packet(&pktl_next->pkt, buf_size) < 0) {
204 pktl_next->pkt.stream_index = index;
205 pktl_next->pkt.pts = time;
206 memcpy(pktl_next->pkt.data, buf, buf_size);
208 for(ppktl = &ctx->pktl ; *ppktl ; ppktl = &(*ppktl)->next);
211 ctx->curbufsize += buf_size;
213 SetEvent(ctx->event);
214 ReleaseMutex(ctx->mutex);
218 ReleaseMutex(ctx->mutex);
223 * Cycle through available devices using the device enumerator devenum,
224 * retrieve the device with type specified by devtype and return the
225 * pointer to the object found in *pfilter.
226 * If pfilter is NULL, list all device names.
229 dshow_cycle_devices(AVFormatContext *avctx, ICreateDevEnum *devenum,
230 enum dshowDeviceType devtype, IBaseFilter **pfilter)
232 struct dshow_ctx *ctx = avctx->priv_data;
233 IBaseFilter *device_filter = NULL;
234 IEnumMoniker *classenum = NULL;
236 const char *device_name = ctx->device_name[devtype];
239 const GUID *device_guid[2] = { &CLSID_VideoInputDeviceCategory,
240 &CLSID_AudioInputDeviceCategory };
241 const char *devtypename = (devtype == VideoDevice) ? "video" : "audio";
243 r = ICreateDevEnum_CreateClassEnumerator(devenum, device_guid[devtype],
244 (IEnumMoniker **) &classenum, 0);
246 av_log(avctx, AV_LOG_ERROR, "Could not enumerate %s devices.\n",
251 while (IEnumMoniker_Next(classenum, 1, &m, NULL) == S_OK && !device_filter) {
252 IPropertyBag *bag = NULL;
256 r = IMoniker_BindToStorage(m, 0, 0, &IID_IPropertyBag, (void *) &bag);
261 r = IPropertyBag_Read(bag, L"FriendlyName", &var, NULL);
265 buf = dup_wchar_to_utf8(var.bstrVal);
268 if (strcmp(device_name, buf))
271 IMoniker_BindToObject(m, 0, 0, &IID_IBaseFilter, (void *) &device_filter);
273 av_log(avctx, AV_LOG_INFO, " \"%s\"\n", buf);
280 IPropertyBag_Release(bag);
284 IEnumMoniker_Release(classenum);
287 if (!device_filter) {
288 av_log(avctx, AV_LOG_ERROR, "Could not find %s device.\n",
292 *pfilter = device_filter;
299 dshow_open_device(AVFormatContext *avctx, ICreateDevEnum *devenum,
300 enum dshowDeviceType devtype)
302 struct dshow_ctx *ctx = avctx->priv_data;
303 IBaseFilter *device_filter = NULL;
304 IGraphBuilder *graph = ctx->graph;
306 IPin *device_pin = NULL;
307 libAVPin *capture_pin = NULL;
308 libAVFilter *capture_filter = NULL;
309 int ret = AVERROR(EIO);
313 const GUID *mediatype[2] = { &MEDIATYPE_Video, &MEDIATYPE_Audio };
314 const char *devtypename = (devtype == VideoDevice) ? "video" : "audio";
315 const wchar_t *filter_name[2] = { L"Audio capture filter", L"Video capture filter" };
317 if ((r = dshow_cycle_devices(avctx, devenum, devtype, &device_filter)) < 0) {
322 ctx->device_filter [devtype] = device_filter;
324 r = IGraphBuilder_AddFilter(graph, device_filter, NULL);
326 av_log(avctx, AV_LOG_ERROR, "Could not add device filter to graph.\n");
330 r = IBaseFilter_EnumPins(device_filter, &pins);
332 av_log(avctx, AV_LOG_ERROR, "Could not enumerate pins.\n");
336 while (IEnumPins_Next(pins, 1, &pin, NULL) == S_OK && !device_pin) {
337 IKsPropertySet *p = NULL;
338 IEnumMediaTypes *types;
344 IPin_QueryPinInfo(pin, &info);
345 IBaseFilter_Release(info.pFilter);
347 if (info.dir != PINDIR_OUTPUT)
349 if (IPin_QueryInterface(pin, &IID_IKsPropertySet, (void **) &p) != S_OK)
351 if (IKsPropertySet_Get(p, &ROPSETID_Pin, AMPROPERTY_PIN_CATEGORY,
352 NULL, 0, &category, sizeof(GUID), &r2) != S_OK)
354 if (!IsEqualGUID(&category, &PIN_CATEGORY_CAPTURE))
357 if (IPin_EnumMediaTypes(pin, &types) != S_OK)
360 IEnumMediaTypes_Reset(types);
361 while (IEnumMediaTypes_Next(types, 1, &type, NULL) == S_OK && !device_pin) {
362 if (IsEqualGUID(&type->majortype, mediatype[devtype])) {
371 IEnumMediaTypes_Release(types);
373 IKsPropertySet_Release(p);
374 if (device_pin != pin)
379 av_log(avctx, AV_LOG_ERROR,
380 "Could not find output pin from %s capture device.\n", devtypename);
383 ctx->device_pin[devtype] = device_pin;
385 capture_filter = libAVFilter_Create(avctx, callback, devtype);
386 if (!capture_filter) {
387 av_log(avctx, AV_LOG_ERROR, "Could not create grabber filter.\n");
390 ctx->capture_filter[devtype] = capture_filter;
392 r = IGraphBuilder_AddFilter(graph, (IBaseFilter *) capture_filter,
393 filter_name[devtype]);
395 av_log(avctx, AV_LOG_ERROR, "Could not add capture filter to graph\n");
399 libAVPin_AddRef(capture_filter->pin);
400 capture_pin = capture_filter->pin;
401 ctx->capture_pin[devtype] = capture_pin;
403 r = IGraphBuilder_ConnectDirect(graph, device_pin, (IPin *) capture_pin, NULL);
405 av_log(avctx, AV_LOG_ERROR, "Could not connect pins\n");
413 IEnumPins_Release(pins);
418 static enum CodecID waveform_codec_id(enum AVSampleFormat sample_fmt)
420 switch (sample_fmt) {
421 case AV_SAMPLE_FMT_U8: return CODEC_ID_PCM_U8;
422 case AV_SAMPLE_FMT_S16: return CODEC_ID_PCM_S16LE;
423 case AV_SAMPLE_FMT_S32: return CODEC_ID_PCM_S32LE;
424 default: return CODEC_ID_NONE; /* Should never happen. */
428 static enum SampleFormat sample_fmt_bits_per_sample(int bits)
431 case 8: return AV_SAMPLE_FMT_U8;
432 case 16: return AV_SAMPLE_FMT_S16;
433 case 32: return AV_SAMPLE_FMT_S32;
434 default: return AV_SAMPLE_FMT_NONE; /* Should never happen. */
439 dshow_add_device(AVFormatContext *avctx, AVFormatParameters *ap,
440 enum dshowDeviceType devtype)
442 struct dshow_ctx *ctx = avctx->priv_data;
444 AVCodecContext *codec;
446 int ret = AVERROR(EIO);
448 st = av_new_stream(avctx, devtype);
450 ret = AVERROR(ENOMEM);
454 ctx->capture_filter[devtype]->stream_index = st->index;
456 libAVPin_ConnectionMediaType(ctx->capture_pin[devtype], &type);
459 if (devtype == VideoDevice) {
460 BITMAPINFOHEADER *bih = NULL;
462 if (IsEqualGUID(&type.formattype, &FORMAT_VideoInfo)) {
463 VIDEOINFOHEADER *v = (void *) type.pbFormat;
465 } else if (IsEqualGUID(&type.formattype, &FORMAT_VideoInfo2)) {
466 VIDEOINFOHEADER2 *v = (void *) type.pbFormat;
470 av_log(avctx, AV_LOG_ERROR, "Could not get media type.\n");
474 codec->time_base = ap->time_base;
475 codec->codec_type = AVMEDIA_TYPE_VIDEO;
476 codec->width = bih->biWidth;
477 codec->height = bih->biHeight;
478 codec->pix_fmt = dshow_pixfmt(bih->biCompression, bih->biBitCount);
479 if (codec->pix_fmt == PIX_FMT_NONE) {
480 codec->codec_id = dshow_codecid(bih->biCompression);
481 if (codec->codec_id == CODEC_ID_NONE) {
482 av_log(avctx, AV_LOG_ERROR, "Unknown compression type. "
483 "Please report verbose (-v 9) debug information.\n");
484 dshow_read_close(avctx);
485 return AVERROR_PATCHWELCOME;
487 codec->bits_per_coded_sample = bih->biBitCount;
489 codec->codec_id = CODEC_ID_RAWVIDEO;
490 if (bih->biCompression == BI_RGB) {
491 codec->bits_per_coded_sample = bih->biBitCount;
492 codec->extradata = av_malloc(9 + FF_INPUT_BUFFER_PADDING_SIZE);
493 if (codec->extradata) {
494 codec->extradata_size = 9;
495 memcpy(codec->extradata, "BottomUp", 9);
500 WAVEFORMATEX *fx = NULL;
502 if (IsEqualGUID(&type.formattype, &FORMAT_WaveFormatEx)) {
503 fx = (void *) type.pbFormat;
506 av_log(avctx, AV_LOG_ERROR, "Could not get media type.\n");
510 codec->codec_type = AVMEDIA_TYPE_AUDIO;
511 codec->sample_fmt = sample_fmt_bits_per_sample(fx->wBitsPerSample);
512 codec->codec_id = waveform_codec_id(codec->sample_fmt);
513 codec->sample_rate = fx->nSamplesPerSec;
514 codec->channels = fx->nChannels;
517 av_set_pts_info(st, 64, 1, 10000000);
525 static int parse_device_name(AVFormatContext *avctx)
527 struct dshow_ctx *ctx = avctx->priv_data;
528 char **device_name = ctx->device_name;
529 char *name = av_strdup(avctx->filename);
534 while ((type = strtok(tmp, "="))) {
535 char *token = strtok(NULL, ":");
538 if (!strcmp(type, "video")) {
539 device_name[0] = token;
540 } else if (!strcmp(type, "audio")) {
541 device_name[1] = token;
543 device_name[0] = NULL;
544 device_name[1] = NULL;
549 if (!device_name[0] && !device_name[1]) {
553 device_name[0] = av_strdup(device_name[0]);
555 device_name[1] = av_strdup(device_name[1]);
562 static int dshow_read_header(AVFormatContext *avctx, AVFormatParameters *ap)
564 struct dshow_ctx *ctx = avctx->priv_data;
565 IGraphBuilder *graph = NULL;
566 ICreateDevEnum *devenum = NULL;
567 IMediaControl *control = NULL;
568 int ret = AVERROR(EIO);
571 if (!ctx->list_devices && !parse_device_name(avctx)) {
572 av_log(avctx, AV_LOG_ERROR, "Malformed dshow input string.\n");
578 r = CoCreateInstance(&CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
579 &IID_IGraphBuilder, (void **) &graph);
581 av_log(avctx, AV_LOG_ERROR, "Could not create capture graph.\n");
586 r = CoCreateInstance(&CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
587 &IID_ICreateDevEnum, (void **) &devenum);
589 av_log(avctx, AV_LOG_ERROR, "Could not enumerate system devices.\n");
593 if (ctx->list_devices) {
594 av_log(avctx, AV_LOG_INFO, "DirectShow video devices\n");
595 dshow_cycle_devices(avctx, devenum, VideoDevice, NULL);
596 av_log(avctx, AV_LOG_INFO, "DirectShow audio devices\n");
597 dshow_cycle_devices(avctx, devenum, AudioDevice, NULL);
602 if (ctx->device_name[VideoDevice]) {
603 ret = dshow_open_device(avctx, devenum, VideoDevice);
606 ret = dshow_add_device(avctx, ap, VideoDevice);
610 if (ctx->device_name[AudioDevice]) {
611 ret = dshow_open_device(avctx, devenum, AudioDevice);
614 ret = dshow_add_device(avctx, ap, AudioDevice);
619 ctx->mutex = CreateMutex(NULL, 0, NULL);
621 av_log(avctx, AV_LOG_ERROR, "Could not create Mutex\n");
624 ctx->event = CreateEvent(NULL, 1, 0, NULL);
626 av_log(avctx, AV_LOG_ERROR, "Could not create Event\n");
630 r = IGraphBuilder_QueryInterface(graph, &IID_IMediaControl, (void **) &control);
632 av_log(avctx, AV_LOG_ERROR, "Could not get media control.\n");
635 ctx->control = control;
637 r = IMediaControl_Run(control);
640 r = IMediaControl_GetState(control, 0, &pfs);
643 av_log(avctx, AV_LOG_ERROR, "Could not run filter\n");
652 dshow_read_close(avctx);
655 ICreateDevEnum_Release(devenum);
660 static int dshow_read_packet(AVFormatContext *s, AVPacket *pkt)
662 struct dshow_ctx *ctx = s->priv_data;
663 AVPacketList *pktl = NULL;
666 WaitForSingleObject(ctx->mutex, INFINITE);
669 *pkt = ctx->pktl->pkt;
670 ctx->pktl = ctx->pktl->next;
673 ResetEvent(ctx->event);
674 ReleaseMutex(ctx->mutex);
676 if (s->flags & AVFMT_FLAG_NONBLOCK) {
677 return AVERROR(EAGAIN);
679 WaitForSingleObject(ctx->event, INFINITE);
684 ctx->curbufsize -= pkt->size;
689 #define OFFSET(x) offsetof(struct dshow_ctx, x)
690 #define DEC AV_OPT_FLAG_DECODING_PARAM
691 static const AVOption options[] = {
692 { "list_devices", "list available devices", OFFSET(list_devices), FF_OPT_TYPE_INT, {.dbl=0}, 0, 1, DEC, "list_devices" },
693 { "true", "", 0, FF_OPT_TYPE_CONST, {.dbl=1}, 0, 0, DEC, "list_devices" },
694 { "false", "", 0, FF_OPT_TYPE_CONST, {.dbl=0}, 0, 0, DEC, "list_devices" },
698 static const AVClass dshow_class = {
699 .class_name = "DirectShow indev",
700 .item_name = av_default_item_name,
702 .version = LIBAVUTIL_VERSION_INT,
705 AVInputFormat ff_dshow_demuxer = {
707 NULL_IF_CONFIG_SMALL("DirectShow capture"),
708 sizeof(struct dshow_ctx),
713 .flags = AVFMT_NOFILE,
714 .priv_class = &dshow_class,