]> 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 "avdevice.h"
23 #include "dshow.h"
24
25 struct dshow_ctx {
26     IGraphBuilder *graph;
27
28     char *device_name[2];
29
30     IBaseFilter *device_filter[2];
31     IPin        *device_pin[2];
32     libAVFilter *capture_filter[2];
33     libAVPin    *capture_pin[2];
34
35     HANDLE mutex;
36     HANDLE event;
37     AVPacketList *pktl;
38
39     unsigned int curbufsize;
40     unsigned int video_frame_num;
41
42     IMediaControl *control;
43 };
44
45 static enum PixelFormat dshow_pixfmt(DWORD biCompression, WORD biBitCount)
46 {
47     switch(biCompression) {
48     case MKTAG('U', 'Y', 'V', 'Y'):
49         return PIX_FMT_UYVY422;
50     case MKTAG('Y', 'U', 'Y', '2'):
51         return PIX_FMT_YUYV422;
52     case MKTAG('I', '4', '2', '0'):
53         return PIX_FMT_YUV420P;
54     case BI_RGB:
55         switch(biBitCount) { /* 1-8 are untested */
56             case 1:
57                 return PIX_FMT_MONOWHITE;
58             case 4:
59                 return PIX_FMT_RGB4;
60             case 8:
61                 return PIX_FMT_RGB8;
62             case 16:
63                 return PIX_FMT_RGB555;
64             case 24:
65                 return PIX_FMT_BGR24;
66             case 32:
67                 return PIX_FMT_RGB32;
68         }
69     }
70     return PIX_FMT_NONE;
71 }
72
73 static enum CodecID dshow_codecid(DWORD biCompression)
74 {
75     switch(biCompression) {
76     case MKTAG('d', 'v', 's', 'd'):
77         return CODEC_ID_DVVIDEO;
78     case MKTAG('M', 'J', 'P', 'G'):
79     case MKTAG('m', 'j', 'p', 'g'):
80         return CODEC_ID_MJPEG;
81     }
82     return CODEC_ID_NONE;
83 }
84
85 static int
86 dshow_read_close(AVFormatContext *s)
87 {
88     struct dshow_ctx *ctx = s->priv_data;
89     AVPacketList *pktl;
90
91     if (ctx->control) {
92         IMediaControl_Stop(ctx->control);
93         IMediaControl_Release(ctx->control);
94     }
95
96     if (ctx->capture_pin[VideoDevice])
97         libAVPin_Release(ctx->capture_pin[VideoDevice]);
98     if (ctx->capture_pin[AudioDevice])
99         libAVPin_Release(ctx->capture_pin[AudioDevice]);
100     if (ctx->capture_filter[VideoDevice])
101         libAVFilter_Release(ctx->capture_filter[VideoDevice]);
102     if (ctx->capture_filter[AudioDevice])
103         libAVFilter_Release(ctx->capture_filter[AudioDevice]);
104
105     if (ctx->device_pin[VideoDevice])
106         IPin_Release(ctx->device_pin[VideoDevice]);
107     if (ctx->device_pin[AudioDevice])
108         IPin_Release(ctx->device_pin[AudioDevice]);
109     if (ctx->device_filter[VideoDevice])
110         IBaseFilter_Release(ctx->device_filter[VideoDevice]);
111     if (ctx->device_filter[AudioDevice])
112         IBaseFilter_Release(ctx->device_filter[AudioDevice]);
113
114     if (ctx->graph) {
115         IEnumFilters *fenum;
116         int r;
117         r = IGraphBuilder_EnumFilters(ctx->graph, &fenum);
118         if (r == S_OK) {
119             IBaseFilter *f;
120             IEnumFilters_Reset(fenum);
121             while (IEnumFilters_Next(fenum, 1, &f, NULL) == S_OK)
122                 IGraphBuilder_RemoveFilter(ctx->graph, f);
123             IEnumFilters_Release(fenum);
124         }
125         IGraphBuilder_Release(ctx->graph);
126     }
127
128     if (ctx->device_name[0])
129         av_free(ctx->device_name[0]);
130     if (ctx->device_name[1])
131         av_free(ctx->device_name[1]);
132
133     if(ctx->mutex)
134         CloseHandle(ctx->mutex);
135     if(ctx->event)
136         CloseHandle(ctx->event);
137
138     pktl = ctx->pktl;
139     while (pktl) {
140         AVPacketList *next = pktl->next;
141         av_destruct_packet(&pktl->pkt);
142         av_free(pktl);
143         pktl = next;
144     }
145
146     return 0;
147 }
148
149 static char *dup_wchar_to_utf8(wchar_t *w)
150 {
151     char *s = NULL;
152     int l = WideCharToMultiByte(CP_UTF8, 0, w, -1, 0, 0, 0, 0);
153     s = av_malloc(l);
154     if (s)
155         WideCharToMultiByte(CP_UTF8, 0, w, -1, s, l, 0, 0);
156     return s;
157 }
158
159 static int shall_we_drop(AVFormatContext *s)
160 {
161     struct dshow_ctx *ctx = s->priv_data;
162     const uint8_t dropscore[] = {62, 75, 87, 100};
163     const int ndropscores = FF_ARRAY_ELEMS(dropscore);
164     unsigned int buffer_fullness = (ctx->curbufsize*100)/s->max_picture_buffer;
165
166     if(dropscore[++ctx->video_frame_num%ndropscores] <= buffer_fullness) {
167         av_log(s, AV_LOG_ERROR,
168               "real-time buffer %d%% full! frame dropped!\n", buffer_fullness);
169         return 1;
170     }
171
172     return 0;
173 }
174
175 static void
176 callback(void *priv_data, int index, uint8_t *buf, int buf_size, int64_t time)
177 {
178     AVFormatContext *s = priv_data;
179     struct dshow_ctx *ctx = s->priv_data;
180     AVPacketList **ppktl, *pktl_next;
181
182 //    dump_videohdr(s, vdhdr);
183
184     if(shall_we_drop(s))
185         return;
186
187     WaitForSingleObject(ctx->mutex, INFINITE);
188
189     pktl_next = av_mallocz(sizeof(AVPacketList));
190     if(!pktl_next)
191         goto fail;
192
193     if(av_new_packet(&pktl_next->pkt, buf_size) < 0) {
194         av_free(pktl_next);
195         goto fail;
196     }
197
198     pktl_next->pkt.stream_index = index;
199     pktl_next->pkt.pts = time;
200     memcpy(pktl_next->pkt.data, buf, buf_size);
201
202     for(ppktl = &ctx->pktl ; *ppktl ; ppktl = &(*ppktl)->next);
203     *ppktl = pktl_next;
204
205     ctx->curbufsize += buf_size;
206
207     SetEvent(ctx->event);
208     ReleaseMutex(ctx->mutex);
209
210     return;
211 fail:
212     ReleaseMutex(ctx->mutex);
213     return;
214 }
215
216 static int
217 dshow_open_device(AVFormatContext *avctx, ICreateDevEnum *devenum,
218                   enum dshowDeviceType devtype)
219 {
220     struct dshow_ctx *ctx = avctx->priv_data;
221     IBaseFilter *device_filter = NULL;
222     IEnumMoniker *classenum = NULL;
223     IGraphBuilder *graph = ctx->graph;
224     IEnumPins *pins = 0;
225     IMoniker *m = NULL;
226     IPin *device_pin = NULL;
227     libAVPin *capture_pin = NULL;
228     libAVFilter *capture_filter = NULL;
229     const char *device_name = ctx->device_name[devtype];
230     int ret = AVERROR(EIO);
231     IPin *pin;
232     int r;
233
234     const GUID *device_guid[2] = { &CLSID_VideoInputDeviceCategory,
235                                    &CLSID_AudioInputDeviceCategory };
236     const GUID *mediatype[2] = { &MEDIATYPE_Video, &MEDIATYPE_Audio };
237     const char *devtypename = (devtype == VideoDevice) ? "video" : "audio";
238     const wchar_t *filter_name[2] = { L"Audio capture filter", L"Video capture filter" };
239
240     r = ICreateDevEnum_CreateClassEnumerator(devenum, device_guid[devtype],
241                                              (IEnumMoniker **) &classenum, 0);
242     if (r != S_OK) {
243         av_log(avctx, AV_LOG_ERROR, "Could not enumerate %s devices.\n",
244                devtypename);
245         goto error;
246     }
247
248     while (IEnumMoniker_Next(classenum, 1, &m, NULL) == S_OK && !device_filter) {
249         IPropertyBag *bag = NULL;
250         char *buf = NULL;
251         VARIANT var;
252
253         r = IMoniker_BindToStorage(m, 0, 0, &IID_IPropertyBag, (void *) &bag);
254         if (r != S_OK)
255             goto fail1;
256
257         var.vt = VT_BSTR;
258         r = IPropertyBag_Read(bag, L"FriendlyName", &var, NULL);
259         if (r != S_OK)
260             goto fail1;
261
262         buf = dup_wchar_to_utf8(var.bstrVal);
263
264         if (strcmp(device_name, buf))
265             goto fail1;
266
267         IMoniker_BindToObject(m, 0, 0, &IID_IBaseFilter, (void *) &device_filter);
268
269 fail1:
270         if (buf)
271             av_free(buf);
272         if (bag)
273             IPropertyBag_Release(bag);
274         IMoniker_Release(m);
275     }
276
277     if (!device_filter) {
278         av_log(avctx, AV_LOG_ERROR, "Could not find %s device.\n",
279                devtypename);
280         goto error;
281     }
282     ctx->device_filter [devtype] = device_filter;
283
284     r = IGraphBuilder_AddFilter(graph, device_filter, NULL);
285     if (r != S_OK) {
286         av_log(avctx, AV_LOG_ERROR, "Could not add device filter to graph.\n");
287         goto error;
288     }
289
290     r = IBaseFilter_EnumPins(device_filter, &pins);
291     if (r != S_OK) {
292         av_log(avctx, AV_LOG_ERROR, "Could not enumerate pins.\n");
293         goto error;
294     }
295
296     while (IEnumPins_Next(pins, 1, &pin, NULL) == S_OK && !device_pin) {
297         IKsPropertySet *p = NULL;
298         IEnumMediaTypes *types;
299         PIN_INFO info = {0};
300         AM_MEDIA_TYPE *type;
301         GUID category;
302         DWORD r2;
303
304         IPin_QueryPinInfo(pin, &info);
305         IBaseFilter_Release(info.pFilter);
306
307         if (info.dir != PINDIR_OUTPUT)
308             goto next;
309         if (IPin_QueryInterface(pin, &IID_IKsPropertySet, (void **) &p) != S_OK)
310             goto next;
311         if (IKsPropertySet_Get(p, &AMPROPSETID_Pin, AMPROPERTY_PIN_CATEGORY,
312                                NULL, 0, &category, sizeof(GUID), &r2) != S_OK)
313             goto next;
314         if (!IsEqualGUID(&category, &PIN_CATEGORY_CAPTURE))
315             goto next;
316
317         if (IPin_EnumMediaTypes(pin, &types) != S_OK)
318             goto next;
319
320         IEnumMediaTypes_Reset(types);
321         while (IEnumMediaTypes_Next(types, 1, &type, NULL) == S_OK && !device_pin) {
322             if (IsEqualGUID(&type->majortype, mediatype[devtype])) {
323                 device_pin = pin;
324                 goto next;
325             }
326             CoTaskMemFree(type);
327         }
328
329 next:
330         if (types)
331             IEnumMediaTypes_Release(types);
332         if (p)
333             IKsPropertySet_Release(p);
334         if (device_pin != pin)
335             IPin_Release(pin);
336     }
337
338     if (!device_pin) {
339         av_log(avctx, AV_LOG_ERROR,
340                "Could not find output pin from %s capture device.\n", devtypename);
341         goto error;
342     }
343     ctx->device_pin[devtype] = device_pin;
344
345     capture_filter = libAVFilter_Create(avctx, callback, devtype);
346     if (!capture_filter) {
347         av_log(avctx, AV_LOG_ERROR, "Could not create grabber filter.\n");
348         goto error;
349     }
350     ctx->capture_filter[devtype] = capture_filter;
351
352     r = IGraphBuilder_AddFilter(graph, (IBaseFilter *) capture_filter,
353                                 filter_name[devtype]);
354     if (r != S_OK) {
355         av_log(avctx, AV_LOG_ERROR, "Could not add capture filter to graph\n");
356         goto error;
357     }
358
359     libAVPin_AddRef(capture_filter->pin);
360     capture_pin = capture_filter->pin;
361     ctx->capture_pin[devtype] = capture_pin;
362
363     r = IGraphBuilder_ConnectDirect(graph, device_pin, (IPin *) capture_pin, NULL);
364     if (r != S_OK) {
365         av_log(avctx, AV_LOG_ERROR, "Could not connect pins\n");
366         goto error;
367     }
368
369     ret = 0;
370
371 error:
372     if (pins)
373         IEnumPins_Release(pins);
374     if (classenum)
375         IEnumMoniker_Release(classenum);
376
377     return ret;
378 }
379
380 static enum CodecID waveform_codec_id(enum AVSampleFormat sample_fmt)
381 {
382     switch (sample_fmt) {
383     case AV_SAMPLE_FMT_U8:  return CODEC_ID_PCM_U8;
384     case AV_SAMPLE_FMT_S16: return CODEC_ID_PCM_S16LE;
385     case AV_SAMPLE_FMT_S32: return CODEC_ID_PCM_S32LE;
386     default:                return CODEC_ID_NONE; /* Should never happen. */
387     }
388 }
389
390 static enum SampleFormat sample_fmt_bits_per_sample(int bits)
391 {
392     switch (bits) {
393     case 8:  return AV_SAMPLE_FMT_U8;
394     case 16: return AV_SAMPLE_FMT_S16;
395     case 32: return AV_SAMPLE_FMT_S32;
396     default: return AV_SAMPLE_FMT_NONE; /* Should never happen. */
397     }
398 }
399
400 static int
401 dshow_add_device(AVFormatContext *avctx, AVFormatParameters *ap,
402                  enum dshowDeviceType devtype)
403 {
404     struct dshow_ctx *ctx = avctx->priv_data;
405     AM_MEDIA_TYPE type;
406     AVCodecContext *codec;
407     AVStream *st;
408     int ret = AVERROR(EIO);
409
410     st = av_new_stream(avctx, devtype);
411     if (!st) {
412         ret = AVERROR(ENOMEM);
413         goto error;
414     }
415
416     ctx->capture_filter[devtype]->stream_index = st->index;
417
418     libAVPin_ConnectionMediaType(ctx->capture_pin[devtype], &type);
419
420     codec = st->codec;
421     if (devtype == VideoDevice) {
422         BITMAPINFOHEADER *bih = NULL;
423
424         if (IsEqualGUID(&type.formattype, &FORMAT_VideoInfo)) {
425             VIDEOINFOHEADER *v = (void *) type.pbFormat;
426             bih = &v->bmiHeader;
427         } else if (IsEqualGUID(&type.formattype, &FORMAT_VideoInfo2)) {
428             VIDEOINFOHEADER2 *v = (void *) type.pbFormat;
429             bih = &v->bmiHeader;
430         }
431         if (!bih) {
432             av_log(avctx, AV_LOG_ERROR, "Could not get media type.\n");
433             goto error;
434         }
435
436         codec->time_base  = ap->time_base;
437         codec->codec_type = AVMEDIA_TYPE_VIDEO;
438         codec->width      = bih->biWidth;
439         codec->height     = bih->biHeight;
440         codec->pix_fmt    = dshow_pixfmt(bih->biCompression, bih->biBitCount);
441         if (codec->pix_fmt == PIX_FMT_NONE) {
442             codec->codec_id = dshow_codecid(bih->biCompression);
443             if (codec->codec_id == CODEC_ID_NONE) {
444                 av_log(avctx, AV_LOG_ERROR, "Unknown compression type. "
445                                  "Please report verbose (-v 9) debug information.\n");
446                 dshow_read_close(avctx);
447                 return AVERROR_PATCHWELCOME;
448             }
449             codec->bits_per_coded_sample = bih->biBitCount;
450         } else {
451             codec->codec_id = CODEC_ID_RAWVIDEO;
452             if (bih->biCompression == BI_RGB) {
453                 codec->bits_per_coded_sample = bih->biBitCount;
454                 codec->extradata = av_malloc(9 + FF_INPUT_BUFFER_PADDING_SIZE);
455                 if (codec->extradata) {
456                     codec->extradata_size = 9;
457                     memcpy(codec->extradata, "BottomUp", 9);
458                 }
459             }
460         }
461     } else {
462         WAVEFORMATEX *fx = NULL;
463
464         if (IsEqualGUID(&type.formattype, &FORMAT_WaveFormatEx)) {
465             fx = (void *) type.pbFormat;
466         }
467         if (!fx) {
468             av_log(avctx, AV_LOG_ERROR, "Could not get media type.\n");
469             goto error;
470         }
471
472         codec->codec_type  = AVMEDIA_TYPE_AUDIO;
473         codec->sample_fmt  = sample_fmt_bits_per_sample(fx->wBitsPerSample);
474         codec->codec_id    = waveform_codec_id(codec->sample_fmt);
475         codec->sample_rate = fx->nSamplesPerSec;
476         codec->channels    = fx->nChannels;
477     }
478
479     av_set_pts_info(st, 64, 1, 10000000);
480
481     ret = 0;
482
483 error:
484     return ret;
485 }
486
487 static int parse_device_name(AVFormatContext *avctx)
488 {
489     struct dshow_ctx *ctx = avctx->priv_data;
490     char **device_name = ctx->device_name;
491     char *name = av_strdup(avctx->filename);
492     char *tmp = name;
493     int ret = 1;
494     char *type;
495
496     while ((type = strtok(tmp, "="))) {
497         char *token = strtok(NULL, ":");
498         tmp = NULL;
499
500         if        (!strcmp(type, "video")) {
501             device_name[0] = token;
502         } else if (!strcmp(type, "audio")) {
503             device_name[1] = token;
504         } else {
505             device_name[0] = NULL;
506             device_name[1] = NULL;
507             break;
508         }
509     }
510
511     if (!device_name[0] && !device_name[1]) {
512         ret = 0;
513     } else {
514         if (device_name[0])
515             device_name[0] = av_strdup(device_name[0]);
516         if (device_name[1])
517             device_name[1] = av_strdup(device_name[1]);
518     }
519
520     av_free(name);
521     return ret;
522 }
523
524 static int dshow_read_header(AVFormatContext *avctx, AVFormatParameters *ap)
525 {
526     struct dshow_ctx *ctx = avctx->priv_data;
527     IGraphBuilder *graph = NULL;
528     ICreateDevEnum *devenum = NULL;
529     IMediaControl *control = NULL;
530     int ret = AVERROR(EIO);
531     int r;
532
533     if (!parse_device_name(avctx)) {
534         av_log(avctx, AV_LOG_ERROR, "Malformed dshow input string.\n");
535         goto error;
536     }
537
538     CoInitialize(0);
539
540     r = CoCreateInstance(&CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
541                          &IID_IGraphBuilder, (void **) &graph);
542     if (r != S_OK) {
543         av_log(avctx, AV_LOG_ERROR, "Could not create capture graph.\n");
544         goto error;
545     }
546     ctx->graph = graph;
547
548     r = CoCreateInstance(&CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
549                          &IID_ICreateDevEnum, (void **) &devenum);
550     if (r != S_OK) {
551         av_log(avctx, AV_LOG_ERROR, "Could not enumerate system devices.\n");
552         goto error;
553     }
554
555     if (ctx->device_name[VideoDevice]) {
556         ret = dshow_open_device(avctx, devenum, VideoDevice);
557         if (ret < 0)
558             goto error;
559         ret = dshow_add_device(avctx, ap, VideoDevice);
560         if (ret < 0)
561             goto error;
562     }
563     if (ctx->device_name[AudioDevice]) {
564         ret = dshow_open_device(avctx, devenum, AudioDevice);
565         if (ret < 0)
566             goto error;
567         ret = dshow_add_device(avctx, ap, AudioDevice);
568         if (ret < 0)
569             goto error;
570     }
571
572     ctx->mutex = CreateMutex(NULL, 0, NULL);
573     if (!ctx->mutex) {
574         av_log(avctx, AV_LOG_ERROR, "Could not create Mutex\n");
575         goto error;
576     }
577     ctx->event = CreateEvent(NULL, 1, 0, NULL);
578     if (!ctx->event) {
579         av_log(avctx, AV_LOG_ERROR, "Could not create Event\n");
580         goto error;
581     }
582
583     r = IGraphBuilder_QueryInterface(graph, &IID_IMediaControl, (void **) &control);
584     if (r != S_OK) {
585         av_log(avctx, AV_LOG_ERROR, "Could not get media control.\n");
586         goto error;
587     }
588     ctx->control = control;
589
590     r = IMediaControl_Run(control);
591     if (r == S_FALSE) {
592         OAFilterState pfs;
593         r = IMediaControl_GetState(control, 0, &pfs);
594     }
595     if (r != S_OK) {
596         av_log(avctx, AV_LOG_ERROR, "Could not run filter\n");
597         goto error;
598     }
599
600     ret = 0;
601
602 error:
603
604     if (ret < 0)
605         dshow_read_close(avctx);
606
607     if (devenum)
608         ICreateDevEnum_Release(devenum);
609
610     return ret;
611 }
612
613 static int dshow_read_packet(AVFormatContext *s, AVPacket *pkt)
614 {
615     struct dshow_ctx *ctx = s->priv_data;
616     AVPacketList *pktl = NULL;
617
618     while (!pktl) {
619         WaitForSingleObject(ctx->mutex, INFINITE);
620         pktl = ctx->pktl;
621         if (ctx->pktl) {
622             *pkt = ctx->pktl->pkt;
623             ctx->pktl = ctx->pktl->next;
624             av_free(pktl);
625         }
626         ResetEvent(ctx->event);
627         ReleaseMutex(ctx->mutex);
628         if (!pktl) {
629             if (s->flags & AVFMT_FLAG_NONBLOCK) {
630                 return AVERROR(EAGAIN);
631             } else {
632                 WaitForSingleObject(ctx->event, INFINITE);
633             }
634         }
635     }
636
637     ctx->curbufsize -= pkt->size;
638
639     return pkt->size;
640 }
641
642 AVInputFormat ff_dshow_demuxer = {
643     "dshow",
644     NULL_IF_CONFIG_SMALL("DirectShow capture"),
645     sizeof(struct dshow_ctx),
646     NULL,
647     dshow_read_header,
648     dshow_read_packet,
649     dshow_read_close,
650     .flags = AVFMT_NOFILE,
651 };