FFmpeg
 All Data Structures Namespaces 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 {
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  av_frame_unref (priv->pic);
328 
329  /* Flush mode 4 flushes all software and hardware buffers. */
330  DtsFlushInput(priv->dev, 4);
331 }
332 
333 
334 static av_cold int uninit(AVCodecContext *avctx)
335 {
336  CHDContext *priv = avctx->priv_data;
337  HANDLE device;
338 
339  device = priv->dev;
340  DtsStopDecoder(device);
341  DtsCloseDecoder(device);
342  DtsDeviceClose(device);
343 
344  /*
345  * Restore original extradata, so that if the decoder is
346  * reinitialised, the bitstream detection and filtering
347  * will work as expected.
348  */
349  if (priv->orig_extradata) {
350  av_free(avctx->extradata);
351  avctx->extradata = priv->orig_extradata;
352  avctx->extradata_size = priv->orig_extradata_size;
353  priv->orig_extradata = NULL;
354  priv->orig_extradata_size = 0;
355  }
356 
357  av_parser_close(priv->parser);
358  if (priv->bsfc) {
360  }
361 
362  av_free(priv->sps_pps_buf);
363 
364  av_frame_free (&priv->pic);
365 
366  if (priv->head) {
367  OpaqueList *node = priv->head;
368  while (node) {
369  OpaqueList *next = node->next;
370  av_free(node);
371  node = next;
372  }
373  }
374 
375  return 0;
376 }
377 
378 
379 static av_cold int init(AVCodecContext *avctx)
380 {
381  CHDContext* priv;
382  BC_STATUS ret;
383  BC_INFO_CRYSTAL version;
384  BC_INPUT_FORMAT format = {
385  .FGTEnable = FALSE,
386  .Progressive = TRUE,
387  .OptFlags = 0x80000000 | vdecFrameRate59_94 | 0x40,
388  .width = avctx->width,
389  .height = avctx->height,
390  };
391 
392  BC_MEDIA_SUBTYPE subtype;
393 
394  uint32_t mode = DTS_PLAYBACK_MODE |
395  DTS_LOAD_FILE_PLAY_FW |
396  DTS_SKIP_TX_CHK_CPB |
397  DTS_PLAYBACK_DROP_RPT_MODE |
398  DTS_SINGLE_THREADED_MODE |
399  DTS_DFLT_RESOLUTION(vdecRESOLUTION_1080p23_976);
400 
401  av_log(avctx, AV_LOG_VERBOSE, "CrystalHD Init for %s\n",
402  avctx->codec->name);
403 
404  avctx->pix_fmt = AV_PIX_FMT_YUYV422;
405 
406  /* Initialize the library */
407  priv = avctx->priv_data;
408  priv->avctx = avctx;
409  priv->is_nal = avctx->extradata_size > 0 && *(avctx->extradata) == 1;
410  priv->last_picture = -1;
411  priv->decode_wait = BASE_WAIT;
412  priv->pic = av_frame_alloc();
413 
414  subtype = id2subtype(priv, avctx->codec->id);
415  switch (subtype) {
416  case BC_MSUBTYPE_AVC1:
417  {
418  uint8_t *dummy_p;
419  int dummy_int;
420 
421  /* Back up the extradata so it can be restored at close time. */
422  priv->orig_extradata = av_malloc(avctx->extradata_size);
423  if (!priv->orig_extradata) {
424  av_log(avctx, AV_LOG_ERROR,
425  "Failed to allocate copy of extradata\n");
426  return AVERROR(ENOMEM);
427  }
428  priv->orig_extradata_size = avctx->extradata_size;
429  memcpy(priv->orig_extradata, avctx->extradata, avctx->extradata_size);
430 
431  priv->bsfc = av_bitstream_filter_init("h264_mp4toannexb");
432  if (!priv->bsfc) {
433  av_log(avctx, AV_LOG_ERROR,
434  "Cannot open the h264_mp4toannexb BSF!\n");
435  return AVERROR_BSF_NOT_FOUND;
436  }
437  av_bitstream_filter_filter(priv->bsfc, avctx, NULL, &dummy_p,
438  &dummy_int, NULL, 0, 0);
439  }
440  subtype = BC_MSUBTYPE_H264;
441  // Fall-through
442  case BC_MSUBTYPE_H264:
443  format.startCodeSz = 4;
444  // Fall-through
445  case BC_MSUBTYPE_VC1:
446  case BC_MSUBTYPE_WVC1:
447  case BC_MSUBTYPE_WMV3:
448  case BC_MSUBTYPE_WMVA:
449  case BC_MSUBTYPE_MPEG2VIDEO:
450  case BC_MSUBTYPE_DIVX:
451  case BC_MSUBTYPE_DIVX311:
452  format.pMetaData = avctx->extradata;
453  format.metaDataSz = avctx->extradata_size;
454  break;
455  default:
456  av_log(avctx, AV_LOG_ERROR, "CrystalHD: Unknown codec name\n");
457  return AVERROR(EINVAL);
458  }
459  format.mSubtype = subtype;
460 
461  if (priv->sWidth) {
462  format.bEnableScaling = 1;
463  format.ScalingParams.sWidth = priv->sWidth;
464  }
465 
466  /* Get a decoder instance */
467  av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: starting up\n");
468  // Initialize the Link and Decoder devices
469  ret = DtsDeviceOpen(&priv->dev, mode);
470  if (ret != BC_STS_SUCCESS) {
471  av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: DtsDeviceOpen failed\n");
472  goto fail;
473  }
474 
475  ret = DtsCrystalHDVersion(priv->dev, &version);
476  if (ret != BC_STS_SUCCESS) {
477  av_log(avctx, AV_LOG_VERBOSE,
478  "CrystalHD: DtsCrystalHDVersion failed\n");
479  goto fail;
480  }
481  priv->is_70012 = version.device == 0;
482 
483  if (priv->is_70012 &&
484  (subtype == BC_MSUBTYPE_DIVX || subtype == BC_MSUBTYPE_DIVX311)) {
485  av_log(avctx, AV_LOG_VERBOSE,
486  "CrystalHD: BCM70012 doesn't support MPEG4-ASP/DivX/Xvid\n");
487  goto fail;
488  }
489 
490  ret = DtsSetInputFormat(priv->dev, &format);
491  if (ret != BC_STS_SUCCESS) {
492  av_log(avctx, AV_LOG_ERROR, "CrystalHD: SetInputFormat failed\n");
493  goto fail;
494  }
495 
496  ret = DtsOpenDecoder(priv->dev, BC_STREAM_TYPE_ES);
497  if (ret != BC_STS_SUCCESS) {
498  av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsOpenDecoder failed\n");
499  goto fail;
500  }
501 
502  ret = DtsSetColorSpace(priv->dev, OUTPUT_MODE422_YUY2);
503  if (ret != BC_STS_SUCCESS) {
504  av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsSetColorSpace failed\n");
505  goto fail;
506  }
507  ret = DtsStartDecoder(priv->dev);
508  if (ret != BC_STS_SUCCESS) {
509  av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartDecoder failed\n");
510  goto fail;
511  }
512  ret = DtsStartCapture(priv->dev);
513  if (ret != BC_STS_SUCCESS) {
514  av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartCapture failed\n");
515  goto fail;
516  }
517 
518  if (avctx->codec->id == AV_CODEC_ID_H264) {
519  priv->parser = av_parser_init(avctx->codec->id);
520  if (!priv->parser)
521  av_log(avctx, AV_LOG_WARNING,
522  "Cannot open the h.264 parser! Interlaced h.264 content "
523  "will not be detected reliably.\n");
525  }
526  av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Init complete.\n");
527 
528  return 0;
529 
530  fail:
531  uninit(avctx);
532  return -1;
533 }
534 
535 
536 static inline CopyRet copy_frame(AVCodecContext *avctx,
537  BC_DTS_PROC_OUT *output,
538  void *data, int *got_frame)
539 {
540  BC_STATUS ret;
541  BC_DTS_STATUS decoder_status = { 0, };
542  uint8_t trust_interlaced;
543  uint8_t interlaced;
544 
545  CHDContext *priv = avctx->priv_data;
546  int64_t pkt_pts = AV_NOPTS_VALUE;
547  uint8_t pic_type = 0;
548 
549  uint8_t bottom_field = (output->PicInfo.flags & VDEC_FLAG_BOTTOMFIELD) ==
550  VDEC_FLAG_BOTTOMFIELD;
551  uint8_t bottom_first = !!(output->PicInfo.flags & VDEC_FLAG_BOTTOM_FIRST);
552 
553  int width = output->PicInfo.width;
554  int height = output->PicInfo.height;
555  int bwidth;
556  uint8_t *src = output->Ybuff;
557  int sStride;
558  uint8_t *dst;
559  int dStride;
560 
561  if (output->PicInfo.timeStamp != 0) {
562  OpaqueList *node = opaque_list_pop(priv, output->PicInfo.timeStamp);
563  if (node) {
564  pkt_pts = node->reordered_opaque;
565  pic_type = node->pic_type;
566  av_free(node);
567  } else {
568  /*
569  * We will encounter a situation where a timestamp cannot be
570  * popped if a second field is being returned. In this case,
571  * each field has the same timestamp and the first one will
572  * cause it to be popped. To keep subsequent calculations
573  * simple, pic_type should be set a FIELD value - doesn't
574  * matter which, but I chose BOTTOM.
575  */
576  pic_type = PICT_BOTTOM_FIELD;
577  }
578  av_log(avctx, AV_LOG_VERBOSE, "output \"pts\": %"PRIu64"\n",
579  output->PicInfo.timeStamp);
580  av_log(avctx, AV_LOG_VERBOSE, "output picture type %d\n",
581  pic_type);
582  }
583 
584  ret = DtsGetDriverStatus(priv->dev, &decoder_status);
585  if (ret != BC_STS_SUCCESS) {
586  av_log(avctx, AV_LOG_ERROR,
587  "CrystalHD: GetDriverStatus failed: %u\n", ret);
588  return RET_ERROR;
589  }
590 
591  /*
592  * For most content, we can trust the interlaced flag returned
593  * by the hardware, but sometimes we can't. These are the
594  * conditions under which we can trust the flag:
595  *
596  * 1) It's not h.264 content
597  * 2) The UNKNOWN_SRC flag is not set
598  * 3) We know we're expecting a second field
599  * 4) The hardware reports this picture and the next picture
600  * have the same picture number.
601  *
602  * Note that there can still be interlaced content that will
603  * fail this check, if the hardware hasn't decoded the next
604  * picture or if there is a corruption in the stream. (In either
605  * case a 0 will be returned for the next picture number)
606  */
607  trust_interlaced = avctx->codec->id != AV_CODEC_ID_H264 ||
608  !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ||
609  priv->need_second_field ||
610  (decoder_status.picNumFlags & ~0x40000000) ==
611  output->PicInfo.picture_number;
612 
613  /*
614  * If we got a false negative for trust_interlaced on the first field,
615  * we will realise our mistake here when we see that the picture number is that
616  * of the previous picture. We cannot recover the frame and should discard the
617  * second field to keep the correct number of output frames.
618  */
619  if (output->PicInfo.picture_number == priv->last_picture && !priv->need_second_field) {
620  av_log(avctx, AV_LOG_WARNING,
621  "Incorrectly guessed progressive frame. Discarding second field\n");
622  /* Returning without providing a picture. */
623  return RET_OK;
624  }
625 
626  interlaced = (output->PicInfo.flags & VDEC_FLAG_INTERLACED_SRC) &&
627  trust_interlaced;
628 
629  if (!trust_interlaced && (decoder_status.picNumFlags & ~0x40000000) == 0) {
630  av_log(avctx, AV_LOG_VERBOSE,
631  "Next picture number unknown. Assuming progressive frame.\n");
632  }
633 
634  av_log(avctx, AV_LOG_VERBOSE, "Interlaced state: %d | trust_interlaced %d\n",
635  interlaced, trust_interlaced);
636 
637  if (priv->pic->data[0] && !priv->need_second_field)
638  av_frame_unref(priv->pic);
639 
640  priv->need_second_field = interlaced && !priv->need_second_field;
641 
642  if (!priv->pic->data[0]) {
643  if (ff_get_buffer(avctx, priv->pic, AV_GET_BUFFER_FLAG_REF) < 0)
644  return RET_ERROR;
645  }
646 
647  bwidth = av_image_get_linesize(avctx->pix_fmt, width, 0);
648  if (priv->is_70012) {
649  int pStride;
650 
651  if (width <= 720)
652  pStride = 720;
653  else if (width <= 1280)
654  pStride = 1280;
655  else pStride = 1920;
656  sStride = av_image_get_linesize(avctx->pix_fmt, pStride, 0);
657  } else {
658  sStride = bwidth;
659  }
660 
661  dStride = priv->pic->linesize[0];
662  dst = priv->pic->data[0];
663 
664  av_log(priv->avctx, AV_LOG_VERBOSE, "CrystalHD: Copying out frame\n");
665 
666  if (interlaced) {
667  int dY = 0;
668  int sY = 0;
669 
670  height /= 2;
671  if (bottom_field) {
672  av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: bottom field\n");
673  dY = 1;
674  } else {
675  av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: top field\n");
676  dY = 0;
677  }
678 
679  for (sY = 0; sY < height; dY++, sY++) {
680  memcpy(&(dst[dY * dStride]), &(src[sY * sStride]), bwidth);
681  dY++;
682  }
683  } else {
684  av_image_copy_plane(dst, dStride, src, sStride, bwidth, height);
685  }
686 
687  priv->pic->interlaced_frame = interlaced;
688  if (interlaced)
689  priv->pic->top_field_first = !bottom_first;
690 
691  priv->pic->pkt_pts = pkt_pts;
692 
693  if (!priv->need_second_field) {
694  *got_frame = 1;
695  if ((ret = av_frame_ref(data, priv->pic)) < 0) {
696  return ret;
697  }
698  }
699 
700  /*
701  * Two types of PAFF content have been observed. One form causes the
702  * hardware to return a field pair and the other individual fields,
703  * even though the input is always individual fields. We must skip
704  * copying on the next decode() call to maintain pipeline length in
705  * the first case.
706  */
707  if (!interlaced && (output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) &&
708  (pic_type == PICT_TOP_FIELD || pic_type == PICT_BOTTOM_FIELD)) {
709  av_log(priv->avctx, AV_LOG_VERBOSE, "Fieldpair from two packets.\n");
710  return RET_SKIP_NEXT_COPY;
711  }
712 
713  /*
714  * The logic here is purely based on empirical testing with samples.
715  * If we need a second field, it could come from a second input packet,
716  * or it could come from the same field-pair input packet at the current
717  * field. In the first case, we should return and wait for the next time
718  * round to get the second field, while in the second case, we should
719  * ask the decoder for it immediately.
720  *
721  * Testing has shown that we are dealing with the fieldpair -> two fields
722  * case if the VDEC_FLAG_UNKNOWN_SRC is not set or if the input picture
723  * type was PICT_FRAME (in this second case, the flag might still be set)
724  */
725  return priv->need_second_field &&
726  (!(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ||
727  pic_type == PICT_FRAME) ?
729 }
730 
731 
732 static inline CopyRet receive_frame(AVCodecContext *avctx,
733  void *data, int *got_frame)
734 {
735  BC_STATUS ret;
736  BC_DTS_PROC_OUT output = {
737  .PicInfo.width = avctx->width,
738  .PicInfo.height = avctx->height,
739  };
740  CHDContext *priv = avctx->priv_data;
741  HANDLE dev = priv->dev;
742 
743  *got_frame = 0;
744 
745  // Request decoded data from the driver
746  ret = DtsProcOutputNoCopy(dev, OUTPUT_PROC_TIMEOUT, &output);
747  if (ret == BC_STS_FMT_CHANGE) {
748  av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Initial format change\n");
749  avctx->width = output.PicInfo.width;
750  avctx->height = output.PicInfo.height;
751  switch ( output.PicInfo.aspect_ratio ) {
752  case vdecAspectRatioSquare:
753  avctx->sample_aspect_ratio = (AVRational) { 1, 1};
754  break;
755  case vdecAspectRatio12_11:
756  avctx->sample_aspect_ratio = (AVRational) { 12, 11};
757  break;
758  case vdecAspectRatio10_11:
759  avctx->sample_aspect_ratio = (AVRational) { 10, 11};
760  break;
761  case vdecAspectRatio16_11:
762  avctx->sample_aspect_ratio = (AVRational) { 16, 11};
763  break;
764  case vdecAspectRatio40_33:
765  avctx->sample_aspect_ratio = (AVRational) { 40, 33};
766  break;
767  case vdecAspectRatio24_11:
768  avctx->sample_aspect_ratio = (AVRational) { 24, 11};
769  break;
770  case vdecAspectRatio20_11:
771  avctx->sample_aspect_ratio = (AVRational) { 20, 11};
772  break;
773  case vdecAspectRatio32_11:
774  avctx->sample_aspect_ratio = (AVRational) { 32, 11};
775  break;
776  case vdecAspectRatio80_33:
777  avctx->sample_aspect_ratio = (AVRational) { 80, 33};
778  break;
779  case vdecAspectRatio18_11:
780  avctx->sample_aspect_ratio = (AVRational) { 18, 11};
781  break;
782  case vdecAspectRatio15_11:
783  avctx->sample_aspect_ratio = (AVRational) { 15, 11};
784  break;
785  case vdecAspectRatio64_33:
786  avctx->sample_aspect_ratio = (AVRational) { 64, 33};
787  break;
788  case vdecAspectRatio160_99:
789  avctx->sample_aspect_ratio = (AVRational) {160, 99};
790  break;
791  case vdecAspectRatio4_3:
792  avctx->sample_aspect_ratio = (AVRational) { 4, 3};
793  break;
794  case vdecAspectRatio16_9:
795  avctx->sample_aspect_ratio = (AVRational) { 16, 9};
796  break;
797  case vdecAspectRatio221_1:
798  avctx->sample_aspect_ratio = (AVRational) {221, 1};
799  break;
800  }
801  return RET_COPY_AGAIN;
802  } else if (ret == BC_STS_SUCCESS) {
803  int copy_ret = -1;
804  if (output.PoutFlags & BC_POUT_FLAGS_PIB_VALID) {
805  if (priv->last_picture == -1) {
806  /*
807  * Init to one less, so that the incrementing code doesn't
808  * need to be special-cased.
809  */
810  priv->last_picture = output.PicInfo.picture_number - 1;
811  }
812 
813  if (avctx->codec->id == AV_CODEC_ID_MPEG4 &&
814  output.PicInfo.timeStamp == 0 && priv->bframe_bug) {
815  av_log(avctx, AV_LOG_VERBOSE,
816  "CrystalHD: Not returning packed frame twice.\n");
817  priv->last_picture++;
818  DtsReleaseOutputBuffs(dev, NULL, FALSE);
819  return RET_COPY_AGAIN;
820  }
821 
822  print_frame_info(priv, &output);
823 
824  if (priv->last_picture + 1 < output.PicInfo.picture_number) {
825  av_log(avctx, AV_LOG_WARNING,
826  "CrystalHD: Picture Number discontinuity\n");
827  /*
828  * Have we lost frames? If so, we need to shrink the
829  * pipeline length appropriately.
830  *
831  * XXX: I have no idea what the semantics of this situation
832  * are so I don't even know if we've lost frames or which
833  * ones.
834  *
835  * In any case, only warn the first time.
836  */
837  priv->last_picture = output.PicInfo.picture_number - 1;
838  }
839 
840  copy_ret = copy_frame(avctx, &output, data, got_frame);
841  if (*got_frame > 0) {
842  avctx->has_b_frames--;
843  priv->last_picture++;
844  av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Pipeline length: %u\n",
845  avctx->has_b_frames);
846  }
847  } else {
848  /*
849  * An invalid frame has been consumed.
850  */
851  av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput succeeded with "
852  "invalid PIB\n");
853  avctx->has_b_frames--;
854  copy_ret = RET_OK;
855  }
856  DtsReleaseOutputBuffs(dev, NULL, FALSE);
857 
858  return copy_ret;
859  } else if (ret == BC_STS_BUSY) {
860  return RET_COPY_AGAIN;
861  } else {
862  av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput failed %d\n", ret);
863  return RET_ERROR;
864  }
865 }
866 
867 
868 static int decode(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt)
869 {
870  BC_STATUS ret;
871  BC_DTS_STATUS decoder_status = { 0, };
872  CopyRet rec_ret;
873  CHDContext *priv = avctx->priv_data;
874  HANDLE dev = priv->dev;
875  uint8_t *in_data = avpkt->data;
876  int len = avpkt->size;
877  int free_data = 0;
878  uint8_t pic_type = 0;
879 
880  av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: decode_frame\n");
881 
882  if (avpkt->size == 7 && !priv->bframe_bug) {
883  /*
884  * The use of a drop frame triggers the bug
885  */
886  av_log(avctx, AV_LOG_INFO,
887  "CrystalHD: Enabling work-around for packed b-frame bug\n");
888  priv->bframe_bug = 1;
889  } else if (avpkt->size == 8 && priv->bframe_bug) {
890  /*
891  * Delay frames don't trigger the bug
892  */
893  av_log(avctx, AV_LOG_INFO,
894  "CrystalHD: Disabling work-around for packed b-frame bug\n");
895  priv->bframe_bug = 0;
896  }
897 
898  if (len) {
899  int32_t tx_free = (int32_t)DtsTxFreeSize(dev);
900 
901  if (priv->parser) {
902  int ret = 0;
903 
904  if (priv->bsfc) {
905  ret = av_bitstream_filter_filter(priv->bsfc, avctx, NULL,
906  &in_data, &len,
907  avpkt->data, len, 0);
908  }
909  free_data = ret > 0;
910 
911  if (ret >= 0) {
912  uint8_t *pout;
913  int psize;
914  int index;
915  H264Context *h = priv->parser->priv_data;
916 
917  index = av_parser_parse2(priv->parser, avctx, &pout, &psize,
918  in_data, len, avctx->internal->pkt->pts,
919  avctx->internal->pkt->dts, 0);
920  if (index < 0) {
921  av_log(avctx, AV_LOG_WARNING,
922  "CrystalHD: Failed to parse h.264 packet to "
923  "detect interlacing.\n");
924  } else if (index != len) {
925  av_log(avctx, AV_LOG_WARNING,
926  "CrystalHD: Failed to parse h.264 packet "
927  "completely. Interlaced frames may be "
928  "incorrectly detected.\n");
929  } else {
930  av_log(avctx, AV_LOG_VERBOSE,
931  "CrystalHD: parser picture type %d\n",
932  h->picture_structure);
933  pic_type = h->picture_structure;
934  }
935  } else {
936  av_log(avctx, AV_LOG_WARNING,
937  "CrystalHD: mp4toannexb filter failed to filter "
938  "packet. Interlaced frames may be incorrectly "
939  "detected.\n");
940  }
941  }
942 
943  if (len < tx_free - 1024) {
944  /*
945  * Despite being notionally opaque, either libcrystalhd or
946  * the hardware itself will mangle pts values that are too
947  * small or too large. The docs claim it should be in units
948  * of 100ns. Given that we're nominally dealing with a black
949  * box on both sides, any transform we do has no guarantee of
950  * avoiding mangling so we need to build a mapping to values
951  * we know will not be mangled.
952  */
953  uint64_t pts = opaque_list_push(priv, avctx->internal->pkt->pts, pic_type);
954  if (!pts) {
955  if (free_data) {
956  av_freep(&in_data);
957  }
958  return AVERROR(ENOMEM);
959  }
960  av_log(priv->avctx, AV_LOG_VERBOSE,
961  "input \"pts\": %"PRIu64"\n", pts);
962  ret = DtsProcInput(dev, in_data, len, pts, 0);
963  if (free_data) {
964  av_freep(&in_data);
965  }
966  if (ret == BC_STS_BUSY) {
967  av_log(avctx, AV_LOG_WARNING,
968  "CrystalHD: ProcInput returned busy\n");
969  usleep(BASE_WAIT);
970  return AVERROR(EBUSY);
971  } else if (ret != BC_STS_SUCCESS) {
972  av_log(avctx, AV_LOG_ERROR,
973  "CrystalHD: ProcInput failed: %u\n", ret);
974  return -1;
975  }
976  avctx->has_b_frames++;
977  } else {
978  av_log(avctx, AV_LOG_WARNING, "CrystalHD: Input buffer full\n");
979  len = 0; // We didn't consume any bytes.
980  }
981  } else {
982  av_log(avctx, AV_LOG_INFO, "CrystalHD: No more input data\n");
983  }
984 
985  if (priv->skip_next_output) {
986  av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Skipping next output.\n");
987  priv->skip_next_output = 0;
988  avctx->has_b_frames--;
989  return len;
990  }
991 
992  ret = DtsGetDriverStatus(dev, &decoder_status);
993  if (ret != BC_STS_SUCCESS) {
994  av_log(avctx, AV_LOG_ERROR, "CrystalHD: GetDriverStatus failed\n");
995  return -1;
996  }
997 
998  /*
999  * No frames ready. Don't try to extract.
1000  *
1001  * Empirical testing shows that ReadyListCount can be a damn lie,
1002  * and ProcOut still fails when count > 0. The same testing showed
1003  * that two more iterations were needed before ProcOutput would
1004  * succeed.
1005  */
1006  if (priv->output_ready < 2) {
1007  if (decoder_status.ReadyListCount != 0)
1008  priv->output_ready++;
1009  usleep(BASE_WAIT);
1010  av_log(avctx, AV_LOG_INFO, "CrystalHD: Filling pipeline.\n");
1011  return len;
1012  } else if (decoder_status.ReadyListCount == 0) {
1013  /*
1014  * After the pipeline is established, if we encounter a lack of frames
1015  * that probably means we're not giving the hardware enough time to
1016  * decode them, so start increasing the wait time at the end of a
1017  * decode call.
1018  */
1019  usleep(BASE_WAIT);
1020  priv->decode_wait += WAIT_UNIT;
1021  av_log(avctx, AV_LOG_INFO, "CrystalHD: No frames ready. Returning\n");
1022  return len;
1023  }
1024 
1025  do {
1026  rec_ret = receive_frame(avctx, data, got_frame);
1027  if (rec_ret == RET_OK && *got_frame == 0) {
1028  /*
1029  * This case is for when the encoded fields are stored
1030  * separately and we get a separate avpkt for each one. To keep
1031  * the pipeline stable, we should return nothing and wait for
1032  * the next time round to grab the second field.
1033  * H.264 PAFF is an example of this.
1034  */
1035  av_log(avctx, AV_LOG_VERBOSE, "Returning after first field.\n");
1036  avctx->has_b_frames--;
1037  } else if (rec_ret == RET_COPY_NEXT_FIELD) {
1038  /*
1039  * This case is for when the encoded fields are stored in a
1040  * single avpkt but the hardware returns then separately. Unless
1041  * we grab the second field before returning, we'll slip another
1042  * frame in the pipeline and if that happens a lot, we're sunk.
1043  * So we have to get that second field now.
1044  * Interlaced mpeg2 and vc1 are examples of this.
1045  */
1046  av_log(avctx, AV_LOG_VERBOSE, "Trying to get second field.\n");
1047  while (1) {
1048  usleep(priv->decode_wait);
1049  ret = DtsGetDriverStatus(dev, &decoder_status);
1050  if (ret == BC_STS_SUCCESS &&
1051  decoder_status.ReadyListCount > 0) {
1052  rec_ret = receive_frame(avctx, data, got_frame);
1053  if ((rec_ret == RET_OK && *got_frame > 0) ||
1054  rec_ret == RET_ERROR)
1055  break;
1056  }
1057  }
1058  av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Got second field.\n");
1059  } else if (rec_ret == RET_SKIP_NEXT_COPY) {
1060  /*
1061  * Two input packets got turned into a field pair. Gawd.
1062  */
1063  av_log(avctx, AV_LOG_VERBOSE,
1064  "Don't output on next decode call.\n");
1065  priv->skip_next_output = 1;
1066  }
1067  /*
1068  * If rec_ret == RET_COPY_AGAIN, that means that either we just handled
1069  * a FMT_CHANGE event and need to go around again for the actual frame,
1070  * we got a busy status and need to try again, or we're dealing with
1071  * packed b-frames, where the hardware strangely returns the packed
1072  * p-frame twice. We choose to keep the second copy as it carries the
1073  * valid pts.
1074  */
1075  } while (rec_ret == RET_COPY_AGAIN);
1076  usleep(priv->decode_wait);
1077  return len;
1078 }
1079 
1080 
1081 #if CONFIG_H264_CRYSTALHD_DECODER
1082 static AVClass h264_class = {
1083  "h264_crystalhd",
1085  options,
1087 };
1088 
1089 AVCodec ff_h264_crystalhd_decoder = {
1090  .name = "h264_crystalhd",
1091  .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (CrystalHD acceleration)"),
1092  .type = AVMEDIA_TYPE_VIDEO,
1093  .id = AV_CODEC_ID_H264,
1094  .priv_data_size = sizeof(CHDContext),
1095  .init = init,
1096  .close = uninit,
1097  .decode = decode,
1098  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
1099  .flush = flush,
1100  .pix_fmts = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
1101  .priv_class = &h264_class,
1102 };
1103 #endif
1104 
1105 #if CONFIG_MPEG2_CRYSTALHD_DECODER
1106 static AVClass mpeg2_class = {
1107  "mpeg2_crystalhd",
1109  options,
1111 };
1112 
1113 AVCodec ff_mpeg2_crystalhd_decoder = {
1114  .name = "mpeg2_crystalhd",
1115  .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 Video (CrystalHD acceleration)"),
1116  .type = AVMEDIA_TYPE_VIDEO,
1117  .id = AV_CODEC_ID_MPEG2VIDEO,
1118  .priv_data_size = sizeof(CHDContext),
1119  .init = init,
1120  .close = uninit,
1121  .decode = decode,
1122  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
1123  .flush = flush,
1124  .pix_fmts = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
1125  .priv_class = &mpeg2_class,
1126 };
1127 #endif
1128 
1129 #if CONFIG_MPEG4_CRYSTALHD_DECODER
1130 static AVClass mpeg4_class = {
1131  "mpeg4_crystalhd",
1133  options,
1135 };
1136 
1137 AVCodec ff_mpeg4_crystalhd_decoder = {
1138  .name = "mpeg4_crystalhd",
1139  .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 (CrystalHD acceleration)"),
1140  .type = AVMEDIA_TYPE_VIDEO,
1141  .id = AV_CODEC_ID_MPEG4,
1142  .priv_data_size = sizeof(CHDContext),
1143  .init = init,
1144  .close = uninit,
1145  .decode = decode,
1146  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
1147  .flush = flush,
1148  .pix_fmts = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
1149  .priv_class = &mpeg4_class,
1150 };
1151 #endif
1152 
1153 #if CONFIG_MSMPEG4_CRYSTALHD_DECODER
1154 static AVClass msmpeg4_class = {
1155  "msmpeg4_crystalhd",
1157  options,
1159 };
1160 
1161 AVCodec ff_msmpeg4_crystalhd_decoder = {
1162  .name = "msmpeg4_crystalhd",
1163  .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 Microsoft variant version 3 (CrystalHD acceleration)"),
1164  .type = AVMEDIA_TYPE_VIDEO,
1165  .id = AV_CODEC_ID_MSMPEG4V3,
1166  .priv_data_size = sizeof(CHDContext),
1167  .init = init,
1168  .close = uninit,
1169  .decode = decode,
1171  .flush = flush,
1172  .pix_fmts = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
1173  .priv_class = &msmpeg4_class,
1174 };
1175 #endif
1176 
1177 #if CONFIG_VC1_CRYSTALHD_DECODER
1178 static AVClass vc1_class = {
1179  "vc1_crystalhd",
1181  options,
1183 };
1184 
1185 AVCodec ff_vc1_crystalhd_decoder = {
1186  .name = "vc1_crystalhd",
1187  .long_name = NULL_IF_CONFIG_SMALL("SMPTE VC-1 (CrystalHD acceleration)"),
1188  .type = AVMEDIA_TYPE_VIDEO,
1189  .id = AV_CODEC_ID_VC1,
1190  .priv_data_size = sizeof(CHDContext),
1191  .init = init,
1192  .close = uninit,
1193  .decode = decode,
1194  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
1195  .flush = flush,
1196  .pix_fmts = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
1197  .priv_class = &vc1_class,
1198 };
1199 #endif
1200 
1201 #if CONFIG_WMV3_CRYSTALHD_DECODER
1202 static AVClass wmv3_class = {
1203  "wmv3_crystalhd",
1205  options,
1207 };
1208 
1209 AVCodec ff_wmv3_crystalhd_decoder = {
1210  .name = "wmv3_crystalhd",
1211  .long_name = NULL_IF_CONFIG_SMALL("Windows Media Video 9 (CrystalHD acceleration)"),
1212  .type = AVMEDIA_TYPE_VIDEO,
1213  .id = AV_CODEC_ID_WMV3,
1214  .priv_data_size = sizeof(CHDContext),
1215  .init = init,
1216  .close = uninit,
1217  .decode = decode,
1218  .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
1219  .flush = flush,
1220  .pix_fmts = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
1221  .priv_class = &wmv3_class,
1222 };
1223 #endif