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.

1146 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. format.startCodeSz = (avctx->extradata[4] & 0x03) + 1;
  349. priv->bsfc = av_bitstream_filter_init("h264_mp4toannexb");
  350. if (!priv->bsfc) {
  351. av_log(avctx, AV_LOG_ERROR,
  352. "Cannot open the h264_mp4toannexb BSF!\n");
  353. return AVERROR_BSF_NOT_FOUND;
  354. }
  355. av_bitstream_filter_filter(priv->bsfc, avctx, NULL, &dummy_p,
  356. &dummy_int, NULL, 0, 0);
  357. format.pMetaData = avctx->extradata;
  358. format.metaDataSz = avctx->extradata_size;
  359. }
  360. break;
  361. case BC_MSUBTYPE_H264:
  362. format.startCodeSz = 4;
  363. // Fall-through
  364. case BC_MSUBTYPE_VC1:
  365. case BC_MSUBTYPE_WVC1:
  366. case BC_MSUBTYPE_WMV3:
  367. case BC_MSUBTYPE_WMVA:
  368. case BC_MSUBTYPE_MPEG2VIDEO:
  369. case BC_MSUBTYPE_DIVX:
  370. case BC_MSUBTYPE_DIVX311:
  371. format.pMetaData = avctx->extradata;
  372. format.metaDataSz = avctx->extradata_size;
  373. break;
  374. default:
  375. av_log(avctx, AV_LOG_ERROR, "CrystalHD: Unknown codec name\n");
  376. return AVERROR(EINVAL);
  377. }
  378. format.mSubtype = subtype;
  379. if (priv->sWidth) {
  380. format.bEnableScaling = 1;
  381. format.ScalingParams.sWidth = priv->sWidth;
  382. }
  383. /* Get a decoder instance */
  384. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: starting up\n");
  385. // Initialize the Link and Decoder devices
  386. ret = DtsDeviceOpen(&priv->dev, mode);
  387. if (ret != BC_STS_SUCCESS) {
  388. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: DtsDeviceOpen failed\n");
  389. goto fail;
  390. }
  391. ret = DtsCrystalHDVersion(priv->dev, &version);
  392. if (ret != BC_STS_SUCCESS) {
  393. av_log(avctx, AV_LOG_VERBOSE,
  394. "CrystalHD: DtsCrystalHDVersion failed\n");
  395. goto fail;
  396. }
  397. priv->is_70012 = version.device == 0;
  398. if (priv->is_70012 &&
  399. (subtype == BC_MSUBTYPE_DIVX || subtype == BC_MSUBTYPE_DIVX311)) {
  400. av_log(avctx, AV_LOG_VERBOSE,
  401. "CrystalHD: BCM70012 doesn't support MPEG4-ASP/DivX/Xvid\n");
  402. goto fail;
  403. }
  404. ret = DtsSetInputFormat(priv->dev, &format);
  405. if (ret != BC_STS_SUCCESS) {
  406. av_log(avctx, AV_LOG_ERROR, "CrystalHD: SetInputFormat failed\n");
  407. goto fail;
  408. }
  409. ret = DtsOpenDecoder(priv->dev, BC_STREAM_TYPE_ES);
  410. if (ret != BC_STS_SUCCESS) {
  411. av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsOpenDecoder failed\n");
  412. goto fail;
  413. }
  414. ret = DtsSetColorSpace(priv->dev, OUTPUT_MODE422_YUY2);
  415. if (ret != BC_STS_SUCCESS) {
  416. av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsSetColorSpace failed\n");
  417. goto fail;
  418. }
  419. ret = DtsStartDecoder(priv->dev);
  420. if (ret != BC_STS_SUCCESS) {
  421. av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartDecoder failed\n");
  422. goto fail;
  423. }
  424. ret = DtsStartCapture(priv->dev);
  425. if (ret != BC_STS_SUCCESS) {
  426. av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartCapture failed\n");
  427. goto fail;
  428. }
  429. if (avctx->codec->id == CODEC_ID_H264) {
  430. priv->parser = av_parser_init(avctx->codec->id);
  431. if (!priv->parser)
  432. av_log(avctx, AV_LOG_WARNING,
  433. "Cannot open the h.264 parser! Interlaced h.264 content "
  434. "will not be detected reliably.\n");
  435. priv->parser->flags = PARSER_FLAG_COMPLETE_FRAMES;
  436. }
  437. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Init complete.\n");
  438. return 0;
  439. fail:
  440. uninit(avctx);
  441. return -1;
  442. }
  443. static inline CopyRet copy_frame(AVCodecContext *avctx,
  444. BC_DTS_PROC_OUT *output,
  445. void *data, int *data_size)
  446. {
  447. BC_STATUS ret;
  448. BC_DTS_STATUS decoder_status;
  449. uint8_t trust_interlaced;
  450. uint8_t interlaced;
  451. CHDContext *priv = avctx->priv_data;
  452. int64_t pkt_pts = AV_NOPTS_VALUE;
  453. uint8_t pic_type = 0;
  454. uint8_t bottom_field = (output->PicInfo.flags & VDEC_FLAG_BOTTOMFIELD) ==
  455. VDEC_FLAG_BOTTOMFIELD;
  456. uint8_t bottom_first = !!(output->PicInfo.flags & VDEC_FLAG_BOTTOM_FIRST);
  457. int width = output->PicInfo.width;
  458. int height = output->PicInfo.height;
  459. int bwidth;
  460. uint8_t *src = output->Ybuff;
  461. int sStride;
  462. uint8_t *dst;
  463. int dStride;
  464. if (output->PicInfo.timeStamp != 0) {
  465. OpaqueList *node = opaque_list_pop(priv, output->PicInfo.timeStamp);
  466. if (node) {
  467. pkt_pts = node->reordered_opaque;
  468. pic_type = node->pic_type;
  469. av_free(node);
  470. } else {
  471. /*
  472. * We will encounter a situation where a timestamp cannot be
  473. * popped if a second field is being returned. In this case,
  474. * each field has the same timestamp and the first one will
  475. * cause it to be popped. To keep subsequent calculations
  476. * simple, pic_type should be set a FIELD value - doesn't
  477. * matter which, but I chose BOTTOM.
  478. */
  479. pic_type = PICT_BOTTOM_FIELD;
  480. }
  481. av_log(avctx, AV_LOG_VERBOSE, "output \"pts\": %"PRIu64"\n",
  482. output->PicInfo.timeStamp);
  483. av_log(avctx, AV_LOG_VERBOSE, "output picture type %d\n",
  484. pic_type);
  485. }
  486. ret = DtsGetDriverStatus(priv->dev, &decoder_status);
  487. if (ret != BC_STS_SUCCESS) {
  488. av_log(avctx, AV_LOG_ERROR,
  489. "CrystalHD: GetDriverStatus failed: %u\n", ret);
  490. return RET_ERROR;
  491. }
  492. /*
  493. * For most content, we can trust the interlaced flag returned
  494. * by the hardware, but sometimes we can't. These are the
  495. * conditions under which we can trust the flag:
  496. *
  497. * 1) It's not h.264 content
  498. * 2) The UNKNOWN_SRC flag is not set
  499. * 3) We know we're expecting a second field
  500. * 4) The hardware reports this picture and the next picture
  501. * have the same picture number.
  502. *
  503. * Note that there can still be interlaced content that will
  504. * fail this check, if the hardware hasn't decoded the next
  505. * picture or if there is a corruption in the stream. (In either
  506. * case a 0 will be returned for the next picture number)
  507. */
  508. trust_interlaced = avctx->codec->id != CODEC_ID_H264 ||
  509. !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ||
  510. priv->need_second_field ||
  511. (decoder_status.picNumFlags & ~0x40000000) ==
  512. output->PicInfo.picture_number;
  513. /*
  514. * If we got a false negative for trust_interlaced on the first field,
  515. * we will realise our mistake here when we see that the picture number is that
  516. * of the previous picture. We cannot recover the frame and should discard the
  517. * second field to keep the correct number of output frames.
  518. */
  519. if (output->PicInfo.picture_number == priv->last_picture && !priv->need_second_field) {
  520. av_log(avctx, AV_LOG_WARNING,
  521. "Incorrectly guessed progressive frame. Discarding second field\n");
  522. /* Returning without providing a picture. */
  523. return RET_OK;
  524. }
  525. interlaced = (output->PicInfo.flags & VDEC_FLAG_INTERLACED_SRC) &&
  526. trust_interlaced;
  527. if (!trust_interlaced && (decoder_status.picNumFlags & ~0x40000000) == 0) {
  528. av_log(avctx, AV_LOG_VERBOSE,
  529. "Next picture number unknown. Assuming progressive frame.\n");
  530. }
  531. av_log(avctx, AV_LOG_VERBOSE, "Interlaced state: %d | trust_interlaced %d\n",
  532. interlaced, trust_interlaced);
  533. if (priv->pic.data[0] && !priv->need_second_field)
  534. avctx->release_buffer(avctx, &priv->pic);
  535. priv->need_second_field = interlaced && !priv->need_second_field;
  536. priv->pic.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE |
  537. FF_BUFFER_HINTS_REUSABLE;
  538. if (!priv->pic.data[0]) {
  539. if (avctx->get_buffer(avctx, &priv->pic) < 0) {
  540. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  541. return RET_ERROR;
  542. }
  543. }
  544. bwidth = av_image_get_linesize(avctx->pix_fmt, width, 0);
  545. if (priv->is_70012) {
  546. int pStride;
  547. if (width <= 720)
  548. pStride = 720;
  549. else if (width <= 1280)
  550. pStride = 1280;
  551. else if (width <= 1080)
  552. pStride = 1080;
  553. sStride = av_image_get_linesize(avctx->pix_fmt, pStride, 0);
  554. } else {
  555. sStride = bwidth;
  556. }
  557. dStride = priv->pic.linesize[0];
  558. dst = priv->pic.data[0];
  559. av_log(priv->avctx, AV_LOG_VERBOSE, "CrystalHD: Copying out frame\n");
  560. if (interlaced) {
  561. int dY = 0;
  562. int sY = 0;
  563. height /= 2;
  564. if (bottom_field) {
  565. av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: bottom field\n");
  566. dY = 1;
  567. } else {
  568. av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: top field\n");
  569. dY = 0;
  570. }
  571. for (sY = 0; sY < height; dY++, sY++) {
  572. memcpy(&(dst[dY * dStride]), &(src[sY * sStride]), bwidth);
  573. dY++;
  574. }
  575. } else {
  576. av_image_copy_plane(dst, dStride, src, sStride, bwidth, height);
  577. }
  578. priv->pic.interlaced_frame = interlaced;
  579. if (interlaced)
  580. priv->pic.top_field_first = !bottom_first;
  581. priv->pic.pkt_pts = pkt_pts;
  582. if (!priv->need_second_field) {
  583. *data_size = sizeof(AVFrame);
  584. *(AVFrame *)data = priv->pic;
  585. }
  586. /*
  587. * Two types of PAFF content have been observed. One form causes the
  588. * hardware to return a field pair and the other individual fields,
  589. * even though the input is always individual fields. We must skip
  590. * copying on the next decode() call to maintain pipeline length in
  591. * the first case.
  592. */
  593. if (!interlaced && (output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) &&
  594. (pic_type == PICT_TOP_FIELD || pic_type == PICT_BOTTOM_FIELD)) {
  595. av_log(priv->avctx, AV_LOG_VERBOSE, "Fieldpair from two packets.\n");
  596. return RET_SKIP_NEXT_COPY;
  597. }
  598. /*
  599. * Testing has shown that in all cases where we don't want to return the
  600. * full frame immediately, VDEC_FLAG_UNKNOWN_SRC is set.
  601. */
  602. return priv->need_second_field &&
  603. !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ?
  604. RET_COPY_NEXT_FIELD : RET_OK;
  605. }
  606. static inline CopyRet receive_frame(AVCodecContext *avctx,
  607. void *data, int *data_size)
  608. {
  609. BC_STATUS ret;
  610. BC_DTS_PROC_OUT output = {
  611. .PicInfo.width = avctx->width,
  612. .PicInfo.height = avctx->height,
  613. };
  614. CHDContext *priv = avctx->priv_data;
  615. HANDLE dev = priv->dev;
  616. *data_size = 0;
  617. // Request decoded data from the driver
  618. ret = DtsProcOutputNoCopy(dev, OUTPUT_PROC_TIMEOUT, &output);
  619. if (ret == BC_STS_FMT_CHANGE) {
  620. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Initial format change\n");
  621. avctx->width = output.PicInfo.width;
  622. avctx->height = output.PicInfo.height;
  623. return RET_COPY_AGAIN;
  624. } else if (ret == BC_STS_SUCCESS) {
  625. int copy_ret = -1;
  626. if (output.PoutFlags & BC_POUT_FLAGS_PIB_VALID) {
  627. if (priv->last_picture == -1) {
  628. /*
  629. * Init to one less, so that the incrementing code doesn't
  630. * need to be special-cased.
  631. */
  632. priv->last_picture = output.PicInfo.picture_number - 1;
  633. }
  634. if (avctx->codec->id == CODEC_ID_MPEG4 &&
  635. output.PicInfo.timeStamp == 0 && priv->bframe_bug) {
  636. av_log(avctx, AV_LOG_VERBOSE,
  637. "CrystalHD: Not returning packed frame twice.\n");
  638. priv->last_picture++;
  639. DtsReleaseOutputBuffs(dev, NULL, FALSE);
  640. return RET_COPY_AGAIN;
  641. }
  642. print_frame_info(priv, &output);
  643. if (priv->last_picture + 1 < output.PicInfo.picture_number) {
  644. av_log(avctx, AV_LOG_WARNING,
  645. "CrystalHD: Picture Number discontinuity\n");
  646. /*
  647. * Have we lost frames? If so, we need to shrink the
  648. * pipeline length appropriately.
  649. *
  650. * XXX: I have no idea what the semantics of this situation
  651. * are so I don't even know if we've lost frames or which
  652. * ones.
  653. *
  654. * In any case, only warn the first time.
  655. */
  656. priv->last_picture = output.PicInfo.picture_number - 1;
  657. }
  658. copy_ret = copy_frame(avctx, &output, data, data_size);
  659. if (*data_size > 0) {
  660. avctx->has_b_frames--;
  661. priv->last_picture++;
  662. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Pipeline length: %u\n",
  663. avctx->has_b_frames);
  664. }
  665. } else {
  666. /*
  667. * An invalid frame has been consumed.
  668. */
  669. av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput succeeded with "
  670. "invalid PIB\n");
  671. avctx->has_b_frames--;
  672. copy_ret = RET_OK;
  673. }
  674. DtsReleaseOutputBuffs(dev, NULL, FALSE);
  675. return copy_ret;
  676. } else if (ret == BC_STS_BUSY) {
  677. return RET_COPY_AGAIN;
  678. } else {
  679. av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput failed %d\n", ret);
  680. return RET_ERROR;
  681. }
  682. }
  683. static int decode(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
  684. {
  685. BC_STATUS ret;
  686. BC_DTS_STATUS decoder_status;
  687. CopyRet rec_ret;
  688. CHDContext *priv = avctx->priv_data;
  689. HANDLE dev = priv->dev;
  690. uint8_t *in_data = avpkt->data;
  691. int len = avpkt->size;
  692. int free_data = 0;
  693. uint8_t pic_type = 0;
  694. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: decode_frame\n");
  695. if (avpkt->size == 7 && !priv->bframe_bug) {
  696. /*
  697. * The use of a drop frame triggers the bug
  698. */
  699. av_log(avctx, AV_LOG_INFO,
  700. "CrystalHD: Enabling work-around for packed b-frame bug\n");
  701. priv->bframe_bug = 1;
  702. } else if (avpkt->size == 8 && priv->bframe_bug) {
  703. /*
  704. * Delay frames don't trigger the bug
  705. */
  706. av_log(avctx, AV_LOG_INFO,
  707. "CrystalHD: Disabling work-around for packed b-frame bug\n");
  708. priv->bframe_bug = 0;
  709. }
  710. if (len) {
  711. int32_t tx_free = (int32_t)DtsTxFreeSize(dev);
  712. if (priv->parser) {
  713. int ret = 0;
  714. if (priv->bsfc) {
  715. ret = av_bitstream_filter_filter(priv->bsfc, avctx, NULL,
  716. &in_data, &len,
  717. avpkt->data, len, 0);
  718. }
  719. free_data = ret > 0;
  720. if (ret >= 0) {
  721. uint8_t *pout;
  722. int psize;
  723. int index;
  724. H264Context *h = priv->parser->priv_data;
  725. index = av_parser_parse2(priv->parser, avctx, &pout, &psize,
  726. in_data, len, avctx->pkt->pts,
  727. avctx->pkt->dts, 0);
  728. if (index < 0) {
  729. av_log(avctx, AV_LOG_WARNING,
  730. "CrystalHD: Failed to parse h.264 packet to "
  731. "detect interlacing.\n");
  732. } else if (index != len) {
  733. av_log(avctx, AV_LOG_WARNING,
  734. "CrystalHD: Failed to parse h.264 packet "
  735. "completely. Interlaced frames may be "
  736. "incorrectly detected\n.");
  737. } else {
  738. av_log(avctx, AV_LOG_VERBOSE,
  739. "CrystalHD: parser picture type %d\n",
  740. h->s.picture_structure);
  741. pic_type = h->s.picture_structure;
  742. }
  743. } else {
  744. av_log(avctx, AV_LOG_WARNING,
  745. "CrystalHD: mp4toannexb filter failed to filter "
  746. "packet. Interlaced frames may be incorrectly "
  747. "detected.\n");
  748. }
  749. }
  750. if (len < tx_free - 1024) {
  751. /*
  752. * Despite being notionally opaque, either libcrystalhd or
  753. * the hardware itself will mangle pts values that are too
  754. * small or too large. The docs claim it should be in units
  755. * of 100ns. Given that we're nominally dealing with a black
  756. * box on both sides, any transform we do has no guarantee of
  757. * avoiding mangling so we need to build a mapping to values
  758. * we know will not be mangled.
  759. */
  760. uint64_t pts = opaque_list_push(priv, avctx->pkt->pts, pic_type);
  761. if (!pts) {
  762. if (free_data) {
  763. av_freep(&in_data);
  764. }
  765. return AVERROR(ENOMEM);
  766. }
  767. av_log(priv->avctx, AV_LOG_VERBOSE,
  768. "input \"pts\": %"PRIu64"\n", pts);
  769. ret = DtsProcInput(dev, in_data, len, pts, 0);
  770. if (free_data) {
  771. av_freep(&in_data);
  772. }
  773. if (ret == BC_STS_BUSY) {
  774. av_log(avctx, AV_LOG_WARNING,
  775. "CrystalHD: ProcInput returned busy\n");
  776. usleep(BASE_WAIT);
  777. return AVERROR(EBUSY);
  778. } else if (ret != BC_STS_SUCCESS) {
  779. av_log(avctx, AV_LOG_ERROR,
  780. "CrystalHD: ProcInput failed: %u\n", ret);
  781. return -1;
  782. }
  783. avctx->has_b_frames++;
  784. } else {
  785. av_log(avctx, AV_LOG_WARNING, "CrystalHD: Input buffer full\n");
  786. len = 0; // We didn't consume any bytes.
  787. }
  788. } else {
  789. av_log(avctx, AV_LOG_INFO, "CrystalHD: No more input data\n");
  790. }
  791. if (priv->skip_next_output) {
  792. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Skipping next output.\n");
  793. priv->skip_next_output = 0;
  794. avctx->has_b_frames--;
  795. return len;
  796. }
  797. ret = DtsGetDriverStatus(dev, &decoder_status);
  798. if (ret != BC_STS_SUCCESS) {
  799. av_log(avctx, AV_LOG_ERROR, "CrystalHD: GetDriverStatus failed\n");
  800. return -1;
  801. }
  802. /*
  803. * No frames ready. Don't try to extract.
  804. *
  805. * Empirical testing shows that ReadyListCount can be a damn lie,
  806. * and ProcOut still fails when count > 0. The same testing showed
  807. * that two more iterations were needed before ProcOutput would
  808. * succeed.
  809. */
  810. if (priv->output_ready < 2) {
  811. if (decoder_status.ReadyListCount != 0)
  812. priv->output_ready++;
  813. usleep(BASE_WAIT);
  814. av_log(avctx, AV_LOG_INFO, "CrystalHD: Filling pipeline.\n");
  815. return len;
  816. } else if (decoder_status.ReadyListCount == 0) {
  817. /*
  818. * After the pipeline is established, if we encounter a lack of frames
  819. * that probably means we're not giving the hardware enough time to
  820. * decode them, so start increasing the wait time at the end of a
  821. * decode call.
  822. */
  823. usleep(BASE_WAIT);
  824. priv->decode_wait += WAIT_UNIT;
  825. av_log(avctx, AV_LOG_INFO, "CrystalHD: No frames ready. Returning\n");
  826. return len;
  827. }
  828. do {
  829. rec_ret = receive_frame(avctx, data, data_size);
  830. if (rec_ret == RET_OK && *data_size == 0) {
  831. /*
  832. * This case is for when the encoded fields are stored
  833. * separately and we get a separate avpkt for each one. To keep
  834. * the pipeline stable, we should return nothing and wait for
  835. * the next time round to grab the second field.
  836. * H.264 PAFF is an example of this.
  837. */
  838. av_log(avctx, AV_LOG_VERBOSE, "Returning after first field.\n");
  839. avctx->has_b_frames--;
  840. } else if (rec_ret == RET_COPY_NEXT_FIELD) {
  841. /*
  842. * This case is for when the encoded fields are stored in a
  843. * single avpkt but the hardware returns then separately. Unless
  844. * we grab the second field before returning, we'll slip another
  845. * frame in the pipeline and if that happens a lot, we're sunk.
  846. * So we have to get that second field now.
  847. * Interlaced mpeg2 and vc1 are examples of this.
  848. */
  849. av_log(avctx, AV_LOG_VERBOSE, "Trying to get second field.\n");
  850. while (1) {
  851. usleep(priv->decode_wait);
  852. ret = DtsGetDriverStatus(dev, &decoder_status);
  853. if (ret == BC_STS_SUCCESS &&
  854. decoder_status.ReadyListCount > 0) {
  855. rec_ret = receive_frame(avctx, data, data_size);
  856. if ((rec_ret == RET_OK && *data_size > 0) ||
  857. rec_ret == RET_ERROR)
  858. break;
  859. }
  860. }
  861. av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Got second field.\n");
  862. } else if (rec_ret == RET_SKIP_NEXT_COPY) {
  863. /*
  864. * Two input packets got turned into a field pair. Gawd.
  865. */
  866. av_log(avctx, AV_LOG_VERBOSE,
  867. "Don't output on next decode call.\n");
  868. priv->skip_next_output = 1;
  869. }
  870. /*
  871. * If rec_ret == RET_COPY_AGAIN, that means that either we just handled
  872. * a FMT_CHANGE event and need to go around again for the actual frame,
  873. * we got a busy status and need to try again, or we're dealing with
  874. * packed b-frames, where the hardware strangely returns the packed
  875. * p-frame twice. We choose to keep the second copy as it carries the
  876. * valid pts.
  877. */
  878. } while (rec_ret == RET_COPY_AGAIN);
  879. usleep(priv->decode_wait);
  880. return len;
  881. }
  882. #if CONFIG_H264_CRYSTALHD_DECODER
  883. static AVClass h264_class = {
  884. "h264_crystalhd",
  885. av_default_item_name,
  886. options,
  887. LIBAVUTIL_VERSION_INT,
  888. };
  889. AVCodec ff_h264_crystalhd_decoder = {
  890. .name = "h264_crystalhd",
  891. .type = AVMEDIA_TYPE_VIDEO,
  892. .id = CODEC_ID_H264,
  893. .priv_data_size = sizeof(CHDContext),
  894. .init = init,
  895. .close = uninit,
  896. .decode = decode,
  897. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
  898. .flush = flush,
  899. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (CrystalHD acceleration)"),
  900. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
  901. .priv_class = &h264_class,
  902. };
  903. #endif
  904. #if CONFIG_MPEG2_CRYSTALHD_DECODER
  905. static AVClass mpeg2_class = {
  906. "mpeg2_crystalhd",
  907. av_default_item_name,
  908. options,
  909. LIBAVUTIL_VERSION_INT,
  910. };
  911. AVCodec ff_mpeg2_crystalhd_decoder = {
  912. .name = "mpeg2_crystalhd",
  913. .type = AVMEDIA_TYPE_VIDEO,
  914. .id = CODEC_ID_MPEG2VIDEO,
  915. .priv_data_size = sizeof(CHDContext),
  916. .init = init,
  917. .close = uninit,
  918. .decode = decode,
  919. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
  920. .flush = flush,
  921. .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 Video (CrystalHD acceleration)"),
  922. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
  923. .priv_class = &mpeg2_class,
  924. };
  925. #endif
  926. #if CONFIG_MPEG4_CRYSTALHD_DECODER
  927. static AVClass mpeg4_class = {
  928. "mpeg4_crystalhd",
  929. av_default_item_name,
  930. options,
  931. LIBAVUTIL_VERSION_INT,
  932. };
  933. AVCodec ff_mpeg4_crystalhd_decoder = {
  934. .name = "mpeg4_crystalhd",
  935. .type = AVMEDIA_TYPE_VIDEO,
  936. .id = CODEC_ID_MPEG4,
  937. .priv_data_size = sizeof(CHDContext),
  938. .init = init,
  939. .close = uninit,
  940. .decode = decode,
  941. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
  942. .flush = flush,
  943. .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 (CrystalHD acceleration)"),
  944. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
  945. .priv_class = &mpeg4_class,
  946. };
  947. #endif
  948. #if CONFIG_MSMPEG4_CRYSTALHD_DECODER
  949. static AVClass msmpeg4_class = {
  950. "msmpeg4_crystalhd",
  951. av_default_item_name,
  952. options,
  953. LIBAVUTIL_VERSION_INT,
  954. };
  955. AVCodec ff_msmpeg4_crystalhd_decoder = {
  956. .name = "msmpeg4_crystalhd",
  957. .type = AVMEDIA_TYPE_VIDEO,
  958. .id = CODEC_ID_MSMPEG4V3,
  959. .priv_data_size = sizeof(CHDContext),
  960. .init = init,
  961. .close = uninit,
  962. .decode = decode,
  963. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
  964. .flush = flush,
  965. .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 Microsoft variant version 3 (CrystalHD acceleration)"),
  966. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
  967. .priv_class = &msmpeg4_class,
  968. };
  969. #endif
  970. #if CONFIG_VC1_CRYSTALHD_DECODER
  971. static AVClass vc1_class = {
  972. "vc1_crystalhd",
  973. av_default_item_name,
  974. options,
  975. LIBAVUTIL_VERSION_INT,
  976. };
  977. AVCodec ff_vc1_crystalhd_decoder = {
  978. .name = "vc1_crystalhd",
  979. .type = AVMEDIA_TYPE_VIDEO,
  980. .id = CODEC_ID_VC1,
  981. .priv_data_size = sizeof(CHDContext),
  982. .init = init,
  983. .close = uninit,
  984. .decode = decode,
  985. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
  986. .flush = flush,
  987. .long_name = NULL_IF_CONFIG_SMALL("SMPTE VC-1 (CrystalHD acceleration)"),
  988. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
  989. .priv_class = &vc1_class,
  990. };
  991. #endif
  992. #if CONFIG_WMV3_CRYSTALHD_DECODER
  993. static AVClass wmv3_class = {
  994. "wmv3_crystalhd",
  995. av_default_item_name,
  996. options,
  997. LIBAVUTIL_VERSION_INT,
  998. };
  999. AVCodec ff_wmv3_crystalhd_decoder = {
  1000. .name = "wmv3_crystalhd",
  1001. .type = AVMEDIA_TYPE_VIDEO,
  1002. .id = CODEC_ID_WMV3,
  1003. .priv_data_size = sizeof(CHDContext),
  1004. .init = init,
  1005. .close = uninit,
  1006. .decode = decode,
  1007. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
  1008. .flush = flush,
  1009. .long_name = NULL_IF_CONFIG_SMALL("Windows Media Video 9 (CrystalHD acceleration)"),
  1010. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
  1011. .priv_class = &wmv3_class,
  1012. };
  1013. #endif