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.

1112 lines
38KB

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