]> git.sesse.net Git - ffmpeg/blob - libavdevice/dshow.c
dshow: add option to list audio/video options
[ffmpeg] / libavdevice / dshow.c
1 /*
2  * Directshow capture interface
3  * Copyright (c) 2010 Ramiro Polla
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 #include "libavutil/parseutils.h"
23 #include "libavutil/opt.h"
24
25 #include "avdevice.h"
26 #include "dshow.h"
27
28 struct dshow_ctx {
29     const AVClass *class;
30
31     IGraphBuilder *graph;
32
33     char *device_name[2];
34
35     int   list_options;
36     int   list_devices;
37
38     IBaseFilter *device_filter[2];
39     IPin        *device_pin[2];
40     libAVFilter *capture_filter[2];
41     libAVPin    *capture_pin[2];
42
43     HANDLE mutex;
44     HANDLE event;
45     AVPacketList *pktl;
46
47     unsigned int curbufsize;
48     unsigned int video_frame_num;
49
50     IMediaControl *control;
51
52     char *video_size;
53     char *framerate;
54
55     int requested_width;
56     int requested_height;
57     AVRational requested_framerate;
58
59     int sample_rate;
60     int sample_size;
61     int channels;
62 };
63
64 static enum PixelFormat dshow_pixfmt(DWORD biCompression, WORD biBitCount)
65 {
66     switch(biCompression) {
67     case MKTAG('U', 'Y', 'V', 'Y'):
68         return PIX_FMT_UYVY422;
69     case MKTAG('Y', 'U', 'Y', '2'):
70         return PIX_FMT_YUYV422;
71     case MKTAG('I', '4', '2', '0'):
72         return PIX_FMT_YUV420P;
73     case BI_RGB:
74         switch(biBitCount) { /* 1-8 are untested */
75             case 1:
76                 return PIX_FMT_MONOWHITE;
77             case 4:
78                 return PIX_FMT_RGB4;
79             case 8:
80                 return PIX_FMT_RGB8;
81             case 16:
82                 return PIX_FMT_RGB555;
83             case 24:
84                 return PIX_FMT_BGR24;
85             case 32:
86                 return PIX_FMT_RGB32;
87         }
88     }
89     return PIX_FMT_NONE;
90 }
91
92 static enum CodecID dshow_codecid(DWORD biCompression)
93 {
94     switch(biCompression) {
95     case MKTAG('d', 'v', 's', 'd'):
96         return CODEC_ID_DVVIDEO;
97     case MKTAG('M', 'J', 'P', 'G'):
98     case MKTAG('m', 'j', 'p', 'g'):
99         return CODEC_ID_MJPEG;
100     }
101     return CODEC_ID_NONE;
102 }
103
104 static int
105 dshow_read_close(AVFormatContext *s)
106 {
107     struct dshow_ctx *ctx = s->priv_data;
108     AVPacketList *pktl;
109
110     if (ctx->control) {
111         IMediaControl_Stop(ctx->control);
112         IMediaControl_Release(ctx->control);
113     }
114
115     if (ctx->capture_pin[VideoDevice])
116         libAVPin_Release(ctx->capture_pin[VideoDevice]);
117     if (ctx->capture_pin[AudioDevice])
118         libAVPin_Release(ctx->capture_pin[AudioDevice]);
119     if (ctx->capture_filter[VideoDevice])
120         libAVFilter_Release(ctx->capture_filter[VideoDevice]);
121     if (ctx->capture_filter[AudioDevice])
122         libAVFilter_Release(ctx->capture_filter[AudioDevice]);
123
124     if (ctx->device_pin[VideoDevice])
125         IPin_Release(ctx->device_pin[VideoDevice]);
126     if (ctx->device_pin[AudioDevice])
127         IPin_Release(ctx->device_pin[AudioDevice]);
128     if (ctx->device_filter[VideoDevice])
129         IBaseFilter_Release(ctx->device_filter[VideoDevice]);
130     if (ctx->device_filter[AudioDevice])
131         IBaseFilter_Release(ctx->device_filter[AudioDevice]);
132
133     if (ctx->graph) {
134         IEnumFilters *fenum;
135         int r;
136         r = IGraphBuilder_EnumFilters(ctx->graph, &fenum);
137         if (r == S_OK) {
138             IBaseFilter *f;
139             IEnumFilters_Reset(fenum);
140             while (IEnumFilters_Next(fenum, 1, &f, NULL) == S_OK)
141                 IGraphBuilder_RemoveFilter(ctx->graph, f);
142             IEnumFilters_Release(fenum);
143         }
144         IGraphBuilder_Release(ctx->graph);
145     }
146
147     if (ctx->device_name[0])
148         av_free(ctx->device_name[0]);
149     if (ctx->device_name[1])
150         av_free(ctx->device_name[1]);
151
152     if(ctx->mutex)
153         CloseHandle(ctx->mutex);
154     if(ctx->event)
155         CloseHandle(ctx->event);
156
157     pktl = ctx->pktl;
158     while (pktl) {
159         AVPacketList *next = pktl->next;
160         av_destruct_packet(&pktl->pkt);
161         av_free(pktl);
162         pktl = next;
163     }
164
165     return 0;
166 }
167
168 static char *dup_wchar_to_utf8(wchar_t *w)
169 {
170     char *s = NULL;
171     int l = WideCharToMultiByte(CP_UTF8, 0, w, -1, 0, 0, 0, 0);
172     s = av_malloc(l);
173     if (s)
174         WideCharToMultiByte(CP_UTF8, 0, w, -1, s, l, 0, 0);
175     return s;
176 }
177
178 static int shall_we_drop(AVFormatContext *s)
179 {
180     struct dshow_ctx *ctx = s->priv_data;
181     const uint8_t dropscore[] = {62, 75, 87, 100};
182     const int ndropscores = FF_ARRAY_ELEMS(dropscore);
183     unsigned int buffer_fullness = (ctx->curbufsize*100)/s->max_picture_buffer;
184
185     if(dropscore[++ctx->video_frame_num%ndropscores] <= buffer_fullness) {
186         av_log(s, AV_LOG_ERROR,
187               "real-time buffer %d%% full! frame dropped!\n", buffer_fullness);
188         return 1;
189     }
190
191     return 0;
192 }
193
194 static void
195 callback(void *priv_data, int index, uint8_t *buf, int buf_size, int64_t time)
196 {
197     AVFormatContext *s = priv_data;
198     struct dshow_ctx *ctx = s->priv_data;
199     AVPacketList **ppktl, *pktl_next;
200
201 //    dump_videohdr(s, vdhdr);
202
203     if(shall_we_drop(s))
204         return;
205
206     WaitForSingleObject(ctx->mutex, INFINITE);
207
208     pktl_next = av_mallocz(sizeof(AVPacketList));
209     if(!pktl_next)
210         goto fail;
211
212     if(av_new_packet(&pktl_next->pkt, buf_size) < 0) {
213         av_free(pktl_next);
214         goto fail;
215     }
216
217     pktl_next->pkt.stream_index = index;
218     pktl_next->pkt.pts = time;
219     memcpy(pktl_next->pkt.data, buf, buf_size);
220
221     for(ppktl = &ctx->pktl ; *ppktl ; ppktl = &(*ppktl)->next);
222     *ppktl = pktl_next;
223
224     ctx->curbufsize += buf_size;
225
226     SetEvent(ctx->event);
227     ReleaseMutex(ctx->mutex);
228
229     return;
230 fail:
231     ReleaseMutex(ctx->mutex);
232     return;
233 }
234
235 /**
236  * Cycle through available devices using the device enumerator devenum,
237  * retrieve the device with type specified by devtype and return the
238  * pointer to the object found in *pfilter.
239  * If pfilter is NULL, list all device names.
240  */
241 static int
242 dshow_cycle_devices(AVFormatContext *avctx, ICreateDevEnum *devenum,
243                     enum dshowDeviceType devtype, IBaseFilter **pfilter)
244 {
245     struct dshow_ctx *ctx = avctx->priv_data;
246     IBaseFilter *device_filter = NULL;
247     IEnumMoniker *classenum = NULL;
248     IMoniker *m = NULL;
249     const char *device_name = ctx->device_name[devtype];
250     int r;
251
252     const GUID *device_guid[2] = { &CLSID_VideoInputDeviceCategory,
253                                    &CLSID_AudioInputDeviceCategory };
254     const char *devtypename = (devtype == VideoDevice) ? "video" : "audio";
255
256     r = ICreateDevEnum_CreateClassEnumerator(devenum, device_guid[devtype],
257                                              (IEnumMoniker **) &classenum, 0);
258     if (r != S_OK) {
259         av_log(avctx, AV_LOG_ERROR, "Could not enumerate %s devices.\n",
260                devtypename);
261         return AVERROR(EIO);
262     }
263
264     while (IEnumMoniker_Next(classenum, 1, &m, NULL) == S_OK && !device_filter) {
265         IPropertyBag *bag = NULL;
266         char *buf = NULL;
267         VARIANT var;
268
269         r = IMoniker_BindToStorage(m, 0, 0, &IID_IPropertyBag, (void *) &bag);
270         if (r != S_OK)
271             goto fail1;
272
273         var.vt = VT_BSTR;
274         r = IPropertyBag_Read(bag, L"FriendlyName", &var, NULL);
275         if (r != S_OK)
276             goto fail1;
277
278         buf = dup_wchar_to_utf8(var.bstrVal);
279
280         if (pfilter) {
281             if (strcmp(device_name, buf))
282                 goto fail1;
283
284             IMoniker_BindToObject(m, 0, 0, &IID_IBaseFilter, (void *) &device_filter);
285         } else {
286             av_log(avctx, AV_LOG_INFO, " \"%s\"\n", buf);
287         }
288
289 fail1:
290         if (buf)
291             av_free(buf);
292         if (bag)
293             IPropertyBag_Release(bag);
294         IMoniker_Release(m);
295     }
296
297     IEnumMoniker_Release(classenum);
298
299     if (pfilter) {
300         if (!device_filter) {
301             av_log(avctx, AV_LOG_ERROR, "Could not find %s device.\n",
302                    devtypename);
303             return AVERROR(EIO);
304         }
305         *pfilter = device_filter;
306     }
307
308     return 0;
309 }
310
311 /**
312  * Cycle through available formats using the specified pin,
313  * try to set parameters specified through AVOptions and if successful
314  * return 1 in *pformat_set.
315  * If pformat_set is NULL, list all pin capabilities.
316  */
317 static void
318 dshow_cycle_formats(AVFormatContext *avctx, enum dshowDeviceType devtype,
319                     IPin *pin, int *pformat_set)
320 {
321     struct dshow_ctx *ctx = avctx->priv_data;
322     IAMStreamConfig *config = NULL;
323     AM_MEDIA_TYPE *type = NULL;
324     int format_set = 0;
325     void *caps = NULL;
326     int i, n, size;
327
328     if (IPin_QueryInterface(pin, &IID_IAMStreamConfig, (void **) &config) != S_OK)
329         return;
330     if (IAMStreamConfig_GetNumberOfCapabilities(config, &n, &size) != S_OK)
331         goto end;
332
333     caps = av_malloc(size);
334     if (!caps)
335         goto end;
336
337     for (i = 0; i < n && !format_set; i++) {
338         IAMStreamConfig_GetStreamCaps(config, i, &type, (void *) caps);
339
340 #if DSHOWDEBUG
341         ff_print_AM_MEDIA_TYPE(type);
342 #endif
343
344         if (devtype == VideoDevice) {
345             VIDEO_STREAM_CONFIG_CAPS *vcaps = caps;
346             BITMAPINFOHEADER *bih;
347             int64_t *fr;
348 #if DSHOWDEBUG
349             ff_print_VIDEO_STREAM_CONFIG_CAPS(vcaps);
350 #endif
351             if (IsEqualGUID(&type->formattype, &FORMAT_VideoInfo)) {
352                 VIDEOINFOHEADER *v = (void *) type->pbFormat;
353                 fr = &v->AvgTimePerFrame;
354                 bih = &v->bmiHeader;
355             } else if (IsEqualGUID(&type->formattype, &FORMAT_VideoInfo2)) {
356                 VIDEOINFOHEADER2 *v = (void *) type->pbFormat;
357                 fr = &v->AvgTimePerFrame;
358                 bih = &v->bmiHeader;
359             } else {
360                 goto next;
361             }
362             if (!pformat_set) {
363                 av_log(avctx, AV_LOG_INFO, "  min s=%ldx%ld fps=%g max s=%ldx%ld fps=%g\n",
364                        vcaps->MinOutputSize.cx, vcaps->MinOutputSize.cy,
365                        1e7 / vcaps->MinFrameInterval,
366                        vcaps->MaxOutputSize.cx, vcaps->MaxOutputSize.cy,
367                        1e7 / vcaps->MaxFrameInterval);
368                 continue;
369             }
370             if (ctx->framerate) {
371                 int64_t framerate = ((int64_t) ctx->requested_framerate.den*10000000)
372                                             /  ctx->requested_framerate.num;
373                 if (framerate > vcaps->MaxFrameInterval ||
374                     framerate < vcaps->MinFrameInterval)
375                     goto next;
376                 *fr = framerate;
377             }
378             if (ctx->video_size) {
379                 if (ctx->requested_width  > vcaps->MaxOutputSize.cx ||
380                     ctx->requested_width  < vcaps->MinOutputSize.cx ||
381                     ctx->requested_height > vcaps->MaxOutputSize.cy ||
382                     ctx->requested_height < vcaps->MinOutputSize.cy)
383                     goto next;
384                 bih->biWidth  = ctx->requested_width;
385                 bih->biHeight = ctx->requested_height;
386             }
387         } else {
388             AUDIO_STREAM_CONFIG_CAPS *acaps = caps;
389             WAVEFORMATEX *fx;
390 #if DSHOWDEBUG
391             ff_print_AUDIO_STREAM_CONFIG_CAPS(acaps);
392 #endif
393             if (IsEqualGUID(&type->formattype, &FORMAT_WaveFormatEx)) {
394                 fx = (void *) type->pbFormat;
395             } else {
396                 goto next;
397             }
398             if (!pformat_set) {
399                 av_log(avctx, AV_LOG_INFO, "  min ch=%lu bits=%lu rate=%6lu max ch=%lu bits=%lu rate=%6lu\n",
400                        acaps->MinimumChannels, acaps->MinimumBitsPerSample, acaps->MinimumSampleFrequency,
401                        acaps->MaximumChannels, acaps->MaximumBitsPerSample, acaps->MaximumSampleFrequency);
402                 continue;
403             }
404             if (ctx->sample_rate) {
405                 if (ctx->sample_rate > acaps->MaximumSampleFrequency ||
406                     ctx->sample_rate < acaps->MinimumSampleFrequency)
407                     goto next;
408                 fx->nSamplesPerSec = ctx->sample_rate;
409             }
410             if (ctx->sample_size) {
411                 if (ctx->sample_size > acaps->MaximumBitsPerSample ||
412                     ctx->sample_size < acaps->MinimumBitsPerSample)
413                     goto next;
414                 fx->wBitsPerSample = ctx->sample_size;
415             }
416             if (ctx->channels) {
417                 if (ctx->channels > acaps->MaximumChannels ||
418                     ctx->channels < acaps->MinimumChannels)
419                     goto next;
420                 fx->nChannels = ctx->channels;
421             }
422         }
423         if (IAMStreamConfig_SetFormat(config, type) != S_OK)
424             goto next;
425         format_set = 1;
426 next:
427         if (type->pbFormat)
428             CoTaskMemFree(type->pbFormat);
429         CoTaskMemFree(type);
430     }
431 end:
432     IAMStreamConfig_Release(config);
433     if (caps)
434         av_free(caps);
435     if (pformat_set)
436     *pformat_set = format_set;
437 }
438
439 /**
440  * Cycle through available pins using the device_filter device, of type
441  * devtype, retrieve the first output pin and return the pointer to the
442  * object found in *ppin.
443  * If ppin is NULL, cycle through all pins listing audio/video capabilities.
444  */
445 static int
446 dshow_cycle_pins(AVFormatContext *avctx, enum dshowDeviceType devtype,
447                  IBaseFilter *device_filter, IPin **ppin)
448 {
449     struct dshow_ctx *ctx = avctx->priv_data;
450     IEnumPins *pins = 0;
451     IPin *device_pin = NULL;
452     IPin *pin;
453     int r;
454
455     const GUID *mediatype[2] = { &MEDIATYPE_Video, &MEDIATYPE_Audio };
456     const char *devtypename = (devtype == VideoDevice) ? "video" : "audio";
457
458     int set_format = (devtype == VideoDevice && (ctx->video_size || ctx->framerate))
459                   || (devtype == AudioDevice && (ctx->channels || ctx->sample_rate));
460     int format_set = 0;
461
462     r = IBaseFilter_EnumPins(device_filter, &pins);
463     if (r != S_OK) {
464         av_log(avctx, AV_LOG_ERROR, "Could not enumerate pins.\n");
465         return AVERROR(EIO);
466     }
467
468     if (!ppin) {
469         av_log(avctx, AV_LOG_INFO, "DirectShow %s device options\n",
470                devtypename);
471     }
472     while (IEnumPins_Next(pins, 1, &pin, NULL) == S_OK && !device_pin) {
473         IKsPropertySet *p = NULL;
474         IEnumMediaTypes *types = NULL;
475         PIN_INFO info = {0};
476         AM_MEDIA_TYPE *type;
477         GUID category;
478         DWORD r2;
479
480         IPin_QueryPinInfo(pin, &info);
481         IBaseFilter_Release(info.pFilter);
482
483         if (info.dir != PINDIR_OUTPUT)
484             goto next;
485         if (IPin_QueryInterface(pin, &IID_IKsPropertySet, (void **) &p) != S_OK)
486             goto next;
487         if (IKsPropertySet_Get(p, &AMPROPSETID_Pin, AMPROPERTY_PIN_CATEGORY,
488                                NULL, 0, &category, sizeof(GUID), &r2) != S_OK)
489             goto next;
490         if (!IsEqualGUID(&category, &PIN_CATEGORY_CAPTURE))
491             goto next;
492
493         if (!ppin) {
494             char *buf = dup_wchar_to_utf8(info.achName);
495             av_log(avctx, AV_LOG_INFO, " Pin \"%s\"\n", buf);
496             av_free(buf);
497             dshow_cycle_formats(avctx, devtype, pin, NULL);
498             goto next;
499         }
500         if (set_format) {
501             dshow_cycle_formats(avctx, devtype, pin, &format_set);
502             if (!format_set) {
503                 goto next;
504             }
505         }
506
507         if (IPin_EnumMediaTypes(pin, &types) != S_OK)
508             goto next;
509
510         IEnumMediaTypes_Reset(types);
511         while (IEnumMediaTypes_Next(types, 1, &type, NULL) == S_OK && !device_pin) {
512             if (IsEqualGUID(&type->majortype, mediatype[devtype])) {
513                 device_pin = pin;
514                 goto next;
515             }
516             CoTaskMemFree(type);
517         }
518
519 next:
520         if (types)
521             IEnumMediaTypes_Release(types);
522         if (p)
523             IKsPropertySet_Release(p);
524         if (device_pin != pin)
525             IPin_Release(pin);
526     }
527
528     IEnumPins_Release(pins);
529
530     if (ppin) {
531     if (set_format && !format_set) {
532         av_log(avctx, AV_LOG_ERROR, "Could not set %s options\n", devtypename);
533         return AVERROR(EIO);
534     }
535     if (!device_pin) {
536         av_log(avctx, AV_LOG_ERROR,
537                "Could not find output pin from %s capture device.\n", devtypename);
538         return AVERROR(EIO);
539     }
540     *ppin = device_pin;
541     }
542
543     return 0;
544 }
545
546 /**
547  * List options for device with type devtype.
548  *
549  * @param devenum device enumerator used for accessing the device
550  */
551 static int
552 dshow_list_device_options(AVFormatContext *avctx, ICreateDevEnum *devenum,
553                           enum dshowDeviceType devtype)
554 {
555     IBaseFilter *device_filter = NULL;
556     int r;
557
558     if ((r = dshow_cycle_devices(avctx, devenum, devtype, &device_filter)) < 0)
559         return r;
560     if ((r = dshow_cycle_pins(avctx, devtype, device_filter, NULL)) < 0)
561         return r;
562
563     return 0;
564 }
565
566 static int
567 dshow_open_device(AVFormatContext *avctx, ICreateDevEnum *devenum,
568                   enum dshowDeviceType devtype)
569 {
570     struct dshow_ctx *ctx = avctx->priv_data;
571     IBaseFilter *device_filter = NULL;
572     IGraphBuilder *graph = ctx->graph;
573     IPin *device_pin = NULL;
574     libAVPin *capture_pin = NULL;
575     libAVFilter *capture_filter = NULL;
576     int ret = AVERROR(EIO);
577     int r;
578
579     const wchar_t *filter_name[2] = { L"Audio capture filter", L"Video capture filter" };
580
581     if ((r = dshow_cycle_devices(avctx, devenum, devtype, &device_filter)) < 0) {
582         ret = r;
583         goto error;
584     }
585
586     ctx->device_filter [devtype] = device_filter;
587
588     r = IGraphBuilder_AddFilter(graph, device_filter, NULL);
589     if (r != S_OK) {
590         av_log(avctx, AV_LOG_ERROR, "Could not add device filter to graph.\n");
591         goto error;
592     }
593
594     if ((r = dshow_cycle_pins(avctx, devtype, device_filter, &device_pin)) < 0) {
595         ret = r;
596         goto error;
597     }
598     ctx->device_pin[devtype] = device_pin;
599
600     capture_filter = libAVFilter_Create(avctx, callback, devtype);
601     if (!capture_filter) {
602         av_log(avctx, AV_LOG_ERROR, "Could not create grabber filter.\n");
603         goto error;
604     }
605     ctx->capture_filter[devtype] = capture_filter;
606
607     r = IGraphBuilder_AddFilter(graph, (IBaseFilter *) capture_filter,
608                                 filter_name[devtype]);
609     if (r != S_OK) {
610         av_log(avctx, AV_LOG_ERROR, "Could not add capture filter to graph\n");
611         goto error;
612     }
613
614     libAVPin_AddRef(capture_filter->pin);
615     capture_pin = capture_filter->pin;
616     ctx->capture_pin[devtype] = capture_pin;
617
618     r = IGraphBuilder_ConnectDirect(graph, device_pin, (IPin *) capture_pin, NULL);
619     if (r != S_OK) {
620         av_log(avctx, AV_LOG_ERROR, "Could not connect pins\n");
621         goto error;
622     }
623
624     ret = 0;
625
626 error:
627     return ret;
628 }
629
630 static enum CodecID waveform_codec_id(enum AVSampleFormat sample_fmt)
631 {
632     switch (sample_fmt) {
633     case AV_SAMPLE_FMT_U8:  return CODEC_ID_PCM_U8;
634     case AV_SAMPLE_FMT_S16: return CODEC_ID_PCM_S16LE;
635     case AV_SAMPLE_FMT_S32: return CODEC_ID_PCM_S32LE;
636     default:                return CODEC_ID_NONE; /* Should never happen. */
637     }
638 }
639
640 static enum SampleFormat sample_fmt_bits_per_sample(int bits)
641 {
642     switch (bits) {
643     case 8:  return AV_SAMPLE_FMT_U8;
644     case 16: return AV_SAMPLE_FMT_S16;
645     case 32: return AV_SAMPLE_FMT_S32;
646     default: return AV_SAMPLE_FMT_NONE; /* Should never happen. */
647     }
648 }
649
650 static int
651 dshow_add_device(AVFormatContext *avctx, AVFormatParameters *ap,
652                  enum dshowDeviceType devtype)
653 {
654     struct dshow_ctx *ctx = avctx->priv_data;
655     AM_MEDIA_TYPE type;
656     AVCodecContext *codec;
657     AVStream *st;
658     int ret = AVERROR(EIO);
659
660     st = av_new_stream(avctx, devtype);
661     if (!st) {
662         ret = AVERROR(ENOMEM);
663         goto error;
664     }
665
666     ctx->capture_filter[devtype]->stream_index = st->index;
667
668     libAVPin_ConnectionMediaType(ctx->capture_pin[devtype], &type);
669
670     codec = st->codec;
671     if (devtype == VideoDevice) {
672         BITMAPINFOHEADER *bih = NULL;
673
674         if (IsEqualGUID(&type.formattype, &FORMAT_VideoInfo)) {
675             VIDEOINFOHEADER *v = (void *) type.pbFormat;
676             bih = &v->bmiHeader;
677         } else if (IsEqualGUID(&type.formattype, &FORMAT_VideoInfo2)) {
678             VIDEOINFOHEADER2 *v = (void *) type.pbFormat;
679             bih = &v->bmiHeader;
680         }
681         if (!bih) {
682             av_log(avctx, AV_LOG_ERROR, "Could not get media type.\n");
683             goto error;
684         }
685
686         codec->time_base  = ap->time_base;
687         codec->codec_type = AVMEDIA_TYPE_VIDEO;
688         codec->width      = bih->biWidth;
689         codec->height     = bih->biHeight;
690         codec->pix_fmt    = dshow_pixfmt(bih->biCompression, bih->biBitCount);
691         if (codec->pix_fmt == PIX_FMT_NONE) {
692             codec->codec_id = dshow_codecid(bih->biCompression);
693             if (codec->codec_id == CODEC_ID_NONE) {
694                 av_log(avctx, AV_LOG_ERROR, "Unknown compression type. "
695                                  "Please report verbose (-v 9) debug information.\n");
696                 dshow_read_close(avctx);
697                 return AVERROR_PATCHWELCOME;
698             }
699             codec->bits_per_coded_sample = bih->biBitCount;
700         } else {
701             codec->codec_id = CODEC_ID_RAWVIDEO;
702             if (bih->biCompression == BI_RGB) {
703                 codec->bits_per_coded_sample = bih->biBitCount;
704                 codec->extradata = av_malloc(9 + FF_INPUT_BUFFER_PADDING_SIZE);
705                 if (codec->extradata) {
706                     codec->extradata_size = 9;
707                     memcpy(codec->extradata, "BottomUp", 9);
708                 }
709             }
710         }
711     } else {
712         WAVEFORMATEX *fx = NULL;
713
714         if (IsEqualGUID(&type.formattype, &FORMAT_WaveFormatEx)) {
715             fx = (void *) type.pbFormat;
716         }
717         if (!fx) {
718             av_log(avctx, AV_LOG_ERROR, "Could not get media type.\n");
719             goto error;
720         }
721
722         codec->codec_type  = AVMEDIA_TYPE_AUDIO;
723         codec->sample_fmt  = sample_fmt_bits_per_sample(fx->wBitsPerSample);
724         codec->codec_id    = waveform_codec_id(codec->sample_fmt);
725         codec->sample_rate = fx->nSamplesPerSec;
726         codec->channels    = fx->nChannels;
727     }
728
729     av_set_pts_info(st, 64, 1, 10000000);
730
731     ret = 0;
732
733 error:
734     return ret;
735 }
736
737 static int parse_device_name(AVFormatContext *avctx)
738 {
739     struct dshow_ctx *ctx = avctx->priv_data;
740     char **device_name = ctx->device_name;
741     char *name = av_strdup(avctx->filename);
742     char *tmp = name;
743     int ret = 1;
744     char *type;
745
746     while ((type = strtok(tmp, "="))) {
747         char *token = strtok(NULL, ":");
748         tmp = NULL;
749
750         if        (!strcmp(type, "video")) {
751             device_name[0] = token;
752         } else if (!strcmp(type, "audio")) {
753             device_name[1] = token;
754         } else {
755             device_name[0] = NULL;
756             device_name[1] = NULL;
757             break;
758         }
759     }
760
761     if (!device_name[0] && !device_name[1]) {
762         ret = 0;
763     } else {
764         if (device_name[0])
765             device_name[0] = av_strdup(device_name[0]);
766         if (device_name[1])
767             device_name[1] = av_strdup(device_name[1]);
768     }
769
770     av_free(name);
771     return ret;
772 }
773
774 static int dshow_read_header(AVFormatContext *avctx, AVFormatParameters *ap)
775 {
776     struct dshow_ctx *ctx = avctx->priv_data;
777     IGraphBuilder *graph = NULL;
778     ICreateDevEnum *devenum = NULL;
779     IMediaControl *control = NULL;
780     int ret = AVERROR(EIO);
781     int r;
782
783     if (!ctx->list_devices && !parse_device_name(avctx)) {
784         av_log(avctx, AV_LOG_ERROR, "Malformed dshow input string.\n");
785         goto error;
786     }
787
788     if (ctx->video_size) {
789         r = av_parse_video_size(&ctx->requested_width, &ctx->requested_height, ctx->video_size);
790         if (r < 0) {
791             av_log(avctx, AV_LOG_ERROR, "Could not parse video size '%s'.\n", ctx->video_size);
792             goto error;
793         }
794     }
795     if (ctx->framerate) {
796         r = av_parse_video_rate(&ctx->requested_framerate, ctx->framerate);
797         if (r < 0) {
798             av_log(avctx, AV_LOG_ERROR, "Could not parse framerate '%s'.\n", ctx->framerate);
799             goto error;
800         }
801     }
802
803     CoInitialize(0);
804
805     r = CoCreateInstance(&CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
806                          &IID_IGraphBuilder, (void **) &graph);
807     if (r != S_OK) {
808         av_log(avctx, AV_LOG_ERROR, "Could not create capture graph.\n");
809         goto error;
810     }
811     ctx->graph = graph;
812
813     r = CoCreateInstance(&CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
814                          &IID_ICreateDevEnum, (void **) &devenum);
815     if (r != S_OK) {
816         av_log(avctx, AV_LOG_ERROR, "Could not enumerate system devices.\n");
817         goto error;
818     }
819
820     if (ctx->list_devices) {
821         av_log(avctx, AV_LOG_INFO, "DirectShow video devices\n");
822         dshow_cycle_devices(avctx, devenum, VideoDevice, NULL);
823         av_log(avctx, AV_LOG_INFO, "DirectShow audio devices\n");
824         dshow_cycle_devices(avctx, devenum, AudioDevice, NULL);
825         ret = AVERROR_EXIT;
826         goto error;
827     }
828     if (ctx->list_options) {
829         if (ctx->device_name[VideoDevice])
830             dshow_list_device_options(avctx, devenum, VideoDevice);
831         if (ctx->device_name[AudioDevice])
832             dshow_list_device_options(avctx, devenum, AudioDevice);
833         ret = AVERROR_EXIT;
834         goto error;
835     }
836
837     if (ctx->device_name[VideoDevice]) {
838         ret = dshow_open_device(avctx, devenum, VideoDevice);
839         if (ret < 0)
840             goto error;
841         ret = dshow_add_device(avctx, ap, VideoDevice);
842         if (ret < 0)
843             goto error;
844     }
845     if (ctx->device_name[AudioDevice]) {
846         ret = dshow_open_device(avctx, devenum, AudioDevice);
847         if (ret < 0)
848             goto error;
849         ret = dshow_add_device(avctx, ap, AudioDevice);
850         if (ret < 0)
851             goto error;
852     }
853
854     ctx->mutex = CreateMutex(NULL, 0, NULL);
855     if (!ctx->mutex) {
856         av_log(avctx, AV_LOG_ERROR, "Could not create Mutex\n");
857         goto error;
858     }
859     ctx->event = CreateEvent(NULL, 1, 0, NULL);
860     if (!ctx->event) {
861         av_log(avctx, AV_LOG_ERROR, "Could not create Event\n");
862         goto error;
863     }
864
865     r = IGraphBuilder_QueryInterface(graph, &IID_IMediaControl, (void **) &control);
866     if (r != S_OK) {
867         av_log(avctx, AV_LOG_ERROR, "Could not get media control.\n");
868         goto error;
869     }
870     ctx->control = control;
871
872     r = IMediaControl_Run(control);
873     if (r == S_FALSE) {
874         OAFilterState pfs;
875         r = IMediaControl_GetState(control, 0, &pfs);
876     }
877     if (r != S_OK) {
878         av_log(avctx, AV_LOG_ERROR, "Could not run filter\n");
879         goto error;
880     }
881
882     ret = 0;
883
884 error:
885
886     if (ret < 0)
887         dshow_read_close(avctx);
888
889     if (devenum)
890         ICreateDevEnum_Release(devenum);
891
892     return ret;
893 }
894
895 static int dshow_read_packet(AVFormatContext *s, AVPacket *pkt)
896 {
897     struct dshow_ctx *ctx = s->priv_data;
898     AVPacketList *pktl = NULL;
899
900     while (!pktl) {
901         WaitForSingleObject(ctx->mutex, INFINITE);
902         pktl = ctx->pktl;
903         if (ctx->pktl) {
904             *pkt = ctx->pktl->pkt;
905             ctx->pktl = ctx->pktl->next;
906             av_free(pktl);
907         }
908         ResetEvent(ctx->event);
909         ReleaseMutex(ctx->mutex);
910         if (!pktl) {
911             if (s->flags & AVFMT_FLAG_NONBLOCK) {
912                 return AVERROR(EAGAIN);
913             } else {
914                 WaitForSingleObject(ctx->event, INFINITE);
915             }
916         }
917     }
918
919     ctx->curbufsize -= pkt->size;
920
921     return pkt->size;
922 }
923
924 #define OFFSET(x) offsetof(struct dshow_ctx, x)
925 #define DEC AV_OPT_FLAG_DECODING_PARAM
926 static const AVOption options[] = {
927     { "video_size", "set video size given a string such as 640x480 or hd720.", OFFSET(video_size), FF_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
928     { "framerate", "set video frame rate", OFFSET(framerate), FF_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
929     { "sample_rate", "set audio sample rate", OFFSET(sample_rate), FF_OPT_TYPE_INT, {.dbl = 0}, 0, INT_MAX, DEC },
930     { "sample_size", "set audio sample size", OFFSET(sample_size), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 16, DEC },
931     { "channels", "set number of audio channels, such as 1 or 2", OFFSET(channels), FF_OPT_TYPE_INT, {.dbl = 0}, 0, INT_MAX, DEC },
932     { "list_devices", "list available devices", OFFSET(list_devices), FF_OPT_TYPE_INT, {.dbl=0}, 0, 1, DEC, "list_devices" },
933     { "true", "", 0, FF_OPT_TYPE_CONST, {.dbl=1}, 0, 0, DEC, "list_devices" },
934     { "false", "", 0, FF_OPT_TYPE_CONST, {.dbl=0}, 0, 0, DEC, "list_devices" },
935     { "list_options", "list available options for specified device", OFFSET(list_options), FF_OPT_TYPE_INT, {.dbl=0}, 0, 1, DEC, "list_options" },
936     { "true", "", 0, FF_OPT_TYPE_CONST, {.dbl=1}, 0, 0, DEC, "list_options" },
937     { "false", "", 0, FF_OPT_TYPE_CONST, {.dbl=0}, 0, 0, DEC, "list_options" },
938     { NULL },
939 };
940
941 static const AVClass dshow_class = {
942     .class_name = "DirectShow indev",
943     .item_name  = av_default_item_name,
944     .option     = options,
945     .version    = LIBAVUTIL_VERSION_INT,
946 };
947
948 AVInputFormat ff_dshow_demuxer = {
949     "dshow",
950     NULL_IF_CONFIG_SMALL("DirectShow capture"),
951     sizeof(struct dshow_ctx),
952     NULL,
953     dshow_read_header,
954     dshow_read_packet,
955     dshow_read_close,
956     .flags = AVFMT_NOFILE,
957     .priv_class = &dshow_class,
958 };