2 * Directshow capture interface
3 * Copyright (c) 2010 Ramiro Polla
5 * This file is part of FFmpeg.
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.
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.
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
22 #include "libavutil/parseutils.h"
23 #include "libavutil/pixdesc.h"
24 #include "libavutil/opt.h"
25 #include "libavformat/internal.h"
27 #include "dshow_capture.h"
35 int video_device_number;
36 int audio_device_number;
40 int audio_buffer_size;
42 IBaseFilter *device_filter[2];
44 libAVFilter *capture_filter[2];
45 libAVPin *capture_pin[2];
52 unsigned int video_frame_num;
54 IMediaControl *control;
56 enum PixelFormat pixel_format;
57 enum AVCodecID video_codec_id;
62 AVRational requested_framerate;
69 static enum PixelFormat dshow_pixfmt(DWORD biCompression, WORD biBitCount)
71 switch(biCompression) {
72 case MKTAG('U', 'Y', 'V', 'Y'):
73 return PIX_FMT_UYVY422;
74 case MKTAG('Y', 'U', 'Y', '2'):
75 return PIX_FMT_YUYV422;
76 case MKTAG('I', '4', '2', '0'):
77 return PIX_FMT_YUV420P;
80 switch(biBitCount) { /* 1-8 are untested */
82 return PIX_FMT_MONOWHITE;
88 return PIX_FMT_RGB555;
98 static enum AVCodecID dshow_codecid(DWORD biCompression)
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;
107 return AV_CODEC_ID_NONE;
111 dshow_read_close(AVFormatContext *s)
113 struct dshow_ctx *ctx = s->priv_data;
117 IMediaControl_Stop(ctx->control);
118 IMediaControl_Release(ctx->control);
124 r = IGraphBuilder_EnumFilters(ctx->graph, &fenum);
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);
134 IEnumFilters_Release(fenum);
136 IGraphBuilder_Release(ctx->graph);
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]);
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]);
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]);
163 CloseHandle(ctx->mutex);
165 CloseHandle(ctx->event);
169 AVPacketList *next = pktl->next;
170 av_destruct_packet(&pktl->pkt);
178 static char *dup_wchar_to_utf8(wchar_t *w)
181 int l = WideCharToMultiByte(CP_UTF8, 0, w, -1, 0, 0, 0, 0);
184 WideCharToMultiByte(CP_UTF8, 0, w, -1, s, l, 0, 0);
188 static int shall_we_drop(AVFormatContext *s)
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;
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);
205 callback(void *priv_data, int index, uint8_t *buf, int buf_size, int64_t time)
207 AVFormatContext *s = priv_data;
208 struct dshow_ctx *ctx = s->priv_data;
209 AVPacketList **ppktl, *pktl_next;
211 // dump_videohdr(s, vdhdr);
213 WaitForSingleObject(ctx->mutex, INFINITE);
218 pktl_next = av_mallocz(sizeof(AVPacketList));
222 if(av_new_packet(&pktl_next->pkt, buf_size) < 0) {
227 pktl_next->pkt.stream_index = index;
228 pktl_next->pkt.pts = time;
229 memcpy(pktl_next->pkt.data, buf, buf_size);
231 for(ppktl = &ctx->pktl ; *ppktl ; ppktl = &(*ppktl)->next);
234 ctx->curbufsize += buf_size;
236 SetEvent(ctx->event);
237 ReleaseMutex(ctx->mutex);
241 ReleaseMutex(ctx->mutex);
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.
252 dshow_cycle_devices(AVFormatContext *avctx, ICreateDevEnum *devenum,
253 enum dshowDeviceType devtype, IBaseFilter **pfilter)
255 struct dshow_ctx *ctx = avctx->priv_data;
256 IBaseFilter *device_filter = NULL;
257 IEnumMoniker *classenum = NULL;
259 const char *device_name = ctx->device_name[devtype];
260 int skip = (devtype == VideoDevice) ? ctx->video_device_number
261 : ctx->audio_device_number;
264 const GUID *device_guid[2] = { &CLSID_VideoInputDeviceCategory,
265 &CLSID_AudioInputDeviceCategory };
266 const char *devtypename = (devtype == VideoDevice) ? "video" : "audio";
268 r = ICreateDevEnum_CreateClassEnumerator(devenum, device_guid[devtype],
269 (IEnumMoniker **) &classenum, 0);
271 av_log(avctx, AV_LOG_ERROR, "Could not enumerate %s devices.\n",
276 while (!device_filter && IEnumMoniker_Next(classenum, 1, &m, NULL) == S_OK) {
277 IPropertyBag *bag = NULL;
281 r = IMoniker_BindToStorage(m, 0, 0, &IID_IPropertyBag, (void *) &bag);
286 r = IPropertyBag_Read(bag, L"FriendlyName", &var, NULL);
290 buf = dup_wchar_to_utf8(var.bstrVal);
293 if (strcmp(device_name, buf))
297 IMoniker_BindToObject(m, 0, 0, &IID_IBaseFilter, (void *) &device_filter);
299 av_log(avctx, AV_LOG_INFO, " \"%s\"\n", buf);
306 IPropertyBag_Release(bag);
310 IEnumMoniker_Release(classenum);
313 if (!device_filter) {
314 av_log(avctx, AV_LOG_ERROR, "Could not find %s device.\n",
318 *pfilter = device_filter;
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.
331 dshow_cycle_formats(AVFormatContext *avctx, enum dshowDeviceType devtype,
332 IPin *pin, int *pformat_set)
334 struct dshow_ctx *ctx = avctx->priv_data;
335 IAMStreamConfig *config = NULL;
336 AM_MEDIA_TYPE *type = NULL;
341 if (IPin_QueryInterface(pin, &IID_IAMStreamConfig, (void **) &config) != S_OK)
343 if (IAMStreamConfig_GetNumberOfCapabilities(config, &n, &size) != S_OK)
346 caps = av_malloc(size);
350 for (i = 0; i < n && !format_set; i++) {
351 IAMStreamConfig_GetStreamCaps(config, i, &type, (void *) caps);
354 ff_print_AM_MEDIA_TYPE(type);
357 if (devtype == VideoDevice) {
358 VIDEO_STREAM_CONFIG_CAPS *vcaps = caps;
359 BITMAPINFOHEADER *bih;
362 ff_print_VIDEO_STREAM_CONFIG_CAPS(vcaps);
364 if (IsEqualGUID(&type->formattype, &FORMAT_VideoInfo)) {
365 VIDEOINFOHEADER *v = (void *) type->pbFormat;
366 fr = &v->AvgTimePerFrame;
368 } else if (IsEqualGUID(&type->formattype, &FORMAT_VideoInfo2)) {
369 VIDEOINFOHEADER2 *v = (void *) type->pbFormat;
370 fr = &v->AvgTimePerFrame;
376 enum PixelFormat pix_fmt = dshow_pixfmt(bih->biCompression, bih->biBitCount);
377 if (pix_fmt == 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);
383 av_log(avctx, AV_LOG_INFO, " vcodec=%s", codec->name);
386 av_log(avctx, AV_LOG_INFO, " pixel_format=%s", av_get_pix_fmt_name(pix_fmt));
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);
395 if (ctx->video_codec_id != AV_CODEC_ID_RAWVIDEO) {
396 if (ctx->video_codec_id != dshow_codecid(bih->biCompression))
399 if (ctx->pixel_format != PIX_FMT_NONE &&
400 ctx->pixel_format != dshow_pixfmt(bih->biCompression, bih->biBitCount)) {
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)
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)
417 bih->biWidth = ctx->requested_width;
418 bih->biHeight = ctx->requested_height;
421 AUDIO_STREAM_CONFIG_CAPS *acaps = caps;
424 ff_print_AUDIO_STREAM_CONFIG_CAPS(acaps);
426 if (IsEqualGUID(&type->formattype, &FORMAT_WaveFormatEx)) {
427 fx = (void *) type->pbFormat;
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);
437 if (ctx->sample_rate) {
438 if (ctx->sample_rate > acaps->MaximumSampleFrequency ||
439 ctx->sample_rate < acaps->MinimumSampleFrequency)
441 fx->nSamplesPerSec = ctx->sample_rate;
443 if (ctx->sample_size) {
444 if (ctx->sample_size > acaps->MaximumBitsPerSample ||
445 ctx->sample_size < acaps->MinimumBitsPerSample)
447 fx->wBitsPerSample = ctx->sample_size;
450 if (ctx->channels > acaps->MaximumChannels ||
451 ctx->channels < acaps->MinimumChannels)
453 fx->nChannels = ctx->channels;
456 if (IAMStreamConfig_SetFormat(config, type) != S_OK)
461 CoTaskMemFree(type->pbFormat);
465 IAMStreamConfig_Release(config);
469 *pformat_set = format_set;
473 * Set audio device buffer size in milliseconds (which can directly impact
474 * latency, depending on the device).
477 dshow_set_audio_buffer_size(AVFormatContext *avctx, IPin *pin)
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);
486 if (IPin_QueryInterface(pin, &IID_IAMStreamConfig, (void **) &config) != S_OK)
488 if (IAMStreamConfig_GetFormat(config, &type) != S_OK)
490 if (!IsEqualGUID(&type->formattype, &FORMAT_WaveFormatEx))
493 props.cbBuffer = (((WAVEFORMATEX *) type->pbFormat)->nAvgBytesPerSec)
494 * ctx->audio_buffer_size / 1000;
496 if (IPin_QueryInterface(pin, &IID_IAMBufferNegotiation, (void **) &buffer_negotiation) != S_OK)
498 if (IAMBufferNegotiation_SuggestAllocatorProperties(buffer_negotiation, &props) != S_OK)
504 if (buffer_negotiation)
505 IAMBufferNegotiation_Release(buffer_negotiation);
508 CoTaskMemFree(type->pbFormat);
512 IAMStreamConfig_Release(config);
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.
524 dshow_cycle_pins(AVFormatContext *avctx, enum dshowDeviceType devtype,
525 IBaseFilter *device_filter, IPin **ppin)
527 struct dshow_ctx *ctx = avctx->priv_data;
529 IPin *device_pin = NULL;
533 const GUID *mediatype[2] = { &MEDIATYPE_Video, &MEDIATYPE_Audio };
534 const char *devtypename = (devtype == VideoDevice) ? "video" : "audio";
536 int set_format = (devtype == VideoDevice && (ctx->framerate ||
537 (ctx->requested_width && ctx->requested_height) ||
538 ctx->pixel_format != PIX_FMT_NONE ||
539 ctx->video_codec_id != AV_CODEC_ID_RAWVIDEO))
540 || (devtype == AudioDevice && (ctx->channels || ctx->sample_rate));
543 r = IBaseFilter_EnumPins(device_filter, &pins);
545 av_log(avctx, AV_LOG_ERROR, "Could not enumerate pins.\n");
550 av_log(avctx, AV_LOG_INFO, "DirectShow %s device options\n",
553 while (!device_pin && IEnumPins_Next(pins, 1, &pin, NULL) == S_OK) {
554 IKsPropertySet *p = NULL;
555 IEnumMediaTypes *types = NULL;
561 IPin_QueryPinInfo(pin, &info);
562 IBaseFilter_Release(info.pFilter);
564 if (info.dir != PINDIR_OUTPUT)
566 if (IPin_QueryInterface(pin, &IID_IKsPropertySet, (void **) &p) != S_OK)
568 if (IKsPropertySet_Get(p, &ROPSETID_Pin, AMPROPERTY_PIN_CATEGORY,
569 NULL, 0, &category, sizeof(GUID), &r2) != S_OK)
571 if (!IsEqualGUID(&category, &PIN_CATEGORY_CAPTURE))
575 char *buf = dup_wchar_to_utf8(info.achName);
576 av_log(avctx, AV_LOG_INFO, " Pin \"%s\"\n", buf);
578 dshow_cycle_formats(avctx, devtype, pin, NULL);
582 dshow_cycle_formats(avctx, devtype, pin, &format_set);
587 if (devtype == AudioDevice && ctx->audio_buffer_size) {
588 if (dshow_set_audio_buffer_size(avctx, pin) < 0)
592 if (IPin_EnumMediaTypes(pin, &types) != S_OK)
595 IEnumMediaTypes_Reset(types);
596 while (!device_pin && IEnumMediaTypes_Next(types, 1, &type, NULL) == S_OK) {
597 if (IsEqualGUID(&type->majortype, mediatype[devtype])) {
606 IEnumMediaTypes_Release(types);
608 IKsPropertySet_Release(p);
609 if (device_pin != pin)
613 IEnumPins_Release(pins);
616 if (set_format && !format_set) {
617 av_log(avctx, AV_LOG_ERROR, "Could not set %s options\n", devtypename);
621 av_log(avctx, AV_LOG_ERROR,
622 "Could not find output pin from %s capture device.\n", devtypename);
632 * List options for device with type devtype.
634 * @param devenum device enumerator used for accessing the device
637 dshow_list_device_options(AVFormatContext *avctx, ICreateDevEnum *devenum,
638 enum dshowDeviceType devtype)
640 struct dshow_ctx *ctx = avctx->priv_data;
641 IBaseFilter *device_filter = NULL;
644 if ((r = dshow_cycle_devices(avctx, devenum, devtype, &device_filter)) < 0)
646 ctx->device_filter[devtype] = device_filter;
647 if ((r = dshow_cycle_pins(avctx, devtype, device_filter, NULL)) < 0)
654 dshow_open_device(AVFormatContext *avctx, ICreateDevEnum *devenum,
655 enum dshowDeviceType devtype)
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);
666 const wchar_t *filter_name[2] = { L"Audio capture filter", L"Video capture filter" };
668 if ((r = dshow_cycle_devices(avctx, devenum, devtype, &device_filter)) < 0) {
673 ctx->device_filter [devtype] = device_filter;
675 r = IGraphBuilder_AddFilter(graph, device_filter, NULL);
677 av_log(avctx, AV_LOG_ERROR, "Could not add device filter to graph.\n");
681 if ((r = dshow_cycle_pins(avctx, devtype, device_filter, &device_pin)) < 0) {
685 ctx->device_pin[devtype] = device_pin;
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");
692 ctx->capture_filter[devtype] = capture_filter;
694 r = IGraphBuilder_AddFilter(graph, (IBaseFilter *) capture_filter,
695 filter_name[devtype]);
697 av_log(avctx, AV_LOG_ERROR, "Could not add capture filter to graph\n");
701 libAVPin_AddRef(capture_filter->pin);
702 capture_pin = capture_filter->pin;
703 ctx->capture_pin[devtype] = capture_pin;
705 r = IGraphBuilder_ConnectDirect(graph, device_pin, (IPin *) capture_pin, NULL);
707 av_log(avctx, AV_LOG_ERROR, "Could not connect pins\n");
717 static enum AVCodecID waveform_codec_id(enum AVSampleFormat sample_fmt)
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. */
727 static enum AVSampleFormat sample_fmt_bits_per_sample(int 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. */
738 dshow_add_device(AVFormatContext *avctx,
739 enum dshowDeviceType devtype)
741 struct dshow_ctx *ctx = avctx->priv_data;
743 AVCodecContext *codec;
745 int ret = AVERROR(EIO);
747 st = avformat_new_stream(avctx, NULL);
749 ret = AVERROR(ENOMEM);
754 ctx->capture_filter[devtype]->stream_index = st->index;
756 libAVPin_ConnectionMediaType(ctx->capture_pin[devtype], &type);
759 if (devtype == VideoDevice) {
760 BITMAPINFOHEADER *bih = NULL;
761 AVRational time_base;
763 if (IsEqualGUID(&type.formattype, &FORMAT_VideoInfo)) {
764 VIDEOINFOHEADER *v = (void *) type.pbFormat;
765 time_base = (AVRational) { v->AvgTimePerFrame, 10000000 };
767 } else if (IsEqualGUID(&type.formattype, &FORMAT_VideoInfo2)) {
768 VIDEOINFOHEADER2 *v = (void *) type.pbFormat;
769 time_base = (AVRational) { v->AvgTimePerFrame, 10000000 };
773 av_log(avctx, AV_LOG_ERROR, "Could not get media type.\n");
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 == 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;
790 codec->bits_per_coded_sample = bih->biBitCount;
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);
803 WAVEFORMATEX *fx = NULL;
805 if (IsEqualGUID(&type.formattype, &FORMAT_WaveFormatEx)) {
806 fx = (void *) type.pbFormat;
809 av_log(avctx, AV_LOG_ERROR, "Could not get media type.\n");
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;
820 avpriv_set_pts_info(st, 64, 1, 10000000);
828 static int parse_device_name(AVFormatContext *avctx)
830 struct dshow_ctx *ctx = avctx->priv_data;
831 char **device_name = ctx->device_name;
832 char *name = av_strdup(avctx->filename);
837 while ((type = strtok(tmp, "="))) {
838 char *token = strtok(NULL, ":");
841 if (!strcmp(type, "video")) {
842 device_name[0] = token;
843 } else if (!strcmp(type, "audio")) {
844 device_name[1] = token;
846 device_name[0] = NULL;
847 device_name[1] = NULL;
852 if (!device_name[0] && !device_name[1]) {
856 device_name[0] = av_strdup(device_name[0]);
858 device_name[1] = av_strdup(device_name[1]);
865 static int dshow_read_header(AVFormatContext *avctx)
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);
874 if (!ctx->list_devices && !parse_device_name(avctx)) {
875 av_log(avctx, AV_LOG_ERROR, "Malformed dshow input string.\n");
879 ctx->video_codec_id = avctx->video_codec_id ? avctx->video_codec_id
880 : AV_CODEC_ID_RAWVIDEO;
881 if (ctx->pixel_format != 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);
889 if (ctx->framerate) {
890 r = av_parse_video_rate(&ctx->requested_framerate, ctx->framerate);
892 av_log(avctx, AV_LOG_ERROR, "Could not parse framerate '%s'.\n", ctx->framerate);
899 r = CoCreateInstance(&CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
900 &IID_IGraphBuilder, (void **) &graph);
902 av_log(avctx, AV_LOG_ERROR, "Could not create capture graph.\n");
907 r = CoCreateInstance(&CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
908 &IID_ICreateDevEnum, (void **) &devenum);
910 av_log(avctx, AV_LOG_ERROR, "Could not enumerate system devices.\n");
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);
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);
931 if (ctx->device_name[VideoDevice]) {
932 ret = dshow_open_device(avctx, devenum, VideoDevice);
935 ret = dshow_add_device(avctx, VideoDevice);
939 if (ctx->device_name[AudioDevice]) {
940 ret = dshow_open_device(avctx, devenum, AudioDevice);
943 ret = dshow_add_device(avctx, AudioDevice);
948 ctx->mutex = CreateMutex(NULL, 0, NULL);
950 av_log(avctx, AV_LOG_ERROR, "Could not create Mutex\n");
953 ctx->event = CreateEvent(NULL, 1, 0, NULL);
955 av_log(avctx, AV_LOG_ERROR, "Could not create Event\n");
959 r = IGraphBuilder_QueryInterface(graph, &IID_IMediaControl, (void **) &control);
961 av_log(avctx, AV_LOG_ERROR, "Could not get media control.\n");
964 ctx->control = control;
966 r = IMediaControl_Run(control);
969 r = IMediaControl_GetState(control, 0, &pfs);
972 av_log(avctx, AV_LOG_ERROR, "Could not run filter\n");
981 dshow_read_close(avctx);
984 ICreateDevEnum_Release(devenum);
989 static int dshow_read_packet(AVFormatContext *s, AVPacket *pkt)
991 struct dshow_ctx *ctx = s->priv_data;
992 AVPacketList *pktl = NULL;
995 WaitForSingleObject(ctx->mutex, INFINITE);
999 ctx->pktl = ctx->pktl->next;
1001 ctx->curbufsize -= pkt->size;
1003 ResetEvent(ctx->event);
1004 ReleaseMutex(ctx->mutex);
1006 if (s->flags & AVFMT_FLAG_NONBLOCK) {
1007 return AVERROR(EAGAIN);
1009 WaitForSingleObject(ctx->event, INFINITE);
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 },
1038 static const AVClass dshow_class = {
1039 .class_name = "DirectShow indev",
1040 .item_name = av_default_item_name,
1042 .version = LIBAVUTIL_VERSION_INT,
1045 AVInputFormat ff_dshow_demuxer = {
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,