FFmpeg
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
crystalhd.c
Go to the documentation of this file.
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 /*
24  * - Principles of Operation -
25  *
26  * The CrystalHD decoder operates at the bitstream level - which is an even
27  * higher level than the decoding hardware you typically see in modern GPUs.
28  * This means it has a very simple interface, in principle. You feed demuxed
29  * packets in one end and get decoded picture (fields/frames) out the other.
30  *
31  * Of course, nothing is ever that simple. Due, at the very least, to b-frame
32  * dependencies in the supported formats, the hardware has a delay between
33  * when a packet goes in, and when a picture comes out. Furthermore, this delay
34  * is not just a function of time, but also one of the dependency on additional
35  * frames being fed into the decoder to satisfy the b-frame dependencies.
36  *
37  * As such, a pipeline will build up that is roughly equivalent to the required
38  * DPB for the file being played. If that was all it took, things would still
39  * be simple - so, of course, it isn't.
40  *
41  * The hardware has a way of indicating that a picture is ready to be copied out,
42  * but this is unreliable - and sometimes the attempt will still fail so, based
43  * on testing, the code will wait until 3 pictures are ready before starting
44  * to copy out - and this has the effect of extending the pipeline.
45  *
46  * Finally, while it is tempting to say that once the decoder starts outputting
47  * frames, the software should never fail to return a frame from a decode(),
48  * this is a hard assertion to make, because the stream may switch between
49  * differently encoded content (number of b-frames, interlacing, etc) which
50  * might require a longer pipeline than before. If that happened, you could
51  * deadlock trying to retrieve a frame that can't be decoded without feeding
52  * in additional packets.
53  *
54  * As such, the code will return in the event that a picture cannot be copied
55  * out, leading to an increase in the length of the pipeline. This in turn,
56  * means we have to be sensitive to the time it takes to decode a picture;
57  * We do not want to give up just because the hardware needed a little more
58  * time to prepare the picture! For this reason, there are delays included
59  * in the decode() path that ensure that, under normal conditions, the hardware
60  * will only fail to return a frame if it really needs additional packets to
61  * complete the decoding.
62  *
63  * Finally, to be explicit, we do not want the pipeline to grow without bound
64  * for two reasons: 1) The hardware can only buffer a finite number of packets,
65  * and 2) The client application may not be able to cope with arbitrarily long
66  * delays in the video path relative to the audio path. For example. MPlayer
67  * can only handle a 20 picture delay (although this is arbitrary, and needs
68  * to be extended to fully support the CrystalHD where the delay could be up
69  * to 32 pictures - consider PAFF H.264 content with 16 b-frames).
70  */
71 
72 /*****************************************************************************
73  * Includes
74  ****************************************************************************/
75 
76 #define _XOPEN_SOURCE 600
77 #include <inttypes.h>
78 #include <stdio.h>
79 #include <stdlib.h>
80 #include <unistd.h>
81 
82 #include <libcrystalhd/bc_dts_types.h>
83 #include <libcrystalhd/bc_dts_defs.h>
84 #include <libcrystalhd/libcrystalhd_if.h>
85 
86 #include "avcodec.h"
87 #include "h264.h"
88 #include "internal.h"
89 #include "libavutil/imgutils.h"
90 #include "libavutil/intreadwrite.h"
91 #include "libavutil/opt.h"
92 
93 /** Timeout parameter passed to DtsProcOutput() in us */
94 #define OUTPUT_PROC_TIMEOUT 50
95 /** Step between fake timestamps passed to hardware in units of 100ns */
96 #define TIMESTAMP_UNIT 100000
97 /** Initial value in us of the wait in decode() */
98 #define BASE_WAIT 10000
99 /** Increment in us to adjust wait in decode() */
100 #define WAIT_UNIT 1000
101 
102 
103 /*****************************************************************************
104  * Module private data
105  ****************************************************************************/
106 
107 typedef enum {
108  RET_ERROR = -1,
109  RET_OK = 0,
113 } CopyRet;
114 
115 typedef struct OpaqueList {
116  struct OpaqueList *next;
117  uint64_t fake_timestamp;
120 } OpaqueList;
121 
122 typedef struct {
126  HANDLE dev;
127 
130 
133 
136  uint32_t sps_pps_size;
141  uint64_t decode_wait;
142 
143  uint64_t last_picture;
144 
147 
148  /* Options */
149  uint32_t sWidth;
151 } CHDContext;
152 
153 static const AVOption options[] = {
154  { "crystalhd_downscale_width",
155  "Turn on downscaling to the specified width",
156  offsetof(CHDContext, sWidth),
157  AV_OPT_TYPE_INT, {.i64 = 0}, 0, UINT32_MAX,
159  { NULL, },
160 };
161 
162 
163 /*****************************************************************************
164  * Helper functions
165  ****************************************************************************/
166 
167 static inline BC_MEDIA_SUBTYPE id2subtype(CHDContext *priv, enum AVCodecID id)
168 {
169  switch (id) {
170  case AV_CODEC_ID_MPEG4:
171  return BC_MSUBTYPE_DIVX;
173  return BC_MSUBTYPE_DIVX311;
175  return BC_MSUBTYPE_MPEG2VIDEO;
176  case AV_CODEC_ID_VC1:
177  return BC_MSUBTYPE_VC1;
178  case AV_CODEC_ID_WMV3:
179  return BC_MSUBTYPE_WMV3;
180  case AV_CODEC_ID_H264:
181  return priv->is_nal ? BC_MSUBTYPE_AVC1 : BC_MSUBTYPE_H264;
182  default:
183  return BC_MSUBTYPE_INVALID;
184  }
185 }
186 
187 static inline void print_frame_info(CHDContext *priv, BC_DTS_PROC_OUT *output)
188 {
189  av_log(priv->avctx, AV_LOG_VERBOSE, "\tYBuffSz: %u\n", output->YbuffSz);
190  av_log(priv->avctx, AV_LOG_VERBOSE, "\tYBuffDoneSz: %u\n",
191  output->YBuffDoneSz);
192  av_log(priv->avctx, AV_LOG_VERBOSE, "\tUVBuffDoneSz: %u\n",
193  output->UVBuffDoneSz);
194  av_log(priv->avctx, AV_LOG_VERBOSE, "\tTimestamp: %"PRIu64"\n",
195  output->PicInfo.timeStamp);
196  av_log(priv->avctx, AV_LOG_VERBOSE, "\tPicture Number: %u\n",
197  output->PicInfo.picture_number);
198  av_log(priv->avctx, AV_LOG_VERBOSE, "\tWidth: %u\n",
199  output->PicInfo.width);
200  av_log(priv->avctx, AV_LOG_VERBOSE, "\tHeight: %u\n",
201  output->PicInfo.height);
202  av_log(priv->avctx, AV_LOG_VERBOSE, "\tChroma: 0x%03x\n",
203  output->PicInfo.chroma_format);
204  av_log(priv->avctx, AV_LOG_VERBOSE, "\tPulldown: %u\n",
205  output->PicInfo.pulldown);
206  av_log(priv->avctx, AV_LOG_VERBOSE, "\tFlags: 0x%08x\n",
207  output->PicInfo.flags);
208  av_log(priv->avctx, AV_LOG_VERBOSE, "\tFrame Rate/Res: %u\n",
209  output->PicInfo.frame_rate);
210  av_log(priv->avctx, AV_LOG_VERBOSE, "\tAspect Ratio: %u\n",
211  output->PicInfo.aspect_ratio);
212  av_log(priv->avctx, AV_LOG_VERBOSE, "\tColor Primaries: %u\n",
213  output->PicInfo.colour_primaries);
214  av_log(priv->avctx, AV_LOG_VERBOSE, "\tMetaData: %u\n",
215  output->PicInfo.picture_meta_payload);
216  av_log(priv->avctx, AV_LOG_VERBOSE, "\tSession Number: %u\n",
217  output->PicInfo.sess_num);
218  av_log(priv->avctx, AV_LOG_VERBOSE, "\tycom: %u\n",
219  output->PicInfo.ycom);
220  av_log(priv->avctx, AV_LOG_VERBOSE, "\tCustom Aspect: %u\n",
221  output->PicInfo.custom_aspect_ratio_width_height);
222  av_log(priv->avctx, AV_LOG_VERBOSE, "\tFrames to Drop: %u\n",
223  output->PicInfo.n_drop);
224  av_log(priv->avctx, AV_LOG_VERBOSE, "\tH264 Valid Fields: 0x%08x\n",
225  output->PicInfo.other.h264.valid);
226 }
227 
228 
229 /*****************************************************************************
230  * OpaqueList functions
231  ****************************************************************************/
232 
233 static uint64_t opaque_list_push(CHDContext *priv, uint64_t reordered_opaque,
234  uint8_t pic_type)
235 {
236  OpaqueList *newNode = av_mallocz(sizeof (OpaqueList));
237  if (!newNode) {
238  av_log(priv->avctx, AV_LOG_ERROR,
239  "Unable to allocate new node in OpaqueList.\n");
240  return 0;
241  }
242  if (!priv->head) {
243  newNode->fake_timestamp = TIMESTAMP_UNIT;
244  priv->head = newNode;
245  } else {
246  newNode->fake_timestamp = priv->tail->fake_timestamp + TIMESTAMP_UNIT;
247  priv->tail->next = newNode;
248  }
249  priv->tail = newNode;
250  newNode->reordered_opaque = reordered_opaque;
251  newNode->pic_type = pic_type;
252 
253  return newNode->fake_timestamp;
254 }
255 
256 /*
257  * The OpaqueList is built in decode order, while elements will be removed
258  * in presentation order. If frames are reordered, this means we must be
259  * able to remove elements that are not the first element.
260  *
261  * Returned node must be freed by caller.
262  */
263 static OpaqueList *opaque_list_pop(CHDContext *priv, uint64_t fake_timestamp)
264 {
265  OpaqueList *node = priv->head;
266 
267  if (!priv->head) {
268  av_log(priv->avctx, AV_LOG_ERROR,
269  "CrystalHD: Attempted to query non-existent timestamps.\n");
270  return NULL;
271  }
272 
273  /*
274  * The first element is special-cased because we have to manipulate
275  * the head pointer rather than the previous element in the list.
276  */
277  if (priv->head->fake_timestamp == fake_timestamp) {
278  priv->head = node->next;
279 
280  if (!priv->head->next)
281  priv->tail = priv->head;
282 
283  node->next = NULL;
284  return node;
285  }
286 
287  /*
288  * The list is processed at arm's length so that we have the
289  * previous element available to rewrite its next pointer.
290  */
291  while (node->next) {
292  OpaqueList *current = node->next;
293  if (current->fake_timestamp == fake_timestamp) {
294  node->next = current->next;
295 
296  if (!node->next)
297  priv->tail = node;
298 
299  current->next = NULL;
300  return current;
301  } else {
302  node = current;
303  }
304  }
305 
306  av_log(priv->avctx, AV_LOG_VERBOSE,
307  "CrystalHD: Couldn't match fake_timestamp.\n");
308  return NULL;
309 }
310 
311 
312 /*****************************************************************************
313  * Video decoder API function definitions
314  ****************************************************************************/
315 
316 static void flush(AVCodecContext *avctx)
317 {
318  CHDContext *priv = avctx->priv_data;
319 
320  avctx->has_b_frames = 0;
321  priv->last_picture = -1;
322  priv->output_ready = 0;
323  priv->need_second_field = 0;
324  priv->skip_next_output = 0;
325  priv->decode_wait = BASE_WAIT;
326 
327  if (priv->pic.data[0])
328  avctx->release_buffer(avctx, &priv->pic);
329 
330  /* Flush mode 4 flushes all software and hardware buffers. */
331  DtsFlushInput(priv->dev, 4);
332 }
333 
334 
335 static av_cold int uninit(AVCodecContext *avctx)
336 {
337  CHDContext *priv = avctx->priv_data;
338  HANDLE device;
339 
340  device = priv->dev;
341  DtsStopDecoder(device);
342  DtsCloseDecoder(device);
343  DtsDeviceClose(device);
344 
345  /*
346  * Restore original extradata, so that if the decoder is
347  * reinitialised, the bitstream detection and filtering
348  * will work as expected.
349  */
350  if (priv->orig_extradata) {
351  av_free(avctx->extradata);
352  avctx->extradata = priv->orig_extradata;
353  avctx->extradata_size = priv->orig_extradata_size;
354  priv->orig_extradata = NULL;
355  priv->orig_extradata_size = 0;
356  }
357 
358  av_parser_close(priv->parser);
359  if (priv->bsfc) {
361  }
362 
363  av_free(priv->sps_pps_buf);
364 
365  if (priv->pic.data[0])
366  avctx->release_buffer(avctx, &priv->pic);
367 
368  if (priv->head) {
369  OpaqueList *node = priv->head;
370  while (node) {
371  OpaqueList *next = node->next;
372  av_free(node);
373  node = next;
374  }
375  }
376 
377  return 0;
378 }
379 
380 
381 static av_cold int init(AVCodecContext *avctx)
382 {
383  CHDContext* priv;
384  BC_STATUS ret;
385  BC_INFO_CRYSTAL version;
386  BC_INPUT_FORMAT format = {
387  .FGTEnable = FALSE,
388  .Progressive = TRUE,
389  .OptFlags = 0x80000000 | vdecFrameRate59_94 | 0x40,
390  .width = avctx->width,
391  .height = avctx->height,
392  };
393 
394  BC_MEDIA_SUBTYPE subtype;
395 
396  uint32_t mode = DTS_PLAYBACK_MODE |
397  DTS_LOAD_FILE_PLAY_FW |
398  DTS_SKIP_TX_CHK_CPB |
399  DTS_PLAYBACK_DROP_RPT_MODE |
400  DTS_SINGLE_THREADED_MODE |
401  DTS_DFLT_RESOLUTION(vdecRESOLUTION_1080p23_976);
402 
403  av_log(avctx, AV_LOG_VERBOSE, "CrystalHD Init for %s\n",
404  avctx->codec->name);
405 
406  avctx->pix_fmt = AV_PIX_FMT_YUYV422;
407 
408  /* Initialize the library */
409  priv = avctx->priv_data;
410  priv->avctx = avctx;
411  priv->is_nal = avctx->extradata_size > 0 && *(avctx->extradata) == 1;
412  priv->last_picture = -1;
413  priv->decode_wait = BASE_WAIT;
414 
415  subtype = id2subtype(priv, avctx->codec->id);
416  switch (subtype) {
417  case BC_MSUBTYPE_AVC1:
418  {
419  uint8_t *dummy_p;
420  int dummy_int;
421 
422  /* Back up the extradata so it can be restored at close time. */
423  priv->orig_extradata = av_malloc(avctx->extradata_size);
424  if (!priv->orig_extradata) {
425  av_log(avctx, AV_LOG_ERROR,
426  "Failed to allocate copy of extradata\n");
427  return AVERROR(ENOMEM);
428  }
429  priv->orig_extradata_size = avctx->extradata_size;
430  memcpy(priv->orig_extradata, avctx->extradata, avctx->extradata_size);
431 
432  priv->bsfc = av_bitstream_filter_init("h264_mp4toannexb");
433  if (!priv->bsfc) {
434  av_log(avctx, AV_LOG_ERROR,
435  "Cannot open the h264_mp4toannexb BSF!\n");
436  return AVERROR_BSF_NOT_FOUND;
437  }
438  av_bitstream_filter_filter(priv->bsfc, avctx, NULL, &dummy_p,
439  &dummy_int, NULL, 0, 0);
440  }
441  subtype = BC_MSUBTYPE_H264;
442  // Fall-through
443  case BC_MSUBTYPE_H264:
444  format.startCodeSz = 4;
445  // Fall-through
446  case BC_MSUBTYPE_VC1:
447  case BC_MSUBTYPE_WVC1:
448  case BC_MSUBTYPE_WMV3:
449  case BC_MSUBTYPE_WMVA:
450  case BC_MSUBTYPE_MPEG2VIDEO:
451  case BC_MSUBTYPE_DIVX:
452  case BC_MSUBTYPE_DIVX311:
453  format.pMetaData = avctx->extradata;
454  format.metaDataSz = avctx->extradata_size;
455  break;
456  default:
457  av_log(avctx, AV_LOG_ERROR, "CrystalHD: Unknown codec name\n");
458  return AVERROR(EINVAL);
459  }
460  format.mSubtype = subtype;
461 
462  if (priv->sWidth) {
463  format.bEnableScaling = 1;
464  format.ScalingParams.sWidth = priv->sWidth;
465  }
466 
467  /* Get a decoder instance */
468  av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: starting up\n");
469  // Initialize the Link and Decoder devices
470  ret = DtsDeviceOpen(&priv->dev, mode);
471  if (ret != BC_STS_SUCCESS) {
472  av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: DtsDeviceOpen failed\n");
473  goto fail;
474  }
475 
476  ret = DtsCrystalHDVersion(priv->dev, &version);
477  if (ret != BC_STS_SUCCESS) {
478  av_log(avctx, AV_LOG_VERBOSE,
479  "CrystalHD: DtsCrystalHDVersion failed\n");
480  goto fail;
481  }
482  priv->is_70012 = version.device == 0;
483 
484  if (priv->is_70012 &&
485  (subtype == BC_MSUBTYPE_DIVX || subtype == BC_MSUBTYPE_DIVX311)) {
486  av_log(avctx, AV_LOG_VERBOSE,
487  "CrystalHD: BCM70012 doesn't support MPEG4-ASP/DivX/Xvid\n");
488  goto fail;
489  }
490 
491  ret = DtsSetInputFormat(priv->dev, &format);
492  if (ret != BC_STS_SUCCESS) {
493  av_log(avctx, AV_LOG_ERROR, "CrystalHD: SetInputFormat failed\n");
494  goto fail;
495  }
496 
497  ret = DtsOpenDecoder(priv->dev, BC_STREAM_TYPE_ES);
498  if (ret != BC_STS_SUCCESS) {
499  av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsOpenDecoder failed\n");
500  goto fail;
501  }
502 
503  ret = DtsSetColorSpace(priv->dev, OUTPUT_MODE422_YUY2);
504  if (ret != BC_STS_SUCCESS) {
505  av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsSetColorSpace failed\n");
506  goto fail;
507  }
508  ret = DtsStartDecoder(priv->dev);
509  if (ret != BC_STS_SUCCESS) {
510  av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartDecoder failed\n");
511  goto fail;
512  }
513  ret = DtsStartCapture(priv->dev);
514  if (ret != BC_STS_SUCCESS) {
515  av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartCapture failed\n");
516  goto fail;
517  }
518 
519  if (avctx->codec->id == AV_CODEC_ID_H264) {
520  priv->parser = av_parser_init(avctx->codec->id);
521  if (!priv->parser)
522  av_log(avctx, AV_LOG_WARNING,
523  "Cannot open the h.264 parser! Interlaced h.264 content "
524  "will not be detected reliably.\n");
526  }
527  av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Init complete.\n");
528 
529  return 0;
530 
531  fail:
532  uninit(avctx);
533  return -1;
534 }
535 
536 
537 static inline CopyRet copy_frame(AVCodecContext *avctx,
538  BC_DTS_PROC_OUT *output,
539  void *data, int *got_frame)
540 {
541  BC_STATUS ret;
542  BC_DTS_STATUS decoder_status = { 0, };
543  uint8_t trust_interlaced;
544  uint8_t interlaced;
545 
546  CHDContext *priv = avctx->priv_data;
547  int64_t pkt_pts = AV_NOPTS_VALUE;
548  uint8_t pic_type = 0;
549 
550  uint8_t bottom_field = (output->PicInfo.flags & VDEC_FLAG_BOTTOMFIELD) ==
551  VDEC_FLAG_BOTTOMFIELD;
552  uint8_t bottom_first = !!(output->PicInfo.flags & VDEC_FLAG_BOTTOM_FIRST);
553 
554  int width = output->PicInfo.width;
555  int height = output->PicInfo.height;
556  int bwidth;
557  uint8_t *src = output->Ybuff;
558  int sStride;
559  uint8_t *dst;
560  int dStride;
561 
562  if (output->PicInfo.timeStamp != 0) {
563  OpaqueList *node = opaque_list_pop(priv, output->PicInfo.timeStamp);
564  if (node) {
565  pkt_pts = node->reordered_opaque;
566  pic_type = node->pic_type;
567  av_free(node);
568  } else {
569  /*
570  * We will encounter a situation where a timestamp cannot be
571  * popped if a second field is being returned. In this case,
572  * each field has the same timestamp and the first one will
573  * cause it to be popped. To keep subsequent calculations
574  * simple, pic_type should be set a FIELD value - doesn't
575  * matter which, but I chose BOTTOM.
576  */
577  pic_type = PICT_BOTTOM_FIELD;
578  }
579  av_log(avctx, AV_LOG_VERBOSE, "output \"pts\": %"PRIu64"\n",
580  output->PicInfo.timeStamp);
581  av_log(avctx, AV_LOG_VERBOSE, "output picture type %d\n",
582  pic_type);
583  }
584 
585  ret = DtsGetDriverStatus(priv->dev, &decoder_status);
586  if (ret != BC_STS_SUCCESS) {
587  av_log(avctx, AV_LOG_ERROR,
588  "CrystalHD: GetDriverStatus failed: %u\n", ret);
589  return RET_ERROR;
590  }
591 
592  /*
593  * For most content, we can trust the interlaced flag returned
594  * by the hardware, but sometimes we can't. These are the
595  * conditions under which we can trust the flag:
596  *
597  * 1) It's not h.264 content
598  * 2) The UNKNOWN_SRC flag is not set
599  * 3) We know we're expecting a second field
600  * 4) The hardware reports this picture and the next picture
601  * have the same picture number.
602  *
603  * Note that there can still be interlaced content that will
604  * fail this check, if the hardware hasn't decoded the next
605  * picture or if there is a corruption in the stream. (In either
606  * case a 0 will be returned for the next picture number)
607  */
608  trust_interlaced = avctx->codec->id != AV_CODEC_ID_H264 ||
609  !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ||
610  priv->need_second_field ||
611  (decoder_status.picNumFlags & ~0x40000000) ==
612  output->PicInfo.picture_number;
613 
614  /*
615  * If we got a false negative for trust_interlaced on the first field,
616  * we will realise our mistake here when we see that the picture number is that
617  * of the previous picture. We cannot recover the frame and should discard the
618  * second field to keep the correct number of output frames.
619  */
620  if (output->PicInfo.picture_number == priv->last_picture && !priv->need_second_field) {
621  av_log(avctx, AV_LOG_WARNING,
622  "Incorrectly guessed progressive frame. Discarding second field\n");
623  /* Returning without providing a picture. */
624  return RET_OK;
625  }
626 
627  interlaced = (output->PicInfo.flags & VDEC_FLAG_INTERLACED_SRC) &&
628  trust_interlaced;
629 
630  if (!trust_interlaced && (decoder_status.picNumFlags & ~0x40000000) == 0) {
631  av_log(avctx, AV_LOG_VERBOSE,
632  "Next picture number unknown. Assuming progressive frame.\n");
633  }
634 
635  av_log(avctx, AV_LOG_VERBOSE, "Interlaced state: %d | trust_interlaced %d\n",
636  interlaced, trust_interlaced);
637 
638  if (priv->pic.data[0] && !priv->need_second_field)
639  avctx->release_buffer(avctx, &priv->pic);
640 
641  priv->need_second_field = interlaced && !priv->need_second_field;
642 
645  if (!priv->pic.data[0]) {
646  if (ff_get_buffer(avctx, &priv->pic) < 0) {
647  av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
648  return RET_ERROR;
649  }
650  }
651 
652  bwidth = av_image_get_linesize(avctx->pix_fmt, width, 0);
653  if (priv->is_70012) {
654  int pStride;
655 
656  if (width <= 720)
657  pStride = 720;
658  else if (width <= 1280)
659  pStride = 1280;
660  else pStride = 1920;
661  sStride = av_image_get_linesize(avctx->pix_fmt, pStride, 0);
662  } else {
663  sStride = bwidth;
664  }
665 
666  dStride = priv->pic.linesize[0];
667  dst = priv->pic.data[0];
668 
669  av_log(priv->avctx, AV_LOG_VERBOSE, "CrystalHD: Copying out frame\n");
670 
671  if (interlaced) {
672  int dY = 0;
673  int sY = 0;
674 
675  height /= 2;
676  if (bottom_field) {
677  av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: bottom field\n");
678  dY = 1;
679  } else {
680  av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: top field\n");
681  dY = 0;
682  }
683 
684  for (sY = 0; sY < height; dY++, sY++) {
685  memcpy(&(dst[dY * dStride]), &(src[sY * sStride]), bwidth);
686  dY++;
687  }
688  } else {
689  av_image_copy_plane(dst, dStride, src, sStride, bwidth, height);
690  }
691 
692  priv->pic.interlaced_frame = interlaced;
693  if (interlaced)
694  priv->pic.top_field_first = !bottom_first;
695 
696  priv->pic.pkt_pts = pkt_pts;
697 
698  if (!priv->need_second_field) {
699  *got_frame = 1;
700  *(AVFrame *)data = priv->pic;
701  }
702 
703  /*
704  * Two types of PAFF content have been observed. One form causes the
705  * hardware to return a field pair and the other individual fields,
706  * even though the input is always individual fields. We must skip
707  * copying on the next decode() call to maintain pipeline length in
708  * the first case.
709  */
710  if (!interlaced && (output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) &&
711  (pic_type == PICT_TOP_FIELD || pic_type == PICT_BOTTOM_FIELD)) {
712  av_log(priv->avctx, AV_LOG_VERBOSE, "Fieldpair from two packets.\n");
713  return RET_SKIP_NEXT_COPY;
714  }
715 
716  /*
717  * The logic here is purely based on empirical testing with samples.
718  * If we need a second field, it could come from a second input packet,
719  * or it could come from the same field-pair input packet at the current
720  * field. In the first case, we should return and wait for the next time
721  * round to get the second field, while in the second case, we should
722  * ask the decoder for it immediately.
723  *
724  * Testing has shown that we are dealing with the fieldpair -> two fields
725  * case if the VDEC_FLAG_UNKNOWN_SRC is not set or if the input picture
726  * type was PICT_FRAME (in this second case, the flag might still be set)
727  */
728  return priv->need_second_field &&
729  (!(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ||
730  pic_type == PICT_FRAME) ?
732 }
733 
734 
735 static inline CopyRet receive_frame(AVCodecContext *avctx,
736  void *data, int *got_frame)
737 {
738  BC_STATUS ret;
739  BC_DTS_PROC_OUT output = {
740  .PicInfo.width = avctx->width,
741  .PicInfo.height = avctx->height,
742  };
743  CHDContext *priv = avctx->priv_data;
744  HANDLE dev = priv->dev;
745 
746  *got_frame = 0;
747 
748  // Request decoded data from the driver
749  ret = DtsProcOutputNoCopy(dev, OUTPUT_PROC_TIMEOUT, &output);
750  if (ret == BC_STS_FMT_CHANGE) {
751  av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Initial format change\n");
752  avctx->width = output.PicInfo.width;
753  avctx->height = output.PicInfo.height;
754  switch ( output.PicInfo.aspect_ratio ) {
755  case vdecAspectRatioSquare:
756  avctx->sample_aspect_ratio = (AVRational) { 1, 1};
757  break;
758  case vdecAspectRatio12_11:
759  avctx->sample_aspect_ratio = (AVRational) { 12, 11};
760  break;
761  case vdecAspectRatio10_11:
762  avctx->sample_aspect_ratio = (AVRational) { 10, 11};
763  break;
764  case vdecAspectRatio16_11:
765  avctx->sample_aspect_ratio = (AVRational) { 16, 11};
766  break;
767  case vdecAspectRatio40_33:
768  avctx->sample_aspect_ratio = (AVRational) { 40, 33};
769  break;
770  case vdecAspectRatio24_11:
771  avctx->sample_aspect_ratio = (AVRational) { 24, 11};
772  break;
773  case vdecAspectRatio20_11:
774  avctx->sample_aspect_ratio = (AVRational) { 20, 11};
775  break;
776  case vdecAspectRatio32_11:
777  avctx->sample_aspect_ratio = (AVRational) { 32, 11};
778  break;
779  case vdecAspectRatio80_33:
780  avctx->sample_aspect_ratio = (AVRational) { 80, 33};
781  break;
782  case vdecAspectRatio18_11:
783  avctx->sample_aspect_ratio = (AVRational) { 18, 11};
784  break;
785  case vdecAspectRatio15_11:
786  avctx->sample_aspect_ratio = (AVRational) { 15, 11};
787  break;
788  case vdecAspectRatio64_33:
789  avctx->sample_aspect_ratio = (AVRational) { 64, 33};
790  break;
791  case vdecAspectRatio160_99:
792  avctx->sample_aspect_ratio = (AVRational) {160, 99};
793  break;
794  case vdecAspectRatio4_3:
795  avctx->sample_aspect_ratio = (AVRational) { 4, 3};
796  break;
797  case vdecAspectRatio16_9:
798  avctx->sample_aspect_ratio = (AVRational) { 16, 9};
799  break;
800  case vdecAspectRatio221_1:
801  avctx->sample_aspect_ratio = (AVRational) {221, 1};
802  break;
803  }
804  return RET_COPY_AGAIN;
805  } else if (ret == BC_STS_SUCCESS) {
806  int copy_ret = -1;
807  if (output.PoutFlags & BC_POUT_FLAGS_PIB_VALID) {
808  if (priv->last_picture == -1) {
809  /*
810  * Init to one less, so that the incrementing code doesn't
811  * need to be special-cased.
812  */
813  priv->last_picture = output.PicInfo.picture_number - 1;
814  }
815 
816  if (avctx->codec->id == AV_CODEC_ID_MPEG4 &&
817  output.PicInfo.timeStamp == 0 && priv->bframe_bug) {
818  av_log(avctx, AV_LOG_VERBOSE,
819  "CrystalHD: Not returning packed frame twice.\n");
820  priv->last_picture++;
821  DtsReleaseOutputBuffs(dev, NULL, FALSE);
822  return RET_COPY_AGAIN;
823  }
824 
825  print_frame_info(priv, &output);
826 
827  if (priv->last_picture + 1 < output.PicInfo.picture_number) {
828  av_log(avctx, AV_LOG_WARNING,
829  "CrystalHD: Picture Number discontinuity\n");
830  /*
831  * Have we lost frames? If so, we need to shrink the
832  * pipeline length appropriately.
833  *
834  * XXX: I have no idea what the semantics of this situation
835  * are so I don't even know if we've lost frames or which
836  * ones.
837  *
838  * In any case, only warn the first time.
839  */
840  priv->last_picture = output.PicInfo.picture_number - 1;
841  }
842 
843  copy_ret = copy_frame(avctx, &output, data, got_frame);
844  if (*got_frame > 0) {
845  avctx->has_b_frames--;
846  priv->last_picture++;
847  av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Pipeline length: %u\n",
848  avctx->has_b_frames);
849  }
850  } else {
851  /*
852  * An invalid frame has been consumed.
853  */
854  av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput succeeded with "
855  "invalid PIB\n");
856  avctx->has_b_frames--;
857  copy_ret = RET_OK;
858  }
859  DtsReleaseOutputBuffs(dev, NULL, FALSE);
860 
861  return copy_ret;
862  } else if (ret == BC_STS_BUSY) {
863  return RET_COPY_AGAIN;
864  } else {
865  av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput failed %d\n", ret);
866  return RET_ERROR;
867  }
868 }
869 
870 
871 static int decode(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt)
872 {
873  BC_STATUS ret;
874  BC_DTS_STATUS decoder_status = { 0, };
875  CopyRet rec_ret;
876  CHDContext *priv = avctx->priv_data;
877  HANDLE dev = priv->dev;
878  uint8_t *in_data = avpkt->data;
879  int len = avpkt->size;
880  int free_data = 0;
881  uint8_t pic_type = 0;
882 
883  av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: decode_frame\n");
884 
885  if (avpkt->size == 7 && !priv->bframe_bug) {
886  /*
887  * The use of a drop frame triggers the bug
888  */
889  av_log(avctx, AV_LOG_INFO,
890  "CrystalHD: Enabling work-around for packed b-frame bug\n");
891  priv->bframe_bug = 1;
892  } else if (avpkt->size == 8 && priv->bframe_bug) {
893  /*
894  * Delay frames don't trigger the bug
895  */
896  av_log(avctx, AV_LOG_INFO,
897  "CrystalHD: Disabling work-around for packed b-frame bug\n");
898  priv->bframe_bug = 0;
899  }
900 
901  if (len) {
902  int32_t tx_free = (int32_t)DtsTxFreeSize(dev);
903 
904  if (priv->parser) {
905  int ret = 0;
906 
907  if (priv->bsfc) {
908  ret = av_bitstream_filter_filter(priv->bsfc, avctx, NULL,
909  &in_data, &len,
910  avpkt->data, len, 0);
911  }
912  free_data = ret > 0;
913 
914  if (ret >= 0) {
915  uint8_t *pout;
916  int psize;
917  int index;
918  H264Context *h = priv->parser->priv_data;
919 
920  index = av_parser_parse2(priv->parser, avctx, &pout, &psize,
921  in_data, len, avctx->pkt->pts,
922  avctx->pkt->dts, 0);
923  if (index < 0) {
924  av_log(avctx, AV_LOG_WARNING,
925  "CrystalHD: Failed to parse h.264 packet to "
926  "detect interlacing.\n");
927  } else if (index != len) {
928  av_log(avctx, AV_LOG_WARNING,
929  "CrystalHD: Failed to parse h.264 packet "
930  "completely. Interlaced frames may be "
931  "incorrectly detected.\n");
932  } else {
933  av_log(avctx, AV_LOG_VERBOSE,
934  "CrystalHD: parser picture type %d\n",
935  h->picture_structure);
936  pic_type = h->picture_structure;
937  }
938  } else {
939  av_log(avctx, AV_LOG_WARNING,
940  "CrystalHD: mp4toannexb filter failed to filter "
941  "packet. Interlaced frames may be incorrectly "
942  "detected.\n");
943  }
944  }
945 
946  if (len < tx_free - 1024) {
947  /*
948  * Despite being notionally opaque, either libcrystalhd or
949  * the hardware itself will mangle pts values that are too
950  * small or too large. The docs claim it should be in units
951  * of 100ns. Given that we're nominally dealing with a black
952  * box on both sides, any transform we do has no guarantee of
953  * avoiding mangling so we need to build a mapping to values
954  * we know will not be mangled.
955  */
956  uint64_t pts = opaque_list_push(priv, avctx->pkt->pts, pic_type);
957  if (!pts) {
958  if (free_data) {
959  av_freep(&in_data);
960  }
961  return AVERROR(ENOMEM);
962  }
963  av_log(priv->avctx, AV_LOG_VERBOSE,
964  "input \"pts\": %"PRIu64"\n", pts);
965  ret = DtsProcInput(dev, in_data, len, pts, 0);
966  if (free_data) {
967  av_freep(&in_data);
968  }
969  if (ret == BC_STS_BUSY) {
970  av_log(avctx, AV_LOG_WARNING,
971  "CrystalHD: ProcInput returned busy\n");
972  usleep(BASE_WAIT);
973  return AVERROR(EBUSY);
974  } else if (ret != BC_STS_SUCCESS) {
975  av_log(avctx, AV_LOG_ERROR,
976  "CrystalHD: ProcInput failed: %u\n", ret);
977  return -1;
978  }
979  avctx->has_b_frames++;
980  } else {
981  av_log(avctx, AV_LOG_WARNING, "CrystalHD: Input buffer full\n");
982  len = 0; // We didn't consume any bytes.
983  }
984  } else {
985  av_log(avctx, AV_LOG_INFO, "CrystalHD: No more input data\n");
986  }
987 
988  if (priv->skip_next_output) {
989  av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Skipping next output.\n");
990  priv->skip_next_output = 0;
991  avctx->has_b_frames--;
992  return len;
993  }
994 
995  ret = DtsGetDriverStatus(dev, &decoder_status);
996  if (ret != BC_STS_SUCCESS) {
997  av_log(avctx, AV_LOG_ERROR, "CrystalHD: GetDriverStatus failed\n");
998  return -1;
999  }
1000 
1001  /*
1002  * No frames ready. Don't try to extract.
1003  *
1004  * Empirical testing shows that ReadyListCount can be a damn lie,
1005  * and ProcOut still fails when count > 0. The same testing showed
1006  * that two more iterations were needed before ProcOutput would
1007  * succeed.
1008  */
1009  if (priv->output_ready < 2) {
1010  if (decoder_status.ReadyListCount != 0)
1011  priv->output_ready++;
1012  usleep(BASE_WAIT);
1013  av_log(avctx, AV_LOG_INFO, "CrystalHD: Filling pipeline.\n");
1014  return len;
1015  } else if (decoder_status.ReadyListCount == 0) {
1016  /*
1017  * After the pipeline is established, if we encounter a lack of frames
1018  * that probably means we're not giving the hardware enough time to
1019  * decode them, so start increasing the wait time at the end of a
1020  * decode call.
1021  */
1022  usleep(BASE_WAIT);
1023  priv->decode_wait += WAIT_UNIT;
1024  av_log(avctx, AV_LOG_INFO, "CrystalHD: No frames ready. Returning\n");
1025  return len;
1026  }
1027 
1028  do {
1029  rec_ret = receive_frame(avctx, data, got_frame);
1030  if (rec_ret == RET_OK && *got_frame == 0) {
1031  /*
1032  * This case is for when the encoded fields are stored
1033  * separately and we get a separate avpkt for each one. To keep
1034  * the pipeline stable, we should return nothing and wait for
1035  * the next time round to grab the second field.
1036  * H.264 PAFF is an example of this.
1037  */
1038  av_log(avctx, AV_LOG_VERBOSE, "Returning after first field.\n");
1039  avctx->has_b_frames--;
1040  } else if (rec_ret == RET_COPY_NEXT_FIELD) {
1041  /*
1042  * This case is for when the encoded fields are stored in a
1043  * single avpkt but the hardware returns then separately. Unless
1044  * we grab the second field before returning, we'll slip another
1045  * frame in the pipeline and if that happens a lot, we're sunk.
1046  * So we have to get that second field now.
1047  * Interlaced mpeg2 and vc1 are examples of this.
1048  */
1049  av_log(avctx, AV_LOG_VERBOSE, "Trying to get second field.\n");
1050  while (1) {
1051  usleep(priv->decode_wait);
1052  ret = DtsGetDriverStatus(dev, &decoder_status);
1053  if (ret == BC_STS_SUCCESS &&
1054  decoder_status.ReadyListCount > 0) {
1055  rec_ret = receive_frame(avctx, data, got_frame);
1056  if ((rec_ret == RET_OK && *got_frame > 0) ||
1057  rec_ret == RET_ERROR)
1058  break;
1059  }
1060  }
1061  av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Got second field.\n");
1062  } else if (rec_ret == RET_SKIP_NEXT_COPY) {
1063  /*
1064  * Two input packets got turned into a field pair. Gawd.
1065  */
1066  av_log(avctx, AV_LOG_VERBOSE,
1067  "Don't output on next decode call.\n");
1068  priv->skip_next_output = 1;
1069  }
1070  /*
1071  * If rec_ret == RET_COPY_AGAIN, that means that either we just handled
1072  * a FMT_CHANGE event and need to go around again for the actual frame,
1073  * we got a busy status and need to try again, or we're dealing with
1074  * packed b-frames, where the hardware strangely returns the packed
1075  * p-frame twice. We choose to keep the second copy as it carries the
1076  * valid pts.
1077  */
1078  } while (rec_ret == RET_COPY_AGAIN);
1079  usleep(priv->decode_wait);
1080  return len;
1081 }
1082 
1083 
1084 #if CONFIG_H264_CRYSTALHD_DECODER
1085 static AVClass h264_class = {
1086  "h264_crystalhd",
1088  options,
1090 };
1091 
1092 AVCodec ff_h264_crystalhd_decoder = {
1093  .name = "h264_crystalhd",
1094  .type = AVMEDIA_TYPE_VIDEO,
1095  .id = AV_CODEC_ID_H264,
1096  .priv_data_size = sizeof(CHDContext),
1097  .init = init,
1098  .close = uninit,
1099  .decode = decode,
1100  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
1101  .flush = flush,
1102  .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (CrystalHD acceleration)"),
1103  .pix_fmts = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
1104  .priv_class = &h264_class,
1105 };
1106 #endif
1107 
1108 #if CONFIG_MPEG2_CRYSTALHD_DECODER
1109 static AVClass mpeg2_class = {
1110  "mpeg2_crystalhd",
1112  options,
1114 };
1115 
1116 AVCodec ff_mpeg2_crystalhd_decoder = {
1117  .name = "mpeg2_crystalhd",
1118  .type = AVMEDIA_TYPE_VIDEO,
1119  .id = AV_CODEC_ID_MPEG2VIDEO,
1120  .priv_data_size = sizeof(CHDContext),
1121  .init = init,
1122  .close = uninit,
1123  .decode = decode,
1124  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
1125  .flush = flush,
1126  .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 Video (CrystalHD acceleration)"),
1127  .pix_fmts = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
1128  .priv_class = &mpeg2_class,
1129 };
1130 #endif
1131 
1132 #if CONFIG_MPEG4_CRYSTALHD_DECODER
1133 static AVClass mpeg4_class = {
1134  "mpeg4_crystalhd",
1136  options,
1138 };
1139 
1140 AVCodec ff_mpeg4_crystalhd_decoder = {
1141  .name = "mpeg4_crystalhd",
1142  .type = AVMEDIA_TYPE_VIDEO,
1143  .id = AV_CODEC_ID_MPEG4,
1144  .priv_data_size = sizeof(CHDContext),
1145  .init = init,
1146  .close = uninit,
1147  .decode = decode,
1148  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
1149  .flush = flush,
1150  .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 (CrystalHD acceleration)"),
1151  .pix_fmts = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
1152  .priv_class = &mpeg4_class,
1153 };
1154 #endif
1155 
1156 #if CONFIG_MSMPEG4_CRYSTALHD_DECODER
1157 static AVClass msmpeg4_class = {
1158  "msmpeg4_crystalhd",
1160  options,
1162 };
1163 
1164 AVCodec ff_msmpeg4_crystalhd_decoder = {
1165  .name = "msmpeg4_crystalhd",
1166  .type = AVMEDIA_TYPE_VIDEO,
1167  .id = AV_CODEC_ID_MSMPEG4V3,
1168  .priv_data_size = sizeof(CHDContext),
1169  .init = init,
1170  .close = uninit,
1171  .decode = decode,
1173  .flush = flush,
1174  .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 Microsoft variant version 3 (CrystalHD acceleration)"),
1175  .pix_fmts = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
1176  .priv_class = &msmpeg4_class,
1177 };
1178 #endif
1179 
1180 #if CONFIG_VC1_CRYSTALHD_DECODER
1181 static AVClass vc1_class = {
1182  "vc1_crystalhd",
1184  options,
1186 };
1187 
1188 AVCodec ff_vc1_crystalhd_decoder = {
1189  .name = "vc1_crystalhd",
1190  .type = AVMEDIA_TYPE_VIDEO,
1191  .id = AV_CODEC_ID_VC1,
1192  .priv_data_size = sizeof(CHDContext),
1193  .init = init,
1194  .close = uninit,
1195  .decode = decode,
1196  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
1197  .flush = flush,
1198  .long_name = NULL_IF_CONFIG_SMALL("SMPTE VC-1 (CrystalHD acceleration)"),
1199  .pix_fmts = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
1200  .priv_class = &vc1_class,
1201 };
1202 #endif
1203 
1204 #if CONFIG_WMV3_CRYSTALHD_DECODER
1205 static AVClass wmv3_class = {
1206  "wmv3_crystalhd",
1208  options,
1210 };
1211 
1212 AVCodec ff_wmv3_crystalhd_decoder = {
1213  .name = "wmv3_crystalhd",
1214  .type = AVMEDIA_TYPE_VIDEO,
1215  .id = AV_CODEC_ID_WMV3,
1216  .priv_data_size = sizeof(CHDContext),
1217  .init = init,
1218  .close = uninit,
1219  .decode = decode,
1220  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
1221  .flush = flush,
1222  .long_name = NULL_IF_CONFIG_SMALL("Windows Media Video 9 (CrystalHD acceleration)"),
1223  .pix_fmts = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
1224  .priv_class = &wmv3_class,
1225 };
1226 #endif