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