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 "dshow_capture.h"
23 #include "libavutil/parseutils.h"
24 #include "libavutil/pixdesc.h"
25 #include "libavutil/opt.h"
26 #include "libavformat/internal.h"
27 #include "libavformat/riff.h"
29 #include "libavcodec/raw.h"
37 int video_device_number;
38 int audio_device_number;
42 int audio_buffer_size;
44 IBaseFilter *device_filter[2];
46 libAVFilter *capture_filter[2];
47 libAVPin *capture_pin[2];
50 HANDLE event[2]; /* event[0] is set by DirectShow
51 * event[1] is set by callback() */
56 int64_t curbufsize[2];
57 unsigned int video_frame_num;
59 IMediaControl *control;
60 IMediaEvent *media_event;
62 enum AVPixelFormat pixel_format;
63 enum AVCodecID video_codec_id;
68 AVRational requested_framerate;
75 static enum AVPixelFormat dshow_pixfmt(DWORD biCompression, WORD biBitCount)
77 switch(biCompression) {
80 switch(biBitCount) { /* 1-8 are untested */
82 return AV_PIX_FMT_MONOWHITE;
84 return AV_PIX_FMT_RGB4;
86 return AV_PIX_FMT_RGB8;
88 return AV_PIX_FMT_RGB555;
90 return AV_PIX_FMT_BGR24;
92 return AV_PIX_FMT_0RGB32;
95 return avpriv_find_pix_fmt(avpriv_get_raw_pix_fmt_tags(), biCompression); // all others
99 dshow_read_close(AVFormatContext *s)
101 struct dshow_ctx *ctx = s->priv_data;
105 IMediaControl_Stop(ctx->control);
106 IMediaControl_Release(ctx->control);
109 if (ctx->media_event)
110 IMediaEvent_Release(ctx->media_event);
115 r = IGraphBuilder_EnumFilters(ctx->graph, &fenum);
118 IEnumFilters_Reset(fenum);
119 while (IEnumFilters_Next(fenum, 1, &f, NULL) == S_OK) {
120 if (IGraphBuilder_RemoveFilter(ctx->graph, f) == S_OK)
121 IEnumFilters_Reset(fenum); /* When a filter is removed,
122 * the list must be reset. */
123 IBaseFilter_Release(f);
125 IEnumFilters_Release(fenum);
127 IGraphBuilder_Release(ctx->graph);
130 if (ctx->capture_pin[VideoDevice])
131 libAVPin_Release(ctx->capture_pin[VideoDevice]);
132 if (ctx->capture_pin[AudioDevice])
133 libAVPin_Release(ctx->capture_pin[AudioDevice]);
134 if (ctx->capture_filter[VideoDevice])
135 libAVFilter_Release(ctx->capture_filter[VideoDevice]);
136 if (ctx->capture_filter[AudioDevice])
137 libAVFilter_Release(ctx->capture_filter[AudioDevice]);
139 if (ctx->device_pin[VideoDevice])
140 IPin_Release(ctx->device_pin[VideoDevice]);
141 if (ctx->device_pin[AudioDevice])
142 IPin_Release(ctx->device_pin[AudioDevice]);
143 if (ctx->device_filter[VideoDevice])
144 IBaseFilter_Release(ctx->device_filter[VideoDevice]);
145 if (ctx->device_filter[AudioDevice])
146 IBaseFilter_Release(ctx->device_filter[AudioDevice]);
148 if (ctx->device_name[0])
149 av_freep(&ctx->device_name[0]);
150 if (ctx->device_name[1])
151 av_freep(&ctx->device_name[1]);
154 CloseHandle(ctx->mutex);
156 CloseHandle(ctx->event[0]);
158 CloseHandle(ctx->event[1]);
162 AVPacketList *next = pktl->next;
163 av_destruct_packet(&pktl->pkt);
173 static char *dup_wchar_to_utf8(wchar_t *w)
176 int l = WideCharToMultiByte(CP_UTF8, 0, w, -1, 0, 0, 0, 0);
179 WideCharToMultiByte(CP_UTF8, 0, w, -1, s, l, 0, 0);
183 static int shall_we_drop(AVFormatContext *s, int index, enum dshowDeviceType devtype)
185 struct dshow_ctx *ctx = s->priv_data;
186 static const uint8_t dropscore[] = {62, 75, 87, 100};
187 const int ndropscores = FF_ARRAY_ELEMS(dropscore);
188 unsigned int buffer_fullness = (ctx->curbufsize[index]*100)/s->max_picture_buffer;
190 if(dropscore[++ctx->video_frame_num%ndropscores] <= buffer_fullness) {
191 av_log(s, AV_LOG_ERROR,
192 "real-time buffer[%s] too full (%d%% of size: %d)! frame dropped!\n", ctx->device_name[devtype], buffer_fullness, s->max_picture_buffer);
200 callback(void *priv_data, int index, uint8_t *buf, int buf_size, int64_t time, enum dshowDeviceType devtype)
202 AVFormatContext *s = priv_data;
203 struct dshow_ctx *ctx = s->priv_data;
204 AVPacketList **ppktl, *pktl_next;
206 // dump_videohdr(s, vdhdr);
208 WaitForSingleObject(ctx->mutex, INFINITE);
210 if(shall_we_drop(s, index, devtype))
213 pktl_next = av_mallocz(sizeof(AVPacketList));
217 if(av_new_packet(&pktl_next->pkt, buf_size) < 0) {
222 pktl_next->pkt.stream_index = index;
223 pktl_next->pkt.pts = time;
224 memcpy(pktl_next->pkt.data, buf, buf_size);
226 for(ppktl = &ctx->pktl ; *ppktl ; ppktl = &(*ppktl)->next);
228 ctx->curbufsize[index] += buf_size;
230 SetEvent(ctx->event[1]);
231 ReleaseMutex(ctx->mutex);
235 ReleaseMutex(ctx->mutex);
240 * Cycle through available devices using the device enumerator devenum,
241 * retrieve the device with type specified by devtype and return the
242 * pointer to the object found in *pfilter.
243 * If pfilter is NULL, list all device names.
246 dshow_cycle_devices(AVFormatContext *avctx, ICreateDevEnum *devenum,
247 enum dshowDeviceType devtype, IBaseFilter **pfilter)
249 struct dshow_ctx *ctx = avctx->priv_data;
250 IBaseFilter *device_filter = NULL;
251 IEnumMoniker *classenum = NULL;
253 const char *device_name = ctx->device_name[devtype];
254 int skip = (devtype == VideoDevice) ? ctx->video_device_number
255 : ctx->audio_device_number;
258 const GUID *device_guid[2] = { &CLSID_VideoInputDeviceCategory,
259 &CLSID_AudioInputDeviceCategory };
260 const char *devtypename = (devtype == VideoDevice) ? "video" : "audio";
262 r = ICreateDevEnum_CreateClassEnumerator(devenum, device_guid[devtype],
263 (IEnumMoniker **) &classenum, 0);
265 av_log(avctx, AV_LOG_ERROR, "Could not enumerate %s devices.\n",
270 while (!device_filter && IEnumMoniker_Next(classenum, 1, &m, NULL) == S_OK) {
271 IPropertyBag *bag = NULL;
275 r = IMoniker_BindToStorage(m, 0, 0, &IID_IPropertyBag, (void *) &bag);
280 r = IPropertyBag_Read(bag, L"FriendlyName", &var, NULL);
284 buf = dup_wchar_to_utf8(var.bstrVal);
287 if (strcmp(device_name, buf))
291 IMoniker_BindToObject(m, 0, 0, &IID_IBaseFilter, (void *) &device_filter);
293 av_log(avctx, AV_LOG_INFO, " \"%s\"\n", buf);
299 IPropertyBag_Release(bag);
303 IEnumMoniker_Release(classenum);
306 if (!device_filter) {
307 av_log(avctx, AV_LOG_ERROR, "Could not find %s device.\n",
311 *pfilter = device_filter;
318 * Cycle through available formats using the specified pin,
319 * try to set parameters specified through AVOptions and if successful
320 * return 1 in *pformat_set.
321 * If pformat_set is NULL, list all pin capabilities.
324 dshow_cycle_formats(AVFormatContext *avctx, enum dshowDeviceType devtype,
325 IPin *pin, int *pformat_set)
327 struct dshow_ctx *ctx = avctx->priv_data;
328 IAMStreamConfig *config = NULL;
329 AM_MEDIA_TYPE *type = NULL;
334 if (IPin_QueryInterface(pin, &IID_IAMStreamConfig, (void **) &config) != S_OK)
336 if (IAMStreamConfig_GetNumberOfCapabilities(config, &n, &size) != S_OK)
339 caps = av_malloc(size);
343 for (i = 0; i < n && !format_set; i++) {
344 IAMStreamConfig_GetStreamCaps(config, i, &type, (void *) caps);
347 ff_print_AM_MEDIA_TYPE(type);
350 if (devtype == VideoDevice) {
351 VIDEO_STREAM_CONFIG_CAPS *vcaps = caps;
352 BITMAPINFOHEADER *bih;
354 const AVCodecTag *const tags[] = { avformat_get_riff_video_tags(), NULL };
356 ff_print_VIDEO_STREAM_CONFIG_CAPS(vcaps);
358 if (IsEqualGUID(&type->formattype, &FORMAT_VideoInfo)) {
359 VIDEOINFOHEADER *v = (void *) type->pbFormat;
360 fr = &v->AvgTimePerFrame;
362 } else if (IsEqualGUID(&type->formattype, &FORMAT_VideoInfo2)) {
363 VIDEOINFOHEADER2 *v = (void *) type->pbFormat;
364 fr = &v->AvgTimePerFrame;
370 enum AVPixelFormat pix_fmt = dshow_pixfmt(bih->biCompression, bih->biBitCount);
371 if (pix_fmt == AV_PIX_FMT_NONE) {
372 enum AVCodecID codec_id = av_codec_get_id(tags, bih->biCompression);
373 AVCodec *codec = avcodec_find_decoder(codec_id);
374 if (codec_id == AV_CODEC_ID_NONE || !codec) {
375 av_log(avctx, AV_LOG_INFO, " unknown compression type 0x%X", (int) bih->biCompression);
377 av_log(avctx, AV_LOG_INFO, " vcodec=%s", codec->name);
380 av_log(avctx, AV_LOG_INFO, " pixel_format=%s", av_get_pix_fmt_name(pix_fmt));
382 av_log(avctx, AV_LOG_INFO, " min s=%ldx%ld fps=%g max s=%ldx%ld fps=%g\n",
383 vcaps->MinOutputSize.cx, vcaps->MinOutputSize.cy,
384 1e7 / vcaps->MaxFrameInterval,
385 vcaps->MaxOutputSize.cx, vcaps->MaxOutputSize.cy,
386 1e7 / vcaps->MinFrameInterval);
389 if (ctx->video_codec_id != AV_CODEC_ID_RAWVIDEO) {
390 if (ctx->video_codec_id != av_codec_get_id(tags, bih->biCompression))
393 if (ctx->pixel_format != AV_PIX_FMT_NONE &&
394 ctx->pixel_format != dshow_pixfmt(bih->biCompression, bih->biBitCount)) {
397 if (ctx->framerate) {
398 int64_t framerate = ((int64_t) ctx->requested_framerate.den*10000000)
399 / ctx->requested_framerate.num;
400 if (framerate > vcaps->MaxFrameInterval ||
401 framerate < vcaps->MinFrameInterval)
405 if (ctx->requested_width && ctx->requested_height) {
406 if (ctx->requested_width > vcaps->MaxOutputSize.cx ||
407 ctx->requested_width < vcaps->MinOutputSize.cx ||
408 ctx->requested_height > vcaps->MaxOutputSize.cy ||
409 ctx->requested_height < vcaps->MinOutputSize.cy)
411 bih->biWidth = ctx->requested_width;
412 bih->biHeight = ctx->requested_height;
415 AUDIO_STREAM_CONFIG_CAPS *acaps = caps;
418 ff_print_AUDIO_STREAM_CONFIG_CAPS(acaps);
420 if (IsEqualGUID(&type->formattype, &FORMAT_WaveFormatEx)) {
421 fx = (void *) type->pbFormat;
426 av_log(avctx, AV_LOG_INFO, " min ch=%lu bits=%lu rate=%6lu max ch=%lu bits=%lu rate=%6lu\n",
427 acaps->MinimumChannels, acaps->MinimumBitsPerSample, acaps->MinimumSampleFrequency,
428 acaps->MaximumChannels, acaps->MaximumBitsPerSample, acaps->MaximumSampleFrequency);
431 if (ctx->sample_rate) {
432 if (ctx->sample_rate > acaps->MaximumSampleFrequency ||
433 ctx->sample_rate < acaps->MinimumSampleFrequency)
435 fx->nSamplesPerSec = ctx->sample_rate;
437 if (ctx->sample_size) {
438 if (ctx->sample_size > acaps->MaximumBitsPerSample ||
439 ctx->sample_size < acaps->MinimumBitsPerSample)
441 fx->wBitsPerSample = ctx->sample_size;
444 if (ctx->channels > acaps->MaximumChannels ||
445 ctx->channels < acaps->MinimumChannels)
447 fx->nChannels = ctx->channels;
450 if (IAMStreamConfig_SetFormat(config, type) != S_OK)
455 CoTaskMemFree(type->pbFormat);
459 IAMStreamConfig_Release(config);
462 *pformat_set = format_set;
466 * Set audio device buffer size in milliseconds (which can directly impact
467 * latency, depending on the device).
470 dshow_set_audio_buffer_size(AVFormatContext *avctx, IPin *pin)
472 struct dshow_ctx *ctx = avctx->priv_data;
473 IAMBufferNegotiation *buffer_negotiation = NULL;
474 ALLOCATOR_PROPERTIES props = { -1, -1, -1, -1 };
475 IAMStreamConfig *config = NULL;
476 AM_MEDIA_TYPE *type = NULL;
477 int ret = AVERROR(EIO);
479 if (IPin_QueryInterface(pin, &IID_IAMStreamConfig, (void **) &config) != S_OK)
481 if (IAMStreamConfig_GetFormat(config, &type) != S_OK)
483 if (!IsEqualGUID(&type->formattype, &FORMAT_WaveFormatEx))
486 props.cbBuffer = (((WAVEFORMATEX *) type->pbFormat)->nAvgBytesPerSec)
487 * ctx->audio_buffer_size / 1000;
489 if (IPin_QueryInterface(pin, &IID_IAMBufferNegotiation, (void **) &buffer_negotiation) != S_OK)
491 if (IAMBufferNegotiation_SuggestAllocatorProperties(buffer_negotiation, &props) != S_OK)
497 if (buffer_negotiation)
498 IAMBufferNegotiation_Release(buffer_negotiation);
501 CoTaskMemFree(type->pbFormat);
505 IAMStreamConfig_Release(config);
511 * Cycle through available pins using the device_filter device, of type
512 * devtype, retrieve the first output pin and return the pointer to the
513 * object found in *ppin.
514 * If ppin is NULL, cycle through all pins listing audio/video capabilities.
517 dshow_cycle_pins(AVFormatContext *avctx, enum dshowDeviceType devtype,
518 IBaseFilter *device_filter, IPin **ppin)
520 struct dshow_ctx *ctx = avctx->priv_data;
522 IPin *device_pin = NULL;
526 const GUID *mediatype[2] = { &MEDIATYPE_Video, &MEDIATYPE_Audio };
527 const char *devtypename = (devtype == VideoDevice) ? "video" : "audio";
529 int set_format = (devtype == VideoDevice && (ctx->framerate ||
530 (ctx->requested_width && ctx->requested_height) ||
531 ctx->pixel_format != AV_PIX_FMT_NONE ||
532 ctx->video_codec_id != AV_CODEC_ID_RAWVIDEO))
533 || (devtype == AudioDevice && (ctx->channels || ctx->sample_rate));
536 r = IBaseFilter_EnumPins(device_filter, &pins);
538 av_log(avctx, AV_LOG_ERROR, "Could not enumerate pins.\n");
543 av_log(avctx, AV_LOG_INFO, "DirectShow %s device options\n",
546 while (!device_pin && IEnumPins_Next(pins, 1, &pin, NULL) == S_OK) {
547 IKsPropertySet *p = NULL;
548 IEnumMediaTypes *types = NULL;
554 IPin_QueryPinInfo(pin, &info);
555 IBaseFilter_Release(info.pFilter);
557 if (info.dir != PINDIR_OUTPUT)
559 if (IPin_QueryInterface(pin, &IID_IKsPropertySet, (void **) &p) != S_OK)
561 if (IKsPropertySet_Get(p, &ROPSETID_Pin, AMPROPERTY_PIN_CATEGORY,
562 NULL, 0, &category, sizeof(GUID), &r2) != S_OK)
564 if (!IsEqualGUID(&category, &PIN_CATEGORY_CAPTURE))
568 char *buf = dup_wchar_to_utf8(info.achName);
569 av_log(avctx, AV_LOG_INFO, " Pin \"%s\"\n", buf);
571 dshow_cycle_formats(avctx, devtype, pin, NULL);
575 dshow_cycle_formats(avctx, devtype, pin, &format_set);
580 if (devtype == AudioDevice && ctx->audio_buffer_size) {
581 if (dshow_set_audio_buffer_size(avctx, pin) < 0) {
582 av_log(avctx, AV_LOG_ERROR, "unable to set audio buffer size %d to pin, using pin anyway...", ctx->audio_buffer_size);
586 if (IPin_EnumMediaTypes(pin, &types) != S_OK)
589 IEnumMediaTypes_Reset(types);
590 while (!device_pin && IEnumMediaTypes_Next(types, 1, &type, NULL) == S_OK) {
591 if (IsEqualGUID(&type->majortype, mediatype[devtype])) {
600 IEnumMediaTypes_Release(types);
602 IKsPropertySet_Release(p);
603 if (device_pin != pin)
607 IEnumPins_Release(pins);
610 if (set_format && !format_set) {
611 av_log(avctx, AV_LOG_ERROR, "Could not set %s options\n", devtypename);
615 av_log(avctx, AV_LOG_ERROR,
616 "Could not find output pin from %s capture device.\n", devtypename);
626 * List options for device with type devtype.
628 * @param devenum device enumerator used for accessing the device
631 dshow_list_device_options(AVFormatContext *avctx, ICreateDevEnum *devenum,
632 enum dshowDeviceType devtype)
634 struct dshow_ctx *ctx = avctx->priv_data;
635 IBaseFilter *device_filter = NULL;
638 if ((r = dshow_cycle_devices(avctx, devenum, devtype, &device_filter)) < 0)
640 ctx->device_filter[devtype] = device_filter;
641 if ((r = dshow_cycle_pins(avctx, devtype, device_filter, NULL)) < 0)
648 dshow_open_device(AVFormatContext *avctx, ICreateDevEnum *devenum,
649 enum dshowDeviceType devtype)
651 struct dshow_ctx *ctx = avctx->priv_data;
652 IBaseFilter *device_filter = NULL;
653 IGraphBuilder *graph = ctx->graph;
654 IPin *device_pin = NULL;
655 libAVPin *capture_pin = NULL;
656 libAVFilter *capture_filter = NULL;
657 int ret = AVERROR(EIO);
660 const wchar_t *filter_name[2] = { L"Audio capture filter", L"Video capture filter" };
662 if ((r = dshow_cycle_devices(avctx, devenum, devtype, &device_filter)) < 0) {
667 ctx->device_filter [devtype] = device_filter;
669 r = IGraphBuilder_AddFilter(graph, device_filter, NULL);
671 av_log(avctx, AV_LOG_ERROR, "Could not add device filter to graph.\n");
675 if ((r = dshow_cycle_pins(avctx, devtype, device_filter, &device_pin)) < 0) {
679 ctx->device_pin[devtype] = device_pin;
681 capture_filter = libAVFilter_Create(avctx, callback, devtype);
682 if (!capture_filter) {
683 av_log(avctx, AV_LOG_ERROR, "Could not create grabber filter.\n");
686 ctx->capture_filter[devtype] = capture_filter;
688 r = IGraphBuilder_AddFilter(graph, (IBaseFilter *) capture_filter,
689 filter_name[devtype]);
691 av_log(avctx, AV_LOG_ERROR, "Could not add capture filter to graph\n");
695 libAVPin_AddRef(capture_filter->pin);
696 capture_pin = capture_filter->pin;
697 ctx->capture_pin[devtype] = capture_pin;
699 r = IGraphBuilder_ConnectDirect(graph, device_pin, (IPin *) capture_pin, NULL);
701 av_log(avctx, AV_LOG_ERROR, "Could not connect pins\n");
711 static enum AVCodecID waveform_codec_id(enum AVSampleFormat sample_fmt)
713 switch (sample_fmt) {
714 case AV_SAMPLE_FMT_U8: return AV_CODEC_ID_PCM_U8;
715 case AV_SAMPLE_FMT_S16: return AV_CODEC_ID_PCM_S16LE;
716 case AV_SAMPLE_FMT_S32: return AV_CODEC_ID_PCM_S32LE;
717 default: return AV_CODEC_ID_NONE; /* Should never happen. */
721 static enum AVSampleFormat sample_fmt_bits_per_sample(int bits)
724 case 8: return AV_SAMPLE_FMT_U8;
725 case 16: return AV_SAMPLE_FMT_S16;
726 case 32: return AV_SAMPLE_FMT_S32;
727 default: return AV_SAMPLE_FMT_NONE; /* Should never happen. */
732 dshow_add_device(AVFormatContext *avctx,
733 enum dshowDeviceType devtype)
735 struct dshow_ctx *ctx = avctx->priv_data;
737 AVCodecContext *codec;
739 int ret = AVERROR(EIO);
741 st = avformat_new_stream(avctx, NULL);
743 ret = AVERROR(ENOMEM);
748 ctx->capture_filter[devtype]->stream_index = st->index;
750 libAVPin_ConnectionMediaType(ctx->capture_pin[devtype], &type);
753 if (devtype == VideoDevice) {
754 BITMAPINFOHEADER *bih = NULL;
755 AVRational time_base;
757 if (IsEqualGUID(&type.formattype, &FORMAT_VideoInfo)) {
758 VIDEOINFOHEADER *v = (void *) type.pbFormat;
759 time_base = (AVRational) { v->AvgTimePerFrame, 10000000 };
761 } else if (IsEqualGUID(&type.formattype, &FORMAT_VideoInfo2)) {
762 VIDEOINFOHEADER2 *v = (void *) type.pbFormat;
763 time_base = (AVRational) { v->AvgTimePerFrame, 10000000 };
767 av_log(avctx, AV_LOG_ERROR, "Could not get media type.\n");
771 codec->time_base = time_base;
772 codec->codec_type = AVMEDIA_TYPE_VIDEO;
773 codec->width = bih->biWidth;
774 codec->height = bih->biHeight;
775 codec->codec_tag = bih->biCompression;
776 codec->pix_fmt = dshow_pixfmt(bih->biCompression, bih->biBitCount);
777 if (bih->biCompression == MKTAG('H', 'D', 'Y', 'C')) {
778 av_log(avctx, AV_LOG_DEBUG, "attempt to use full range for HDYC...\n");
779 codec->color_range = AVCOL_RANGE_MPEG; // just in case it needs this...
781 if (codec->pix_fmt == AV_PIX_FMT_NONE) {
782 const AVCodecTag *const tags[] = { avformat_get_riff_video_tags(), NULL };
783 codec->codec_id = av_codec_get_id(tags, bih->biCompression);
784 if (codec->codec_id == AV_CODEC_ID_NONE) {
785 av_log(avctx, AV_LOG_ERROR, "Unknown compression type. "
786 "Please report type 0x%X.\n", (int) bih->biCompression);
787 return AVERROR_PATCHWELCOME;
789 codec->bits_per_coded_sample = bih->biBitCount;
791 codec->codec_id = AV_CODEC_ID_RAWVIDEO;
792 if (bih->biCompression == BI_RGB || bih->biCompression == BI_BITFIELDS) {
793 codec->bits_per_coded_sample = bih->biBitCount;
794 codec->extradata = av_malloc(9 + FF_INPUT_BUFFER_PADDING_SIZE);
795 if (codec->extradata) {
796 codec->extradata_size = 9;
797 memcpy(codec->extradata, "BottomUp", 9);
802 WAVEFORMATEX *fx = NULL;
804 if (IsEqualGUID(&type.formattype, &FORMAT_WaveFormatEx)) {
805 fx = (void *) type.pbFormat;
808 av_log(avctx, AV_LOG_ERROR, "Could not get media type.\n");
812 codec->codec_type = AVMEDIA_TYPE_AUDIO;
813 codec->sample_fmt = sample_fmt_bits_per_sample(fx->wBitsPerSample);
814 codec->codec_id = waveform_codec_id(codec->sample_fmt);
815 codec->sample_rate = fx->nSamplesPerSec;
816 codec->channels = fx->nChannels;
819 avpriv_set_pts_info(st, 64, 1, 10000000);
827 static int parse_device_name(AVFormatContext *avctx)
829 struct dshow_ctx *ctx = avctx->priv_data;
830 char **device_name = ctx->device_name;
831 char *name = av_strdup(avctx->filename);
836 while ((type = strtok(tmp, "="))) {
837 char *token = strtok(NULL, ":");
840 if (!strcmp(type, "video")) {
841 device_name[0] = token;
842 } else if (!strcmp(type, "audio")) {
843 device_name[1] = token;
845 device_name[0] = NULL;
846 device_name[1] = NULL;
851 if (!device_name[0] && !device_name[1]) {
855 device_name[0] = av_strdup(device_name[0]);
857 device_name[1] = av_strdup(device_name[1]);
864 static int dshow_read_header(AVFormatContext *avctx)
866 struct dshow_ctx *ctx = avctx->priv_data;
867 IGraphBuilder *graph = NULL;
868 ICreateDevEnum *devenum = NULL;
869 IMediaControl *control = NULL;
870 IMediaEvent *media_event = NULL;
871 HANDLE media_event_handle;
873 int ret = AVERROR(EIO);
878 if (!ctx->list_devices && !parse_device_name(avctx)) {
879 av_log(avctx, AV_LOG_ERROR, "Malformed dshow input string.\n");
883 ctx->video_codec_id = avctx->video_codec_id ? avctx->video_codec_id
884 : AV_CODEC_ID_RAWVIDEO;
885 if (ctx->pixel_format != AV_PIX_FMT_NONE) {
886 if (ctx->video_codec_id != AV_CODEC_ID_RAWVIDEO) {
887 av_log(avctx, AV_LOG_ERROR, "Pixel format may only be set when "
888 "video codec is not set or set to rawvideo\n");
889 ret = AVERROR(EINVAL);
893 if (ctx->framerate) {
894 r = av_parse_video_rate(&ctx->requested_framerate, ctx->framerate);
896 av_log(avctx, AV_LOG_ERROR, "Could not parse framerate '%s'.\n", ctx->framerate);
901 r = CoCreateInstance(&CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
902 &IID_IGraphBuilder, (void **) &graph);
904 av_log(avctx, AV_LOG_ERROR, "Could not create capture graph.\n");
909 r = CoCreateInstance(&CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
910 &IID_ICreateDevEnum, (void **) &devenum);
912 av_log(avctx, AV_LOG_ERROR, "Could not enumerate system devices.\n");
916 if (ctx->list_devices) {
917 av_log(avctx, AV_LOG_INFO, "DirectShow video devices\n");
918 dshow_cycle_devices(avctx, devenum, VideoDevice, NULL);
919 av_log(avctx, AV_LOG_INFO, "DirectShow audio devices\n");
920 dshow_cycle_devices(avctx, devenum, AudioDevice, NULL);
924 if (ctx->list_options) {
925 if (ctx->device_name[VideoDevice])
926 dshow_list_device_options(avctx, devenum, VideoDevice);
927 if (ctx->device_name[AudioDevice])
928 dshow_list_device_options(avctx, devenum, AudioDevice);
933 if (ctx->device_name[VideoDevice]) {
934 if ((r = dshow_open_device(avctx, devenum, VideoDevice)) < 0 ||
935 (r = dshow_add_device(avctx, VideoDevice)) < 0) {
940 if (ctx->device_name[AudioDevice]) {
941 if ((r = dshow_open_device(avctx, devenum, AudioDevice)) < 0 ||
942 (r = dshow_add_device(avctx, AudioDevice)) < 0) {
947 ctx->curbufsize[0] = 0;
948 ctx->curbufsize[1] = 0;
949 ctx->mutex = CreateMutex(NULL, 0, NULL);
951 av_log(avctx, AV_LOG_ERROR, "Could not create Mutex\n");
954 ctx->event[1] = CreateEvent(NULL, 1, 0, NULL);
955 if (!ctx->event[1]) {
956 av_log(avctx, AV_LOG_ERROR, "Could not create Event\n");
960 r = IGraphBuilder_QueryInterface(graph, &IID_IMediaControl, (void **) &control);
962 av_log(avctx, AV_LOG_ERROR, "Could not get media control.\n");
965 ctx->control = control;
967 r = IGraphBuilder_QueryInterface(graph, &IID_IMediaEvent, (void **) &media_event);
969 av_log(avctx, AV_LOG_ERROR, "Could not get media event.\n");
972 ctx->media_event = media_event;
974 r = IMediaEvent_GetEventHandle(media_event, (void *) &media_event_handle);
976 av_log(avctx, AV_LOG_ERROR, "Could not get media event handle.\n");
979 proc = GetCurrentProcess();
980 r = DuplicateHandle(proc, media_event_handle, proc, &ctx->event[0],
981 0, 0, DUPLICATE_SAME_ACCESS);
983 av_log(avctx, AV_LOG_ERROR, "Could not duplicate media event handle.\n");
987 r = IMediaControl_Run(control);
990 r = IMediaControl_GetState(control, 0, &pfs);
993 av_log(avctx, AV_LOG_ERROR, "Could not run filter\n");
1002 ICreateDevEnum_Release(devenum);
1005 dshow_read_close(avctx);
1011 * Checks media events from DirectShow and returns -1 on error or EOF. Also
1012 * purges all events that might be in the event queue to stop the trigger
1013 * of event notification.
1015 static int dshow_check_event_queue(IMediaEvent *media_event)
1021 while (IMediaEvent_GetEvent(media_event, &code, &p1, &p2, 0) != E_ABORT) {
1022 if (code == EC_COMPLETE || code == EC_DEVICE_LOST || code == EC_ERRORABORT)
1024 IMediaEvent_FreeEventParams(media_event, code, p1, p2);
1030 static int dshow_read_packet(AVFormatContext *s, AVPacket *pkt)
1032 struct dshow_ctx *ctx = s->priv_data;
1033 AVPacketList *pktl = NULL;
1035 while (!ctx->eof && !pktl) {
1036 WaitForSingleObject(ctx->mutex, INFINITE);
1040 ctx->pktl = ctx->pktl->next;
1042 ctx->curbufsize[pkt->stream_index] -= pkt->size;
1044 ResetEvent(ctx->event[1]);
1045 ReleaseMutex(ctx->mutex);
1047 if (dshow_check_event_queue(ctx->media_event) < 0) {
1049 } else if (s->flags & AVFMT_FLAG_NONBLOCK) {
1050 return AVERROR(EAGAIN);
1052 WaitForMultipleObjects(2, ctx->event, 0, INFINITE);
1057 return ctx->eof ? AVERROR(EIO) : pkt->size;
1060 #define OFFSET(x) offsetof(struct dshow_ctx, x)
1061 #define DEC AV_OPT_FLAG_DECODING_PARAM
1062 static const AVOption options[] = {
1063 { "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 },
1064 { "pixel_format", "set video pixel format", OFFSET(pixel_format), AV_OPT_TYPE_PIXEL_FMT, {.i64 = AV_PIX_FMT_NONE}, -1, INT_MAX, DEC },
1065 { "framerate", "set video frame rate", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
1066 { "sample_rate", "set audio sample rate", OFFSET(sample_rate), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, DEC },
1067 { "sample_size", "set audio sample size", OFFSET(sample_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 16, DEC },
1068 { "channels", "set number of audio channels, such as 1 or 2", OFFSET(channels), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, DEC },
1069 { "list_devices", "list available devices", OFFSET(list_devices), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, DEC, "list_devices" },
1070 { "true", "", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, DEC, "list_devices" },
1071 { "false", "", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, DEC, "list_devices" },
1072 { "list_options", "list available options for specified device", OFFSET(list_options), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, DEC, "list_options" },
1073 { "true", "", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, DEC, "list_options" },
1074 { "false", "", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, DEC, "list_options" },
1075 { "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 },
1076 { "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 },
1077 { "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 },
1081 static const AVClass dshow_class = {
1082 .class_name = "dshow indev",
1083 .item_name = av_default_item_name,
1085 .version = LIBAVUTIL_VERSION_INT,
1086 .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
1089 AVInputFormat ff_dshow_demuxer = {
1091 .long_name = NULL_IF_CONFIG_SMALL("DirectShow capture"),
1092 .priv_data_size = sizeof(struct dshow_ctx),
1093 .read_header = dshow_read_header,
1094 .read_packet = dshow_read_packet,
1095 .read_close = dshow_read_close,
1096 .flags = AVFMT_NOFILE,
1097 .priv_class = &dshow_class,