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
30 IBaseFilter *device_filter[2];
32 libAVFilter *capture_filter[2];
33 libAVPin *capture_pin[2];
39 unsigned int curbufsize;
40 unsigned int video_frame_num;
42 IMediaControl *control;
45 static enum PixelFormat dshow_pixfmt(DWORD biCompression, WORD biBitCount)
47 switch(biCompression) {
48 case MKTAG('U', 'Y', 'V', 'Y'):
49 return PIX_FMT_UYVY422;
50 case MKTAG('Y', 'U', 'Y', '2'):
51 return PIX_FMT_YUYV422;
52 case MKTAG('I', '4', '2', '0'):
53 return PIX_FMT_YUV420P;
55 switch(biBitCount) { /* 1-8 are untested */
57 return PIX_FMT_MONOWHITE;
63 return PIX_FMT_RGB555;
73 static enum CodecID dshow_codecid(DWORD biCompression)
75 switch(biCompression) {
76 case MKTAG('d', 'v', 's', 'd'):
77 return CODEC_ID_DVVIDEO;
78 case MKTAG('M', 'J', 'P', 'G'):
79 case MKTAG('m', 'j', 'p', 'g'):
80 return CODEC_ID_MJPEG;
86 dshow_read_close(AVFormatContext *s)
88 struct dshow_ctx *ctx = s->priv_data;
92 IMediaControl_Stop(ctx->control);
93 IMediaControl_Release(ctx->control);
96 if (ctx->capture_pin[VideoDevice])
97 libAVPin_Release(ctx->capture_pin[VideoDevice]);
98 if (ctx->capture_pin[AudioDevice])
99 libAVPin_Release(ctx->capture_pin[AudioDevice]);
100 if (ctx->capture_filter[VideoDevice])
101 libAVFilter_Release(ctx->capture_filter[VideoDevice]);
102 if (ctx->capture_filter[AudioDevice])
103 libAVFilter_Release(ctx->capture_filter[AudioDevice]);
105 if (ctx->device_pin[VideoDevice])
106 IPin_Release(ctx->device_pin[VideoDevice]);
107 if (ctx->device_pin[AudioDevice])
108 IPin_Release(ctx->device_pin[AudioDevice]);
109 if (ctx->device_filter[VideoDevice])
110 IBaseFilter_Release(ctx->device_filter[VideoDevice]);
111 if (ctx->device_filter[AudioDevice])
112 IBaseFilter_Release(ctx->device_filter[AudioDevice]);
117 r = IGraphBuilder_EnumFilters(ctx->graph, &fenum);
120 IEnumFilters_Reset(fenum);
121 while (IEnumFilters_Next(fenum, 1, &f, NULL) == S_OK)
122 IGraphBuilder_RemoveFilter(ctx->graph, f);
123 IEnumFilters_Release(fenum);
125 IGraphBuilder_Release(ctx->graph);
128 if (ctx->device_name[0])
129 av_free(ctx->device_name[0]);
130 if (ctx->device_name[1])
131 av_free(ctx->device_name[1]);
134 CloseHandle(ctx->mutex);
136 CloseHandle(ctx->event);
140 AVPacketList *next = pktl->next;
141 av_destruct_packet(&pktl->pkt);
149 static char *dup_wchar_to_utf8(wchar_t *w)
152 int l = WideCharToMultiByte(CP_UTF8, 0, w, -1, 0, 0, 0, 0);
155 WideCharToMultiByte(CP_UTF8, 0, w, -1, s, l, 0, 0);
159 static int shall_we_drop(AVFormatContext *s)
161 struct dshow_ctx *ctx = s->priv_data;
162 const uint8_t dropscore[] = {62, 75, 87, 100};
163 const int ndropscores = FF_ARRAY_ELEMS(dropscore);
164 unsigned int buffer_fullness = (ctx->curbufsize*100)/s->max_picture_buffer;
166 if(dropscore[++ctx->video_frame_num%ndropscores] <= buffer_fullness) {
167 av_log(s, AV_LOG_ERROR,
168 "real-time buffer %d%% full! frame dropped!\n", buffer_fullness);
176 callback(void *priv_data, int index, uint8_t *buf, int buf_size, int64_t time)
178 AVFormatContext *s = priv_data;
179 struct dshow_ctx *ctx = s->priv_data;
180 AVPacketList **ppktl, *pktl_next;
182 // dump_videohdr(s, vdhdr);
187 WaitForSingleObject(ctx->mutex, INFINITE);
189 pktl_next = av_mallocz(sizeof(AVPacketList));
193 if(av_new_packet(&pktl_next->pkt, buf_size) < 0) {
198 pktl_next->pkt.stream_index = index;
199 pktl_next->pkt.pts = time;
200 memcpy(pktl_next->pkt.data, buf, buf_size);
202 for(ppktl = &ctx->pktl ; *ppktl ; ppktl = &(*ppktl)->next);
205 ctx->curbufsize += buf_size;
207 SetEvent(ctx->event);
208 ReleaseMutex(ctx->mutex);
212 ReleaseMutex(ctx->mutex);
217 dshow_open_device(AVFormatContext *avctx, ICreateDevEnum *devenum,
218 enum dshowDeviceType devtype)
220 struct dshow_ctx *ctx = avctx->priv_data;
221 IBaseFilter *device_filter = NULL;
222 IEnumMoniker *classenum = NULL;
223 IGraphBuilder *graph = ctx->graph;
226 IPin *device_pin = NULL;
227 libAVPin *capture_pin = NULL;
228 libAVFilter *capture_filter = NULL;
229 const char *device_name = ctx->device_name[devtype];
230 int ret = AVERROR(EIO);
234 const GUID *device_guid[2] = { &CLSID_VideoInputDeviceCategory,
235 &CLSID_AudioInputDeviceCategory };
236 const GUID *mediatype[2] = { &MEDIATYPE_Video, &MEDIATYPE_Audio };
237 const char *devtypename = (devtype == VideoDevice) ? "video" : "audio";
238 const wchar_t *filter_name[2] = { L"Audio capture filter", L"Video capture filter" };
240 r = ICreateDevEnum_CreateClassEnumerator(devenum, device_guid[devtype],
241 (IEnumMoniker **) &classenum, 0);
243 av_log(avctx, AV_LOG_ERROR, "Could not enumerate %s devices.\n",
248 while (IEnumMoniker_Next(classenum, 1, &m, NULL) == S_OK && !device_filter) {
249 IPropertyBag *bag = NULL;
253 r = IMoniker_BindToStorage(m, 0, 0, &IID_IPropertyBag, (void *) &bag);
258 r = IPropertyBag_Read(bag, L"FriendlyName", &var, NULL);
262 buf = dup_wchar_to_utf8(var.bstrVal);
264 if (strcmp(device_name, buf))
267 IMoniker_BindToObject(m, 0, 0, &IID_IBaseFilter, (void *) &device_filter);
273 IPropertyBag_Release(bag);
277 if (!device_filter) {
278 av_log(avctx, AV_LOG_ERROR, "Could not find %s device.\n",
282 ctx->device_filter [devtype] = device_filter;
284 r = IGraphBuilder_AddFilter(graph, device_filter, NULL);
286 av_log(avctx, AV_LOG_ERROR, "Could not add device filter to graph.\n");
290 r = IBaseFilter_EnumPins(device_filter, &pins);
292 av_log(avctx, AV_LOG_ERROR, "Could not enumerate pins.\n");
296 while (IEnumPins_Next(pins, 1, &pin, NULL) == S_OK && !device_pin) {
297 IKsPropertySet *p = NULL;
298 IEnumMediaTypes *types;
304 IPin_QueryPinInfo(pin, &info);
305 IBaseFilter_Release(info.pFilter);
307 if (info.dir != PINDIR_OUTPUT)
309 if (IPin_QueryInterface(pin, &IID_IKsPropertySet, (void **) &p) != S_OK)
311 if (IKsPropertySet_Get(p, &ROPSETID_Pin, AMPROPERTY_PIN_CATEGORY,
312 NULL, 0, &category, sizeof(GUID), &r2) != S_OK)
314 if (!IsEqualGUID(&category, &PIN_CATEGORY_CAPTURE))
317 if (IPin_EnumMediaTypes(pin, &types) != S_OK)
320 IEnumMediaTypes_Reset(types);
321 while (IEnumMediaTypes_Next(types, 1, &type, NULL) == S_OK && !device_pin) {
322 if (IsEqualGUID(&type->majortype, mediatype[devtype])) {
331 IEnumMediaTypes_Release(types);
333 IKsPropertySet_Release(p);
334 if (device_pin != pin)
339 av_log(avctx, AV_LOG_ERROR,
340 "Could not find output pin from %s capture device.\n", devtypename);
343 ctx->device_pin[devtype] = device_pin;
345 capture_filter = libAVFilter_Create(avctx, callback, devtype);
346 if (!capture_filter) {
347 av_log(avctx, AV_LOG_ERROR, "Could not create grabber filter.\n");
350 ctx->capture_filter[devtype] = capture_filter;
352 r = IGraphBuilder_AddFilter(graph, (IBaseFilter *) capture_filter,
353 filter_name[devtype]);
355 av_log(avctx, AV_LOG_ERROR, "Could not add capture filter to graph\n");
359 libAVPin_AddRef(capture_filter->pin);
360 capture_pin = capture_filter->pin;
361 ctx->capture_pin[devtype] = capture_pin;
363 r = IGraphBuilder_ConnectDirect(graph, device_pin, (IPin *) capture_pin, NULL);
365 av_log(avctx, AV_LOG_ERROR, "Could not connect pins\n");
373 IEnumPins_Release(pins);
375 IEnumMoniker_Release(classenum);
380 static enum CodecID waveform_codec_id(enum AVSampleFormat sample_fmt)
382 switch (sample_fmt) {
383 case AV_SAMPLE_FMT_U8: return CODEC_ID_PCM_U8;
384 case AV_SAMPLE_FMT_S16: return CODEC_ID_PCM_S16LE;
385 case AV_SAMPLE_FMT_S32: return CODEC_ID_PCM_S32LE;
386 default: return CODEC_ID_NONE; /* Should never happen. */
390 static enum SampleFormat sample_fmt_bits_per_sample(int bits)
393 case 8: return AV_SAMPLE_FMT_U8;
394 case 16: return AV_SAMPLE_FMT_S16;
395 case 32: return AV_SAMPLE_FMT_S32;
396 default: return AV_SAMPLE_FMT_NONE; /* Should never happen. */
401 dshow_add_device(AVFormatContext *avctx, AVFormatParameters *ap,
402 enum dshowDeviceType devtype)
404 struct dshow_ctx *ctx = avctx->priv_data;
406 AVCodecContext *codec;
408 int ret = AVERROR(EIO);
410 st = av_new_stream(avctx, devtype);
412 ret = AVERROR(ENOMEM);
416 ctx->capture_filter[devtype]->stream_index = st->index;
418 libAVPin_ConnectionMediaType(ctx->capture_pin[devtype], &type);
421 if (devtype == VideoDevice) {
422 BITMAPINFOHEADER *bih = NULL;
424 if (IsEqualGUID(&type.formattype, &FORMAT_VideoInfo)) {
425 VIDEOINFOHEADER *v = (void *) type.pbFormat;
427 } else if (IsEqualGUID(&type.formattype, &FORMAT_VideoInfo2)) {
428 VIDEOINFOHEADER2 *v = (void *) type.pbFormat;
432 av_log(avctx, AV_LOG_ERROR, "Could not get media type.\n");
436 codec->time_base = ap->time_base;
437 codec->codec_type = AVMEDIA_TYPE_VIDEO;
438 codec->width = bih->biWidth;
439 codec->height = bih->biHeight;
440 codec->pix_fmt = dshow_pixfmt(bih->biCompression, bih->biBitCount);
441 if (codec->pix_fmt == PIX_FMT_NONE) {
442 codec->codec_id = dshow_codecid(bih->biCompression);
443 if (codec->codec_id == CODEC_ID_NONE) {
444 av_log(avctx, AV_LOG_ERROR, "Unknown compression type. "
445 "Please report verbose (-v 9) debug information.\n");
446 dshow_read_close(avctx);
447 return AVERROR_PATCHWELCOME;
449 codec->bits_per_coded_sample = bih->biBitCount;
451 codec->codec_id = CODEC_ID_RAWVIDEO;
452 if (bih->biCompression == BI_RGB) {
453 codec->bits_per_coded_sample = bih->biBitCount;
454 codec->extradata = av_malloc(9 + FF_INPUT_BUFFER_PADDING_SIZE);
455 if (codec->extradata) {
456 codec->extradata_size = 9;
457 memcpy(codec->extradata, "BottomUp", 9);
462 WAVEFORMATEX *fx = NULL;
464 if (IsEqualGUID(&type.formattype, &FORMAT_WaveFormatEx)) {
465 fx = (void *) type.pbFormat;
468 av_log(avctx, AV_LOG_ERROR, "Could not get media type.\n");
472 codec->codec_type = AVMEDIA_TYPE_AUDIO;
473 codec->sample_fmt = sample_fmt_bits_per_sample(fx->wBitsPerSample);
474 codec->codec_id = waveform_codec_id(codec->sample_fmt);
475 codec->sample_rate = fx->nSamplesPerSec;
476 codec->channels = fx->nChannels;
479 av_set_pts_info(st, 64, 1, 10000000);
487 static int parse_device_name(AVFormatContext *avctx)
489 struct dshow_ctx *ctx = avctx->priv_data;
490 char **device_name = ctx->device_name;
491 char *name = av_strdup(avctx->filename);
496 while ((type = strtok(tmp, "="))) {
497 char *token = strtok(NULL, ":");
500 if (!strcmp(type, "video")) {
501 device_name[0] = token;
502 } else if (!strcmp(type, "audio")) {
503 device_name[1] = token;
505 device_name[0] = NULL;
506 device_name[1] = NULL;
511 if (!device_name[0] && !device_name[1]) {
515 device_name[0] = av_strdup(device_name[0]);
517 device_name[1] = av_strdup(device_name[1]);
524 static int dshow_read_header(AVFormatContext *avctx, AVFormatParameters *ap)
526 struct dshow_ctx *ctx = avctx->priv_data;
527 IGraphBuilder *graph = NULL;
528 ICreateDevEnum *devenum = NULL;
529 IMediaControl *control = NULL;
530 int ret = AVERROR(EIO);
533 if (!parse_device_name(avctx)) {
534 av_log(avctx, AV_LOG_ERROR, "Malformed dshow input string.\n");
540 r = CoCreateInstance(&CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
541 &IID_IGraphBuilder, (void **) &graph);
543 av_log(avctx, AV_LOG_ERROR, "Could not create capture graph.\n");
548 r = CoCreateInstance(&CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
549 &IID_ICreateDevEnum, (void **) &devenum);
551 av_log(avctx, AV_LOG_ERROR, "Could not enumerate system devices.\n");
555 if (ctx->device_name[VideoDevice]) {
556 ret = dshow_open_device(avctx, devenum, VideoDevice);
559 ret = dshow_add_device(avctx, ap, VideoDevice);
563 if (ctx->device_name[AudioDevice]) {
564 ret = dshow_open_device(avctx, devenum, AudioDevice);
567 ret = dshow_add_device(avctx, ap, AudioDevice);
572 ctx->mutex = CreateMutex(NULL, 0, NULL);
574 av_log(avctx, AV_LOG_ERROR, "Could not create Mutex\n");
577 ctx->event = CreateEvent(NULL, 1, 0, NULL);
579 av_log(avctx, AV_LOG_ERROR, "Could not create Event\n");
583 r = IGraphBuilder_QueryInterface(graph, &IID_IMediaControl, (void **) &control);
585 av_log(avctx, AV_LOG_ERROR, "Could not get media control.\n");
588 ctx->control = control;
590 r = IMediaControl_Run(control);
593 r = IMediaControl_GetState(control, 0, &pfs);
596 av_log(avctx, AV_LOG_ERROR, "Could not run filter\n");
605 dshow_read_close(avctx);
608 ICreateDevEnum_Release(devenum);
613 static int dshow_read_packet(AVFormatContext *s, AVPacket *pkt)
615 struct dshow_ctx *ctx = s->priv_data;
616 AVPacketList *pktl = NULL;
619 WaitForSingleObject(ctx->mutex, INFINITE);
622 *pkt = ctx->pktl->pkt;
623 ctx->pktl = ctx->pktl->next;
626 ResetEvent(ctx->event);
627 ReleaseMutex(ctx->mutex);
629 if (s->flags & AVFMT_FLAG_NONBLOCK) {
630 return AVERROR(EAGAIN);
632 WaitForSingleObject(ctx->event, INFINITE);
637 ctx->curbufsize -= pkt->size;
642 AVInputFormat ff_dshow_demuxer = {
644 NULL_IF_CONFIG_SMALL("DirectShow capture"),
645 sizeof(struct dshow_ctx),
650 .flags = AVFMT_NOFILE,