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