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