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