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