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.

961 lines
34KB

  1. /*
  2. * - CrystalHD decoder module -
  3. *
  4. * Copyright(C) 2010 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. if (interlaced)
  517. dY++;
  518. }
  519. } else {
  520. av_image_copy_plane(dst, dStride, src, sStride, bwidth, height);
  521. }
  522. priv->pic.interlaced_frame = interlaced;
  523. if (interlaced)
  524. priv->pic.top_field_first = !bottom_first;
  525. if (output->PicInfo.timeStamp != 0) {
  526. priv->pic.pkt_pts = opaque_list_pop(priv, output->PicInfo.timeStamp);
  527. av_log(avctx, AV_LOG_VERBOSE, "output \"pts\": %"PRIu64"\n",
  528. priv->pic.pkt_pts);
  529. }
  530. if (!priv->need_second_field) {
  531. *data_size = sizeof(AVFrame);
  532. *(AVFrame *)data = priv->pic;
  533. }
  534. if (ASSUME_TWO_INPUTS_ONE_OUTPUT &&
  535. output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) {
  536. av_log(priv->avctx, AV_LOG_VERBOSE, "Fieldpair from two packets.\n");
  537. return RET_SKIP_NEXT_COPY;
  538. }
  539. return RET_OK;
  540. }
  541. static inline CopyRet receive_frame(AVCodecContext *avctx,
  542. void *data, int *data_size,
  543. uint8_t second_field)
  544. {
  545. BC_STATUS ret;
  546. BC_DTS_PROC_OUT output = {
  547. .PicInfo.width = avctx->width,
  548. .PicInfo.height = avctx->height,
  549. };
  550. CHDContext *priv = avctx->priv_data;
  551. HANDLE dev = priv->dev;
  552. *data_size = 0;
  553. // Request decoded data from the driver
  554. ret = DtsProcOutputNoCopy(dev, OUTPUT_PROC_TIMEOUT, &output);
  555. if (ret == BC_STS_FMT_CHANGE) {
  556. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Initial format change\n");
  557. avctx->width = output.PicInfo.width;
  558. avctx->height = output.PicInfo.height;
  559. return RET_COPY_AGAIN;
  560. } else if (ret == BC_STS_SUCCESS) {
  561. int copy_ret = -1;
  562. if (output.PoutFlags & BC_POUT_FLAGS_PIB_VALID) {
  563. if (priv->last_picture == -1) {
  564. /*
  565. * Init to one less, so that the incrementing code doesn't
  566. * need to be special-cased.
  567. */
  568. priv->last_picture = output.PicInfo.picture_number - 1;
  569. }
  570. if (avctx->codec->id == CODEC_ID_MPEG4 &&
  571. output.PicInfo.timeStamp == 0) {
  572. av_log(avctx, AV_LOG_VERBOSE,
  573. "CrystalHD: Not returning packed frame twice.\n");
  574. priv->last_picture++;
  575. DtsReleaseOutputBuffs(dev, NULL, FALSE);
  576. return RET_COPY_AGAIN;
  577. }
  578. print_frame_info(priv, &output);
  579. if (priv->last_picture + 1 < output.PicInfo.picture_number) {
  580. av_log(avctx, AV_LOG_WARNING,
  581. "CrystalHD: Picture Number discontinuity\n");
  582. /*
  583. * Have we lost frames? If so, we need to shrink the
  584. * pipeline length appropriately.
  585. *
  586. * XXX: I have no idea what the semantics of this situation
  587. * are so I don't even know if we've lost frames or which
  588. * ones.
  589. *
  590. * In any case, only warn the first time.
  591. */
  592. priv->last_picture = output.PicInfo.picture_number - 1;
  593. }
  594. copy_ret = copy_frame(avctx, &output, data, data_size, second_field);
  595. if (*data_size > 0) {
  596. avctx->has_b_frames--;
  597. priv->last_picture++;
  598. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Pipeline length: %u\n",
  599. avctx->has_b_frames);
  600. }
  601. } else {
  602. /*
  603. * An invalid frame has been consumed.
  604. */
  605. av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput succeeded with "
  606. "invalid PIB\n");
  607. avctx->has_b_frames--;
  608. copy_ret = RET_OK;
  609. }
  610. DtsReleaseOutputBuffs(dev, NULL, FALSE);
  611. return copy_ret;
  612. } else if (ret == BC_STS_BUSY) {
  613. return RET_COPY_AGAIN;
  614. } else {
  615. av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput failed %d\n", ret);
  616. return RET_ERROR;
  617. }
  618. }
  619. static int decode(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
  620. {
  621. BC_STATUS ret;
  622. BC_DTS_STATUS decoder_status;
  623. CopyRet rec_ret;
  624. CHDContext *priv = avctx->priv_data;
  625. HANDLE dev = priv->dev;
  626. int len = avpkt->size;
  627. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: decode_frame\n");
  628. if (len) {
  629. int32_t tx_free = (int32_t)DtsTxFreeSize(dev);
  630. if (len < tx_free - 1024) {
  631. /*
  632. * Despite being notionally opaque, either libcrystalhd or
  633. * the hardware itself will mangle pts values that are too
  634. * small or too large. The docs claim it should be in units
  635. * of 100ns. Given that we're nominally dealing with a black
  636. * box on both sides, any transform we do has no guarantee of
  637. * avoiding mangling so we need to build a mapping to values
  638. * we know will not be mangled.
  639. */
  640. uint64_t pts = opaque_list_push(priv, avctx->pkt->pts);
  641. if (!pts) {
  642. return AVERROR(ENOMEM);
  643. }
  644. av_log(priv->avctx, AV_LOG_VERBOSE,
  645. "input \"pts\": %"PRIu64"\n", pts);
  646. ret = DtsProcInput(dev, avpkt->data, len, pts, 0);
  647. if (ret == BC_STS_BUSY) {
  648. av_log(avctx, AV_LOG_WARNING,
  649. "CrystalHD: ProcInput returned busy\n");
  650. usleep(BASE_WAIT);
  651. return AVERROR(EBUSY);
  652. } else if (ret != BC_STS_SUCCESS) {
  653. av_log(avctx, AV_LOG_ERROR,
  654. "CrystalHD: ProcInput failed: %u\n", ret);
  655. return -1;
  656. }
  657. avctx->has_b_frames++;
  658. } else {
  659. av_log(avctx, AV_LOG_WARNING, "CrystalHD: Input buffer full\n");
  660. len = 0; // We didn't consume any bytes.
  661. }
  662. } else {
  663. av_log(avctx, AV_LOG_INFO, "CrystalHD: No more input data\n");
  664. }
  665. if (priv->skip_next_output) {
  666. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Skipping next output.\n");
  667. priv->skip_next_output = 0;
  668. avctx->has_b_frames--;
  669. return len;
  670. }
  671. ret = DtsGetDriverStatus(dev, &decoder_status);
  672. if (ret != BC_STS_SUCCESS) {
  673. av_log(avctx, AV_LOG_ERROR, "CrystalHD: GetDriverStatus failed\n");
  674. return -1;
  675. }
  676. /*
  677. * No frames ready. Don't try to extract.
  678. *
  679. * Empirical testing shows that ReadyListCount can be a damn lie,
  680. * and ProcOut still fails when count > 0. The same testing showed
  681. * that two more iterations were needed before ProcOutput would
  682. * succeed.
  683. */
  684. if (priv->output_ready < 2) {
  685. if (decoder_status.ReadyListCount != 0)
  686. priv->output_ready++;
  687. usleep(BASE_WAIT);
  688. av_log(avctx, AV_LOG_INFO, "CrystalHD: Filling pipeline.\n");
  689. return len;
  690. } else if (decoder_status.ReadyListCount == 0) {
  691. /*
  692. * After the pipeline is established, if we encounter a lack of frames
  693. * that probably means we're not giving the hardware enough time to
  694. * decode them, so start increasing the wait time at the end of a
  695. * decode call.
  696. */
  697. usleep(BASE_WAIT);
  698. priv->decode_wait += WAIT_UNIT;
  699. av_log(avctx, AV_LOG_INFO, "CrystalHD: No frames ready. Returning\n");
  700. return len;
  701. }
  702. do {
  703. rec_ret = receive_frame(avctx, data, data_size, 0);
  704. if (rec_ret == 0 && *data_size == 0) {
  705. if (avctx->codec->id == CODEC_ID_H264) {
  706. /*
  707. * This case is for when the encoded fields are stored
  708. * separately and we get a separate avpkt for each one. To keep
  709. * the pipeline stable, we should return nothing and wait for
  710. * the next time round to grab the second field.
  711. * H.264 PAFF is an example of this.
  712. */
  713. av_log(avctx, AV_LOG_VERBOSE, "Returning after first field.\n");
  714. avctx->has_b_frames--;
  715. } else {
  716. /*
  717. * This case is for when the encoded fields are stored in a
  718. * single avpkt but the hardware returns then separately. Unless
  719. * we grab the second field before returning, we'll slip another
  720. * frame in the pipeline and if that happens a lot, we're sunk.
  721. * So we have to get that second field now.
  722. * Interlaced mpeg2 and vc1 are examples of this.
  723. */
  724. av_log(avctx, AV_LOG_VERBOSE, "Trying to get second field.\n");
  725. while (1) {
  726. usleep(priv->decode_wait);
  727. ret = DtsGetDriverStatus(dev, &decoder_status);
  728. if (ret == BC_STS_SUCCESS &&
  729. decoder_status.ReadyListCount > 0) {
  730. rec_ret = receive_frame(avctx, data, data_size, 1);
  731. if ((rec_ret == 0 && *data_size > 0) ||
  732. rec_ret == RET_ERROR)
  733. break;
  734. }
  735. }
  736. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Got second field.\n");
  737. }
  738. } else if (rec_ret == RET_SKIP_NEXT_COPY) {
  739. /*
  740. * Two input packets got turned into a field pair. Gawd.
  741. */
  742. av_log(avctx, AV_LOG_VERBOSE,
  743. "Don't output on next decode call.\n");
  744. priv->skip_next_output = 1;
  745. }
  746. /*
  747. * If rec_ret == RET_COPY_AGAIN, that means that either we just handled
  748. * a FMT_CHANGE event and need to go around again for the actual frame,
  749. * we got a busy status and need to try again, or we're dealing with
  750. * packed b-frames, where the hardware strangely returns the packed
  751. * p-frame twice. We choose to keep the second copy as it carries the
  752. * valid pts.
  753. */
  754. } while (rec_ret == RET_COPY_AGAIN);
  755. usleep(priv->decode_wait);
  756. return len;
  757. }
  758. #if CONFIG_H264_CRYSTALHD_DECODER
  759. AVCodec ff_h264_crystalhd_decoder = {
  760. .name = "h264_crystalhd",
  761. .type = AVMEDIA_TYPE_VIDEO,
  762. .id = CODEC_ID_H264,
  763. .priv_data_size = sizeof(CHDContext),
  764. .init = init,
  765. .close = uninit,
  766. .decode = decode,
  767. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
  768. .flush = flush,
  769. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (CrystalHD acceleration)"),
  770. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
  771. };
  772. #endif
  773. #if CONFIG_MPEG2_CRYSTALHD_DECODER
  774. AVCodec ff_mpeg2_crystalhd_decoder = {
  775. .name = "mpeg2_crystalhd",
  776. .type = AVMEDIA_TYPE_VIDEO,
  777. .id = CODEC_ID_MPEG2VIDEO,
  778. .priv_data_size = sizeof(CHDContext),
  779. .init = init,
  780. .close = uninit,
  781. .decode = decode,
  782. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
  783. .flush = flush,
  784. .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 Video (CrystalHD acceleration)"),
  785. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
  786. };
  787. #endif
  788. #if CONFIG_MPEG4_CRYSTALHD_DECODER
  789. AVCodec ff_mpeg4_crystalhd_decoder = {
  790. .name = "mpeg4_crystalhd",
  791. .type = AVMEDIA_TYPE_VIDEO,
  792. .id = CODEC_ID_MPEG4,
  793. .priv_data_size = sizeof(CHDContext),
  794. .init = init,
  795. .close = uninit,
  796. .decode = decode,
  797. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
  798. .flush = flush,
  799. .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 (CrystalHD acceleration)"),
  800. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
  801. };
  802. #endif
  803. #if CONFIG_MSMPEG4_CRYSTALHD_DECODER
  804. AVCodec ff_msmpeg4_crystalhd_decoder = {
  805. .name = "msmpeg4_crystalhd",
  806. .type = AVMEDIA_TYPE_VIDEO,
  807. .id = CODEC_ID_MSMPEG4V3,
  808. .priv_data_size = sizeof(CHDContext),
  809. .init = init,
  810. .close = uninit,
  811. .decode = decode,
  812. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
  813. .flush = flush,
  814. .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 Microsoft variant version 3 (CrystalHD acceleration)"),
  815. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
  816. };
  817. #endif
  818. #if CONFIG_VC1_CRYSTALHD_DECODER
  819. AVCodec ff_vc1_crystalhd_decoder = {
  820. .name = "vc1_crystalhd",
  821. .type = AVMEDIA_TYPE_VIDEO,
  822. .id = CODEC_ID_VC1,
  823. .priv_data_size = sizeof(CHDContext),
  824. .init = init,
  825. .close = uninit,
  826. .decode = decode,
  827. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
  828. .flush = flush,
  829. .long_name = NULL_IF_CONFIG_SMALL("SMPTE VC-1 (CrystalHD acceleration)"),
  830. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
  831. };
  832. #endif
  833. #if CONFIG_WMV3_CRYSTALHD_DECODER
  834. AVCodec ff_wmv3_crystalhd_decoder = {
  835. .name = "wmv3_crystalhd",
  836. .type = AVMEDIA_TYPE_VIDEO,
  837. .id = CODEC_ID_WMV3,
  838. .priv_data_size = sizeof(CHDContext),
  839. .init = init,
  840. .close = uninit,
  841. .decode = decode,
  842. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
  843. .flush = flush,
  844. .long_name = NULL_IF_CONFIG_SMALL("Windows Media Video 9 (CrystalHD acceleration)"),
  845. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
  846. };
  847. #endif