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.

960 lines
34KB

  1. /*
  2. * - CrystalHD decoder module -
  3. *
  4. * Copyright(C) 2010,2011 Philip Langdale <ffmpeg.philipl@overt.org>
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. /*
  23. * - Principles of Operation -
  24. *
  25. * The CrystalHD decoder operates at the bitstream level - which is an even
  26. * higher level than the decoding hardware you typically see in modern GPUs.
  27. * This means it has a very simple interface, in principle. You feed demuxed
  28. * packets in one end and get decoded picture (fields/frames) out the other.
  29. *
  30. * Of course, nothing is ever that simple. Due, at the very least, to b-frame
  31. * dependencies in the supported formats, the hardware has a delay between
  32. * when a packet goes in, and when a picture comes out. Furthermore, this delay
  33. * is not just a function of time, but also one of the dependency on additional
  34. * frames being fed into the decoder to satisfy the b-frame dependencies.
  35. *
  36. * As such, a pipeline will build up that is roughly equivalent to the required
  37. * DPB for the file being played. If that was all it took, things would still
  38. * be simple - so, of course, it isn't.
  39. *
  40. * The hardware has a way of indicating that a picture is ready to be copied out,
  41. * but this is unreliable - and sometimes the attempt will still fail so, based
  42. * on testing, the code will wait until 3 pictures are ready before starting
  43. * to copy out - and this has the effect of extending the pipeline.
  44. *
  45. * Finally, while it is tempting to say that once the decoder starts outputing
  46. * frames, the software should never fail to return a frame from a decode(),
  47. * this is a hard assertion to make, because the stream may switch between
  48. * differently encoded content (number of b-frames, interlacing, etc) which
  49. * might require a longer pipeline than before. If that happened, you could
  50. * deadlock trying to retrieve a frame that can't be decoded without feeding
  51. * in additional packets.
  52. *
  53. * As such, the code will return in the event that a picture cannot be copied
  54. * out, leading to an increase in the length of the pipeline. This in turn,
  55. * means we have to be sensitive to the time it takes to decode a picture;
  56. * We do not want to give up just because the hardware needed a little more
  57. * time to prepare the picture! For this reason, there are delays included
  58. * in the decode() path that ensure that, under normal conditions, the hardware
  59. * will only fail to return a frame if it really needs additional packets to
  60. * complete the decoding.
  61. *
  62. * Finally, to be explicit, we do not want the pipeline to grow without bound
  63. * for two reasons: 1) The hardware can only buffer a finite number of packets,
  64. * and 2) The client application may not be able to cope with arbitrarily long
  65. * delays in the video path relative to the audio path. For example. MPlayer
  66. * can only handle a 20 picture delay (although this is arbitrary, and needs
  67. * to be extended to fully support the CrystalHD where the delay could be up
  68. * to 32 pictures - consider PAFF H.264 content with 16 b-frames).
  69. */
  70. /*****************************************************************************
  71. * Includes
  72. ****************************************************************************/
  73. #define _XOPEN_SOURCE 600
  74. #include <inttypes.h>
  75. #include <stdio.h>
  76. #include <stdlib.h>
  77. #include <unistd.h>
  78. #include <libcrystalhd/bc_dts_types.h>
  79. #include <libcrystalhd/bc_dts_defs.h>
  80. #include <libcrystalhd/libcrystalhd_if.h>
  81. #include "avcodec.h"
  82. #include "libavutil/imgutils.h"
  83. #include "libavutil/intreadwrite.h"
  84. /** Timeout parameter passed to DtsProcOutput() in us */
  85. #define OUTPUT_PROC_TIMEOUT 50
  86. /** Step between fake timestamps passed to hardware in units of 100ns */
  87. #define TIMESTAMP_UNIT 100000
  88. /** Initial value in us of the wait in decode() */
  89. #define BASE_WAIT 10000
  90. /** Increment in us to adjust wait in decode() */
  91. #define WAIT_UNIT 1000
  92. /*****************************************************************************
  93. * Module private data
  94. ****************************************************************************/
  95. typedef enum {
  96. RET_ERROR = -1,
  97. RET_OK = 0,
  98. RET_COPY_AGAIN = 1,
  99. RET_SKIP_NEXT_COPY = 2,
  100. } CopyRet;
  101. typedef struct OpaqueList {
  102. struct OpaqueList *next;
  103. uint64_t fake_timestamp;
  104. uint64_t reordered_opaque;
  105. } OpaqueList;
  106. typedef struct {
  107. AVCodecContext *avctx;
  108. AVFrame pic;
  109. HANDLE dev;
  110. uint8_t is_70012;
  111. uint8_t *sps_pps_buf;
  112. uint32_t sps_pps_size;
  113. uint8_t is_nal;
  114. uint8_t output_ready;
  115. uint8_t need_second_field;
  116. uint8_t skip_next_output;
  117. uint64_t decode_wait;
  118. uint64_t last_picture;
  119. OpaqueList *head;
  120. OpaqueList *tail;
  121. } CHDContext;
  122. /*****************************************************************************
  123. * Helper functions
  124. ****************************************************************************/
  125. static inline BC_MEDIA_SUBTYPE id2subtype(CHDContext *priv, enum CodecID id)
  126. {
  127. switch (id) {
  128. case CODEC_ID_MPEG4:
  129. return BC_MSUBTYPE_DIVX;
  130. case CODEC_ID_MSMPEG4V3:
  131. return BC_MSUBTYPE_DIVX311;
  132. case CODEC_ID_MPEG2VIDEO:
  133. return BC_MSUBTYPE_MPEG2VIDEO;
  134. case CODEC_ID_VC1:
  135. return BC_MSUBTYPE_VC1;
  136. case CODEC_ID_WMV3:
  137. return BC_MSUBTYPE_WMV3;
  138. case CODEC_ID_H264:
  139. return priv->is_nal ? BC_MSUBTYPE_AVC1 : BC_MSUBTYPE_H264;
  140. default:
  141. return BC_MSUBTYPE_INVALID;
  142. }
  143. }
  144. static inline void print_frame_info(CHDContext *priv, BC_DTS_PROC_OUT *output)
  145. {
  146. av_log(priv->avctx, AV_LOG_VERBOSE, "\tYBuffSz: %u\n", output->YbuffSz);
  147. av_log(priv->avctx, AV_LOG_VERBOSE, "\tYBuffDoneSz: %u\n",
  148. output->YBuffDoneSz);
  149. av_log(priv->avctx, AV_LOG_VERBOSE, "\tUVBuffDoneSz: %u\n",
  150. output->UVBuffDoneSz);
  151. av_log(priv->avctx, AV_LOG_VERBOSE, "\tTimestamp: %"PRIu64"\n",
  152. output->PicInfo.timeStamp);
  153. av_log(priv->avctx, AV_LOG_VERBOSE, "\tPicture Number: %u\n",
  154. output->PicInfo.picture_number);
  155. av_log(priv->avctx, AV_LOG_VERBOSE, "\tWidth: %u\n",
  156. output->PicInfo.width);
  157. av_log(priv->avctx, AV_LOG_VERBOSE, "\tHeight: %u\n",
  158. output->PicInfo.height);
  159. av_log(priv->avctx, AV_LOG_VERBOSE, "\tChroma: 0x%03x\n",
  160. output->PicInfo.chroma_format);
  161. av_log(priv->avctx, AV_LOG_VERBOSE, "\tPulldown: %u\n",
  162. output->PicInfo.pulldown);
  163. av_log(priv->avctx, AV_LOG_VERBOSE, "\tFlags: 0x%08x\n",
  164. output->PicInfo.flags);
  165. av_log(priv->avctx, AV_LOG_VERBOSE, "\tFrame Rate/Res: %u\n",
  166. output->PicInfo.frame_rate);
  167. av_log(priv->avctx, AV_LOG_VERBOSE, "\tAspect Ratio: %u\n",
  168. output->PicInfo.aspect_ratio);
  169. av_log(priv->avctx, AV_LOG_VERBOSE, "\tColor Primaries: %u\n",
  170. output->PicInfo.colour_primaries);
  171. av_log(priv->avctx, AV_LOG_VERBOSE, "\tMetaData: %u\n",
  172. output->PicInfo.picture_meta_payload);
  173. av_log(priv->avctx, AV_LOG_VERBOSE, "\tSession Number: %u\n",
  174. output->PicInfo.sess_num);
  175. av_log(priv->avctx, AV_LOG_VERBOSE, "\tycom: %u\n",
  176. output->PicInfo.ycom);
  177. av_log(priv->avctx, AV_LOG_VERBOSE, "\tCustom Aspect: %u\n",
  178. output->PicInfo.custom_aspect_ratio_width_height);
  179. av_log(priv->avctx, AV_LOG_VERBOSE, "\tFrames to Drop: %u\n",
  180. output->PicInfo.n_drop);
  181. av_log(priv->avctx, AV_LOG_VERBOSE, "\tH264 Valid Fields: 0x%08x\n",
  182. output->PicInfo.other.h264.valid);
  183. }
  184. /*****************************************************************************
  185. * OpaqueList functions
  186. ****************************************************************************/
  187. static uint64_t opaque_list_push(CHDContext *priv, uint64_t reordered_opaque)
  188. {
  189. OpaqueList *newNode = av_mallocz(sizeof (OpaqueList));
  190. if (!newNode) {
  191. av_log(priv->avctx, AV_LOG_ERROR,
  192. "Unable to allocate new node in OpaqueList.\n");
  193. return 0;
  194. }
  195. if (!priv->head) {
  196. newNode->fake_timestamp = TIMESTAMP_UNIT;
  197. priv->head = newNode;
  198. } else {
  199. newNode->fake_timestamp = priv->tail->fake_timestamp + TIMESTAMP_UNIT;
  200. priv->tail->next = newNode;
  201. }
  202. priv->tail = newNode;
  203. newNode->reordered_opaque = reordered_opaque;
  204. return newNode->fake_timestamp;
  205. }
  206. /*
  207. * The OpaqueList is built in decode order, while elements will be removed
  208. * in presentation order. If frames are reordered, this means we must be
  209. * able to remove elements that are not the first element.
  210. */
  211. static uint64_t opaque_list_pop(CHDContext *priv, uint64_t fake_timestamp)
  212. {
  213. OpaqueList *node = priv->head;
  214. if (!priv->head) {
  215. av_log(priv->avctx, AV_LOG_ERROR,
  216. "CrystalHD: Attempted to query non-existent timestamps.\n");
  217. return AV_NOPTS_VALUE;
  218. }
  219. /*
  220. * The first element is special-cased because we have to manipulate
  221. * the head pointer rather than the previous element in the list.
  222. */
  223. if (priv->head->fake_timestamp == fake_timestamp) {
  224. uint64_t reordered_opaque = node->reordered_opaque;
  225. priv->head = node->next;
  226. av_free(node);
  227. if (!priv->head->next)
  228. priv->tail = priv->head;
  229. return reordered_opaque;
  230. }
  231. /*
  232. * The list is processed at arm's length so that we have the
  233. * previous element available to rewrite its next pointer.
  234. */
  235. while (node->next) {
  236. OpaqueList *next = node->next;
  237. if (next->fake_timestamp == fake_timestamp) {
  238. uint64_t reordered_opaque = next->reordered_opaque;
  239. node->next = next->next;
  240. av_free(next);
  241. if (!node->next)
  242. priv->tail = node;
  243. return reordered_opaque;
  244. } else {
  245. node = next;
  246. }
  247. }
  248. av_log(priv->avctx, AV_LOG_VERBOSE,
  249. "CrystalHD: Couldn't match fake_timestamp.\n");
  250. return AV_NOPTS_VALUE;
  251. }
  252. /*****************************************************************************
  253. * Video decoder API function definitions
  254. ****************************************************************************/
  255. static void flush(AVCodecContext *avctx)
  256. {
  257. CHDContext *priv = avctx->priv_data;
  258. avctx->has_b_frames = 0;
  259. priv->last_picture = -1;
  260. priv->output_ready = 0;
  261. priv->need_second_field = 0;
  262. priv->skip_next_output = 0;
  263. priv->decode_wait = BASE_WAIT;
  264. if (priv->pic.data[0])
  265. avctx->release_buffer(avctx, &priv->pic);
  266. /* Flush mode 4 flushes all software and hardware buffers. */
  267. DtsFlushInput(priv->dev, 4);
  268. }
  269. static av_cold int uninit(AVCodecContext *avctx)
  270. {
  271. CHDContext *priv = avctx->priv_data;
  272. HANDLE device;
  273. device = priv->dev;
  274. DtsStopDecoder(device);
  275. DtsCloseDecoder(device);
  276. DtsDeviceClose(device);
  277. av_free(priv->sps_pps_buf);
  278. if (priv->pic.data[0])
  279. avctx->release_buffer(avctx, &priv->pic);
  280. if (priv->head) {
  281. OpaqueList *node = priv->head;
  282. while (node) {
  283. OpaqueList *next = node->next;
  284. av_free(node);
  285. node = next;
  286. }
  287. }
  288. return 0;
  289. }
  290. static av_cold int init(AVCodecContext *avctx)
  291. {
  292. CHDContext* priv;
  293. BC_STATUS ret;
  294. BC_INFO_CRYSTAL version;
  295. BC_INPUT_FORMAT format = {
  296. .FGTEnable = FALSE,
  297. .Progressive = TRUE,
  298. .OptFlags = 0x80000000 | vdecFrameRate59_94 | 0x40,
  299. .width = avctx->width,
  300. .height = avctx->height,
  301. };
  302. BC_MEDIA_SUBTYPE subtype;
  303. uint32_t mode = DTS_PLAYBACK_MODE |
  304. DTS_LOAD_FILE_PLAY_FW |
  305. DTS_SKIP_TX_CHK_CPB |
  306. DTS_PLAYBACK_DROP_RPT_MODE |
  307. DTS_SINGLE_THREADED_MODE |
  308. DTS_DFLT_RESOLUTION(vdecRESOLUTION_1080p23_976);
  309. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD Init for %s\n",
  310. avctx->codec->name);
  311. avctx->pix_fmt = PIX_FMT_YUYV422;
  312. /* Initialize the library */
  313. priv = avctx->priv_data;
  314. priv->avctx = avctx;
  315. priv->is_nal = avctx->extradata_size > 0 && *(avctx->extradata) == 1;
  316. priv->last_picture = -1;
  317. priv->decode_wait = BASE_WAIT;
  318. subtype = id2subtype(priv, avctx->codec->id);
  319. switch (subtype) {
  320. case BC_MSUBTYPE_AVC1:
  321. {
  322. uint8_t *dummy_p;
  323. int dummy_int;
  324. AVBitStreamFilterContext *bsfc;
  325. uint32_t orig_data_size = avctx->extradata_size;
  326. uint8_t *orig_data = av_malloc(orig_data_size);
  327. if (!orig_data) {
  328. av_log(avctx, AV_LOG_ERROR,
  329. "Failed to allocate copy of extradata\n");
  330. return AVERROR(ENOMEM);
  331. }
  332. memcpy(orig_data, avctx->extradata, orig_data_size);
  333. bsfc = av_bitstream_filter_init("h264_mp4toannexb");
  334. if (!bsfc) {
  335. av_log(avctx, AV_LOG_ERROR,
  336. "Cannot open the h264_mp4toannexb BSF!\n");
  337. av_free(orig_data);
  338. return AVERROR_BSF_NOT_FOUND;
  339. }
  340. av_bitstream_filter_filter(bsfc, avctx, NULL, &dummy_p,
  341. &dummy_int, NULL, 0, 0);
  342. av_bitstream_filter_close(bsfc);
  343. priv->sps_pps_buf = avctx->extradata;
  344. priv->sps_pps_size = avctx->extradata_size;
  345. avctx->extradata = orig_data;
  346. avctx->extradata_size = orig_data_size;
  347. format.pMetaData = priv->sps_pps_buf;
  348. format.metaDataSz = priv->sps_pps_size;
  349. format.startCodeSz = (avctx->extradata[4] & 0x03) + 1;
  350. }
  351. break;
  352. case BC_MSUBTYPE_H264:
  353. format.startCodeSz = 4;
  354. // Fall-through
  355. case BC_MSUBTYPE_VC1:
  356. case BC_MSUBTYPE_WVC1:
  357. case BC_MSUBTYPE_WMV3:
  358. case BC_MSUBTYPE_WMVA:
  359. case BC_MSUBTYPE_MPEG2VIDEO:
  360. case BC_MSUBTYPE_DIVX:
  361. case BC_MSUBTYPE_DIVX311:
  362. format.pMetaData = avctx->extradata;
  363. format.metaDataSz = avctx->extradata_size;
  364. break;
  365. default:
  366. av_log(avctx, AV_LOG_ERROR, "CrystalHD: Unknown codec name\n");
  367. return AVERROR(EINVAL);
  368. }
  369. format.mSubtype = subtype;
  370. /* Get a decoder instance */
  371. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: starting up\n");
  372. // Initialize the Link and Decoder devices
  373. ret = DtsDeviceOpen(&priv->dev, mode);
  374. if (ret != BC_STS_SUCCESS) {
  375. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: DtsDeviceOpen failed\n");
  376. goto fail;
  377. }
  378. ret = DtsCrystalHDVersion(priv->dev, &version);
  379. if (ret != BC_STS_SUCCESS) {
  380. av_log(avctx, AV_LOG_VERBOSE,
  381. "CrystalHD: DtsCrystalHDVersion failed\n");
  382. goto fail;
  383. }
  384. priv->is_70012 = version.device == 0;
  385. if (priv->is_70012 &&
  386. (subtype == BC_MSUBTYPE_DIVX || subtype == BC_MSUBTYPE_DIVX311)) {
  387. av_log(avctx, AV_LOG_VERBOSE,
  388. "CrystalHD: BCM70012 doesn't support MPEG4-ASP/DivX/Xvid\n");
  389. goto fail;
  390. }
  391. ret = DtsSetInputFormat(priv->dev, &format);
  392. if (ret != BC_STS_SUCCESS) {
  393. av_log(avctx, AV_LOG_ERROR, "CrystalHD: SetInputFormat failed\n");
  394. goto fail;
  395. }
  396. ret = DtsOpenDecoder(priv->dev, BC_STREAM_TYPE_ES);
  397. if (ret != BC_STS_SUCCESS) {
  398. av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsOpenDecoder failed\n");
  399. goto fail;
  400. }
  401. ret = DtsSetColorSpace(priv->dev, OUTPUT_MODE422_YUY2);
  402. if (ret != BC_STS_SUCCESS) {
  403. av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsSetColorSpace failed\n");
  404. goto fail;
  405. }
  406. ret = DtsStartDecoder(priv->dev);
  407. if (ret != BC_STS_SUCCESS) {
  408. av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartDecoder failed\n");
  409. goto fail;
  410. }
  411. ret = DtsStartCapture(priv->dev);
  412. if (ret != BC_STS_SUCCESS) {
  413. av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartCapture failed\n");
  414. goto fail;
  415. }
  416. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Init complete.\n");
  417. return 0;
  418. fail:
  419. uninit(avctx);
  420. return -1;
  421. }
  422. /*
  423. * The CrystalHD doesn't report interlaced H.264 content in a way that allows
  424. * us to distinguish between specific cases that require different handling.
  425. * So, for now, we have to hard-code the behaviour we want.
  426. *
  427. * The default behaviour is to assume MBAFF with input and output fieldpairs.
  428. *
  429. * Define ASSUME_PAFF_OVER_MBAFF to treat input as PAFF with separate input
  430. * and output fields.
  431. *
  432. * Define ASSUME_TWO_INPUTS_ONE_OUTPUT to treat input as separate fields but
  433. * output as a single fieldpair.
  434. *
  435. * Define both to mess up your playback.
  436. */
  437. #define ASSUME_PAFF_OVER_MBAFF 0
  438. #define ASSUME_TWO_INPUTS_ONE_OUTPUT 0
  439. static inline CopyRet copy_frame(AVCodecContext *avctx,
  440. BC_DTS_PROC_OUT *output,
  441. void *data, int *data_size,
  442. uint8_t second_field)
  443. {
  444. BC_STATUS ret;
  445. BC_DTS_STATUS decoder_status;
  446. uint8_t is_paff;
  447. uint8_t next_frame_same;
  448. uint8_t interlaced;
  449. CHDContext *priv = avctx->priv_data;
  450. uint8_t bottom_field = (output->PicInfo.flags & VDEC_FLAG_BOTTOMFIELD) ==
  451. VDEC_FLAG_BOTTOMFIELD;
  452. uint8_t bottom_first = !!(output->PicInfo.flags & VDEC_FLAG_BOTTOM_FIRST);
  453. int width = output->PicInfo.width;
  454. int height = output->PicInfo.height;
  455. int bwidth;
  456. uint8_t *src = output->Ybuff;
  457. int sStride;
  458. uint8_t *dst;
  459. int dStride;
  460. ret = DtsGetDriverStatus(priv->dev, &decoder_status);
  461. if (ret != BC_STS_SUCCESS) {
  462. av_log(avctx, AV_LOG_ERROR,
  463. "CrystalHD: GetDriverStatus failed: %u\n", ret);
  464. return RET_ERROR;
  465. }
  466. is_paff = ASSUME_PAFF_OVER_MBAFF ||
  467. !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC);
  468. next_frame_same = output->PicInfo.picture_number ==
  469. (decoder_status.picNumFlags & ~0x40000000);
  470. interlaced = ((output->PicInfo.flags &
  471. VDEC_FLAG_INTERLACED_SRC) && is_paff) ||
  472. next_frame_same || bottom_field || second_field;
  473. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: next_frame_same: %u | %u | %u\n",
  474. next_frame_same, output->PicInfo.picture_number,
  475. decoder_status.picNumFlags & ~0x40000000);
  476. if (priv->pic.data[0] && !priv->need_second_field)
  477. avctx->release_buffer(avctx, &priv->pic);
  478. priv->need_second_field = interlaced && !priv->need_second_field;
  479. priv->pic.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE |
  480. FF_BUFFER_HINTS_REUSABLE;
  481. if (!priv->pic.data[0]) {
  482. if (avctx->get_buffer(avctx, &priv->pic) < 0) {
  483. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  484. return RET_ERROR;
  485. }
  486. }
  487. bwidth = av_image_get_linesize(avctx->pix_fmt, width, 0);
  488. if (priv->is_70012) {
  489. int pStride;
  490. if (width <= 720)
  491. pStride = 720;
  492. else if (width <= 1280)
  493. pStride = 1280;
  494. else if (width <= 1080)
  495. pStride = 1080;
  496. sStride = av_image_get_linesize(avctx->pix_fmt, pStride, 0);
  497. } else {
  498. sStride = bwidth;
  499. }
  500. dStride = priv->pic.linesize[0];
  501. dst = priv->pic.data[0];
  502. av_log(priv->avctx, AV_LOG_VERBOSE, "CrystalHD: Copying out frame\n");
  503. if (interlaced) {
  504. int dY = 0;
  505. int sY = 0;
  506. height /= 2;
  507. if (bottom_field) {
  508. av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: bottom field\n");
  509. dY = 1;
  510. } else {
  511. av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: top field\n");
  512. dY = 0;
  513. }
  514. for (sY = 0; sY < height; dY++, sY++) {
  515. memcpy(&(dst[dY * dStride]), &(src[sY * sStride]), bwidth);
  516. dY++;
  517. }
  518. } else {
  519. av_image_copy_plane(dst, dStride, src, sStride, bwidth, height);
  520. }
  521. priv->pic.interlaced_frame = interlaced;
  522. if (interlaced)
  523. priv->pic.top_field_first = !bottom_first;
  524. if (output->PicInfo.timeStamp != 0) {
  525. priv->pic.pkt_pts = opaque_list_pop(priv, output->PicInfo.timeStamp);
  526. av_log(avctx, AV_LOG_VERBOSE, "output \"pts\": %"PRIu64"\n",
  527. priv->pic.pkt_pts);
  528. }
  529. if (!priv->need_second_field) {
  530. *data_size = sizeof(AVFrame);
  531. *(AVFrame *)data = priv->pic;
  532. }
  533. if (ASSUME_TWO_INPUTS_ONE_OUTPUT &&
  534. output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) {
  535. av_log(priv->avctx, AV_LOG_VERBOSE, "Fieldpair from two packets.\n");
  536. return RET_SKIP_NEXT_COPY;
  537. }
  538. return RET_OK;
  539. }
  540. static inline CopyRet receive_frame(AVCodecContext *avctx,
  541. void *data, int *data_size,
  542. uint8_t second_field)
  543. {
  544. BC_STATUS ret;
  545. BC_DTS_PROC_OUT output = {
  546. .PicInfo.width = avctx->width,
  547. .PicInfo.height = avctx->height,
  548. };
  549. CHDContext *priv = avctx->priv_data;
  550. HANDLE dev = priv->dev;
  551. *data_size = 0;
  552. // Request decoded data from the driver
  553. ret = DtsProcOutputNoCopy(dev, OUTPUT_PROC_TIMEOUT, &output);
  554. if (ret == BC_STS_FMT_CHANGE) {
  555. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Initial format change\n");
  556. avctx->width = output.PicInfo.width;
  557. avctx->height = output.PicInfo.height;
  558. return RET_COPY_AGAIN;
  559. } else if (ret == BC_STS_SUCCESS) {
  560. int copy_ret = -1;
  561. if (output.PoutFlags & BC_POUT_FLAGS_PIB_VALID) {
  562. if (priv->last_picture == -1) {
  563. /*
  564. * Init to one less, so that the incrementing code doesn't
  565. * need to be special-cased.
  566. */
  567. priv->last_picture = output.PicInfo.picture_number - 1;
  568. }
  569. if (avctx->codec->id == CODEC_ID_MPEG4 &&
  570. output.PicInfo.timeStamp == 0) {
  571. av_log(avctx, AV_LOG_VERBOSE,
  572. "CrystalHD: Not returning packed frame twice.\n");
  573. priv->last_picture++;
  574. DtsReleaseOutputBuffs(dev, NULL, FALSE);
  575. return RET_COPY_AGAIN;
  576. }
  577. print_frame_info(priv, &output);
  578. if (priv->last_picture + 1 < output.PicInfo.picture_number) {
  579. av_log(avctx, AV_LOG_WARNING,
  580. "CrystalHD: Picture Number discontinuity\n");
  581. /*
  582. * Have we lost frames? If so, we need to shrink the
  583. * pipeline length appropriately.
  584. *
  585. * XXX: I have no idea what the semantics of this situation
  586. * are so I don't even know if we've lost frames or which
  587. * ones.
  588. *
  589. * In any case, only warn the first time.
  590. */
  591. priv->last_picture = output.PicInfo.picture_number - 1;
  592. }
  593. copy_ret = copy_frame(avctx, &output, data, data_size, second_field);
  594. if (*data_size > 0) {
  595. avctx->has_b_frames--;
  596. priv->last_picture++;
  597. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Pipeline length: %u\n",
  598. avctx->has_b_frames);
  599. }
  600. } else {
  601. /*
  602. * An invalid frame has been consumed.
  603. */
  604. av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput succeeded with "
  605. "invalid PIB\n");
  606. avctx->has_b_frames--;
  607. copy_ret = RET_OK;
  608. }
  609. DtsReleaseOutputBuffs(dev, NULL, FALSE);
  610. return copy_ret;
  611. } else if (ret == BC_STS_BUSY) {
  612. return RET_COPY_AGAIN;
  613. } else {
  614. av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput failed %d\n", ret);
  615. return RET_ERROR;
  616. }
  617. }
  618. static int decode(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
  619. {
  620. BC_STATUS ret;
  621. BC_DTS_STATUS decoder_status;
  622. CopyRet rec_ret;
  623. CHDContext *priv = avctx->priv_data;
  624. HANDLE dev = priv->dev;
  625. int len = avpkt->size;
  626. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: decode_frame\n");
  627. if (len) {
  628. int32_t tx_free = (int32_t)DtsTxFreeSize(dev);
  629. if (len < tx_free - 1024) {
  630. /*
  631. * Despite being notionally opaque, either libcrystalhd or
  632. * the hardware itself will mangle pts values that are too
  633. * small or too large. The docs claim it should be in units
  634. * of 100ns. Given that we're nominally dealing with a black
  635. * box on both sides, any transform we do has no guarantee of
  636. * avoiding mangling so we need to build a mapping to values
  637. * we know will not be mangled.
  638. */
  639. uint64_t pts = opaque_list_push(priv, avctx->pkt->pts);
  640. if (!pts) {
  641. return AVERROR(ENOMEM);
  642. }
  643. av_log(priv->avctx, AV_LOG_VERBOSE,
  644. "input \"pts\": %"PRIu64"\n", pts);
  645. ret = DtsProcInput(dev, avpkt->data, len, pts, 0);
  646. if (ret == BC_STS_BUSY) {
  647. av_log(avctx, AV_LOG_WARNING,
  648. "CrystalHD: ProcInput returned busy\n");
  649. usleep(BASE_WAIT);
  650. return AVERROR(EBUSY);
  651. } else if (ret != BC_STS_SUCCESS) {
  652. av_log(avctx, AV_LOG_ERROR,
  653. "CrystalHD: ProcInput failed: %u\n", ret);
  654. return -1;
  655. }
  656. avctx->has_b_frames++;
  657. } else {
  658. av_log(avctx, AV_LOG_WARNING, "CrystalHD: Input buffer full\n");
  659. len = 0; // We didn't consume any bytes.
  660. }
  661. } else {
  662. av_log(avctx, AV_LOG_INFO, "CrystalHD: No more input data\n");
  663. }
  664. if (priv->skip_next_output) {
  665. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Skipping next output.\n");
  666. priv->skip_next_output = 0;
  667. avctx->has_b_frames--;
  668. return len;
  669. }
  670. ret = DtsGetDriverStatus(dev, &decoder_status);
  671. if (ret != BC_STS_SUCCESS) {
  672. av_log(avctx, AV_LOG_ERROR, "CrystalHD: GetDriverStatus failed\n");
  673. return -1;
  674. }
  675. /*
  676. * No frames ready. Don't try to extract.
  677. *
  678. * Empirical testing shows that ReadyListCount can be a damn lie,
  679. * and ProcOut still fails when count > 0. The same testing showed
  680. * that two more iterations were needed before ProcOutput would
  681. * succeed.
  682. */
  683. if (priv->output_ready < 2) {
  684. if (decoder_status.ReadyListCount != 0)
  685. priv->output_ready++;
  686. usleep(BASE_WAIT);
  687. av_log(avctx, AV_LOG_INFO, "CrystalHD: Filling pipeline.\n");
  688. return len;
  689. } else if (decoder_status.ReadyListCount == 0) {
  690. /*
  691. * After the pipeline is established, if we encounter a lack of frames
  692. * that probably means we're not giving the hardware enough time to
  693. * decode them, so start increasing the wait time at the end of a
  694. * decode call.
  695. */
  696. usleep(BASE_WAIT);
  697. priv->decode_wait += WAIT_UNIT;
  698. av_log(avctx, AV_LOG_INFO, "CrystalHD: No frames ready. Returning\n");
  699. return len;
  700. }
  701. do {
  702. rec_ret = receive_frame(avctx, data, data_size, 0);
  703. if (rec_ret == 0 && *data_size == 0) {
  704. if (avctx->codec->id == CODEC_ID_H264) {
  705. /*
  706. * This case is for when the encoded fields are stored
  707. * separately and we get a separate avpkt for each one. To keep
  708. * the pipeline stable, we should return nothing and wait for
  709. * the next time round to grab the second field.
  710. * H.264 PAFF is an example of this.
  711. */
  712. av_log(avctx, AV_LOG_VERBOSE, "Returning after first field.\n");
  713. avctx->has_b_frames--;
  714. } else {
  715. /*
  716. * This case is for when the encoded fields are stored in a
  717. * single avpkt but the hardware returns then separately. Unless
  718. * we grab the second field before returning, we'll slip another
  719. * frame in the pipeline and if that happens a lot, we're sunk.
  720. * So we have to get that second field now.
  721. * Interlaced mpeg2 and vc1 are examples of this.
  722. */
  723. av_log(avctx, AV_LOG_VERBOSE, "Trying to get second field.\n");
  724. while (1) {
  725. usleep(priv->decode_wait);
  726. ret = DtsGetDriverStatus(dev, &decoder_status);
  727. if (ret == BC_STS_SUCCESS &&
  728. decoder_status.ReadyListCount > 0) {
  729. rec_ret = receive_frame(avctx, data, data_size, 1);
  730. if ((rec_ret == 0 && *data_size > 0) ||
  731. rec_ret == RET_ERROR)
  732. break;
  733. }
  734. }
  735. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Got second field.\n");
  736. }
  737. } else if (rec_ret == RET_SKIP_NEXT_COPY) {
  738. /*
  739. * Two input packets got turned into a field pair. Gawd.
  740. */
  741. av_log(avctx, AV_LOG_VERBOSE,
  742. "Don't output on next decode call.\n");
  743. priv->skip_next_output = 1;
  744. }
  745. /*
  746. * If rec_ret == RET_COPY_AGAIN, that means that either we just handled
  747. * a FMT_CHANGE event and need to go around again for the actual frame,
  748. * we got a busy status and need to try again, or we're dealing with
  749. * packed b-frames, where the hardware strangely returns the packed
  750. * p-frame twice. We choose to keep the second copy as it carries the
  751. * valid pts.
  752. */
  753. } while (rec_ret == RET_COPY_AGAIN);
  754. usleep(priv->decode_wait);
  755. return len;
  756. }
  757. #if CONFIG_H264_CRYSTALHD_DECODER
  758. AVCodec ff_h264_crystalhd_decoder = {
  759. .name = "h264_crystalhd",
  760. .type = AVMEDIA_TYPE_VIDEO,
  761. .id = CODEC_ID_H264,
  762. .priv_data_size = sizeof(CHDContext),
  763. .init = init,
  764. .close = uninit,
  765. .decode = decode,
  766. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
  767. .flush = flush,
  768. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (CrystalHD acceleration)"),
  769. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
  770. };
  771. #endif
  772. #if CONFIG_MPEG2_CRYSTALHD_DECODER
  773. AVCodec ff_mpeg2_crystalhd_decoder = {
  774. .name = "mpeg2_crystalhd",
  775. .type = AVMEDIA_TYPE_VIDEO,
  776. .id = CODEC_ID_MPEG2VIDEO,
  777. .priv_data_size = sizeof(CHDContext),
  778. .init = init,
  779. .close = uninit,
  780. .decode = decode,
  781. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
  782. .flush = flush,
  783. .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 Video (CrystalHD acceleration)"),
  784. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
  785. };
  786. #endif
  787. #if CONFIG_MPEG4_CRYSTALHD_DECODER
  788. AVCodec ff_mpeg4_crystalhd_decoder = {
  789. .name = "mpeg4_crystalhd",
  790. .type = AVMEDIA_TYPE_VIDEO,
  791. .id = CODEC_ID_MPEG4,
  792. .priv_data_size = sizeof(CHDContext),
  793. .init = init,
  794. .close = uninit,
  795. .decode = decode,
  796. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
  797. .flush = flush,
  798. .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 (CrystalHD acceleration)"),
  799. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
  800. };
  801. #endif
  802. #if CONFIG_MSMPEG4_CRYSTALHD_DECODER
  803. AVCodec ff_msmpeg4_crystalhd_decoder = {
  804. .name = "msmpeg4_crystalhd",
  805. .type = AVMEDIA_TYPE_VIDEO,
  806. .id = CODEC_ID_MSMPEG4V3,
  807. .priv_data_size = sizeof(CHDContext),
  808. .init = init,
  809. .close = uninit,
  810. .decode = decode,
  811. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
  812. .flush = flush,
  813. .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 Microsoft variant version 3 (CrystalHD acceleration)"),
  814. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
  815. };
  816. #endif
  817. #if CONFIG_VC1_CRYSTALHD_DECODER
  818. AVCodec ff_vc1_crystalhd_decoder = {
  819. .name = "vc1_crystalhd",
  820. .type = AVMEDIA_TYPE_VIDEO,
  821. .id = CODEC_ID_VC1,
  822. .priv_data_size = sizeof(CHDContext),
  823. .init = init,
  824. .close = uninit,
  825. .decode = decode,
  826. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
  827. .flush = flush,
  828. .long_name = NULL_IF_CONFIG_SMALL("SMPTE VC-1 (CrystalHD acceleration)"),
  829. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
  830. };
  831. #endif
  832. #if CONFIG_WMV3_CRYSTALHD_DECODER
  833. AVCodec ff_wmv3_crystalhd_decoder = {
  834. .name = "wmv3_crystalhd",
  835. .type = AVMEDIA_TYPE_VIDEO,
  836. .id = CODEC_ID_WMV3,
  837. .priv_data_size = sizeof(CHDContext),
  838. .init = init,
  839. .close = uninit,
  840. .decode = decode,
  841. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
  842. .flush = flush,
  843. .long_name = NULL_IF_CONFIG_SMALL("Windows Media Video 9 (CrystalHD acceleration)"),
  844. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
  845. };
  846. #endif