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.

1039 lines
37KB

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