You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

973 lines
30KB

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