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.

1129 lines
39KB

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