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.

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