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.

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