dshow.c 30 KB

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