2 * - CrystalHD decoder module -
4 * Copyright(C) 2010,2011 Philip Langdale <ffmpeg.philipl@overt.org>
6 * This file is part of FFmpeg.
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.
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.
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
24 * - Principles of Operation -
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.
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.
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.
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.
46 * Finally, while it is tempting to say that once the decoder starts outputing
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.
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.
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).
72 /*****************************************************************************
74 ****************************************************************************/
76 #define _XOPEN_SOURCE 600
82 #include <libcrystalhd/bc_dts_types.h>
83 #include <libcrystalhd/bc_dts_defs.h>
84 #include <libcrystalhd/libcrystalhd_if.h>
88 #include "libavutil/imgutils.h"
89 #include "libavutil/intreadwrite.h"
90 #include "libavutil/opt.h"
92 /** Timeout parameter passed to DtsProcOutput() in us */
93 #define OUTPUT_PROC_TIMEOUT 50
94 /** Step between fake timestamps passed to hardware in units of 100ns */
95 #define TIMESTAMP_UNIT 100000
96 /** Initial value in us of the wait in decode() */
97 #define BASE_WAIT 10000
98 /** Increment in us to adjust wait in decode() */
99 #define WAIT_UNIT 1000
102 /*****************************************************************************
103 * Module private data
104 ****************************************************************************/
110 RET_SKIP_NEXT_COPY = 2,
111 RET_COPY_NEXT_FIELD = 3,
114 typedef struct OpaqueList {
115 struct OpaqueList *next;
116 uint64_t fake_timestamp;
117 uint64_t reordered_opaque;
123 AVCodecContext *avctx;
127 AVBitStreamFilterContext *bsfc;
128 AVCodecParserContext *parser;
131 uint8_t *sps_pps_buf;
132 uint32_t sps_pps_size;
134 uint8_t output_ready;
135 uint8_t need_second_field;
136 uint8_t skip_next_output;
137 uint64_t decode_wait;
139 uint64_t last_picture;
149 static const AVOption options[] = {
150 { "crystalhd_downscale_width",
151 "Turn on downscaling to the specified width",
152 offsetof(CHDContext, sWidth),
153 FF_OPT_TYPE_INT, 0, 0, UINT32_MAX,
154 AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM, },
159 /*****************************************************************************
161 ****************************************************************************/
163 static inline BC_MEDIA_SUBTYPE id2subtype(CHDContext *priv, enum CodecID id)
167 return BC_MSUBTYPE_DIVX;
168 case CODEC_ID_MSMPEG4V3:
169 return BC_MSUBTYPE_DIVX311;
170 case CODEC_ID_MPEG2VIDEO:
171 return BC_MSUBTYPE_MPEG2VIDEO;
173 return BC_MSUBTYPE_VC1;
175 return BC_MSUBTYPE_WMV3;
177 return priv->is_nal ? BC_MSUBTYPE_AVC1 : BC_MSUBTYPE_H264;
179 return BC_MSUBTYPE_INVALID;
183 static inline void print_frame_info(CHDContext *priv, BC_DTS_PROC_OUT *output)
185 av_log(priv->avctx, AV_LOG_VERBOSE, "\tYBuffSz: %u\n", output->YbuffSz);
186 av_log(priv->avctx, AV_LOG_VERBOSE, "\tYBuffDoneSz: %u\n",
187 output->YBuffDoneSz);
188 av_log(priv->avctx, AV_LOG_VERBOSE, "\tUVBuffDoneSz: %u\n",
189 output->UVBuffDoneSz);
190 av_log(priv->avctx, AV_LOG_VERBOSE, "\tTimestamp: %"PRIu64"\n",
191 output->PicInfo.timeStamp);
192 av_log(priv->avctx, AV_LOG_VERBOSE, "\tPicture Number: %u\n",
193 output->PicInfo.picture_number);
194 av_log(priv->avctx, AV_LOG_VERBOSE, "\tWidth: %u\n",
195 output->PicInfo.width);
196 av_log(priv->avctx, AV_LOG_VERBOSE, "\tHeight: %u\n",
197 output->PicInfo.height);
198 av_log(priv->avctx, AV_LOG_VERBOSE, "\tChroma: 0x%03x\n",
199 output->PicInfo.chroma_format);
200 av_log(priv->avctx, AV_LOG_VERBOSE, "\tPulldown: %u\n",
201 output->PicInfo.pulldown);
202 av_log(priv->avctx, AV_LOG_VERBOSE, "\tFlags: 0x%08x\n",
203 output->PicInfo.flags);
204 av_log(priv->avctx, AV_LOG_VERBOSE, "\tFrame Rate/Res: %u\n",
205 output->PicInfo.frame_rate);
206 av_log(priv->avctx, AV_LOG_VERBOSE, "\tAspect Ratio: %u\n",
207 output->PicInfo.aspect_ratio);
208 av_log(priv->avctx, AV_LOG_VERBOSE, "\tColor Primaries: %u\n",
209 output->PicInfo.colour_primaries);
210 av_log(priv->avctx, AV_LOG_VERBOSE, "\tMetaData: %u\n",
211 output->PicInfo.picture_meta_payload);
212 av_log(priv->avctx, AV_LOG_VERBOSE, "\tSession Number: %u\n",
213 output->PicInfo.sess_num);
214 av_log(priv->avctx, AV_LOG_VERBOSE, "\tycom: %u\n",
215 output->PicInfo.ycom);
216 av_log(priv->avctx, AV_LOG_VERBOSE, "\tCustom Aspect: %u\n",
217 output->PicInfo.custom_aspect_ratio_width_height);
218 av_log(priv->avctx, AV_LOG_VERBOSE, "\tFrames to Drop: %u\n",
219 output->PicInfo.n_drop);
220 av_log(priv->avctx, AV_LOG_VERBOSE, "\tH264 Valid Fields: 0x%08x\n",
221 output->PicInfo.other.h264.valid);
225 /*****************************************************************************
226 * OpaqueList functions
227 ****************************************************************************/
229 static uint64_t opaque_list_push(CHDContext *priv, uint64_t reordered_opaque,
232 OpaqueList *newNode = av_mallocz(sizeof (OpaqueList));
234 av_log(priv->avctx, AV_LOG_ERROR,
235 "Unable to allocate new node in OpaqueList.\n");
239 newNode->fake_timestamp = TIMESTAMP_UNIT;
240 priv->head = newNode;
242 newNode->fake_timestamp = priv->tail->fake_timestamp + TIMESTAMP_UNIT;
243 priv->tail->next = newNode;
245 priv->tail = newNode;
246 newNode->reordered_opaque = reordered_opaque;
247 newNode->pic_type = pic_type;
249 return newNode->fake_timestamp;
253 * The OpaqueList is built in decode order, while elements will be removed
254 * in presentation order. If frames are reordered, this means we must be
255 * able to remove elements that are not the first element.
257 * Returned node must be freed by caller.
259 static OpaqueList *opaque_list_pop(CHDContext *priv, uint64_t fake_timestamp)
261 OpaqueList *node = priv->head;
264 av_log(priv->avctx, AV_LOG_ERROR,
265 "CrystalHD: Attempted to query non-existent timestamps.\n");
270 * The first element is special-cased because we have to manipulate
271 * the head pointer rather than the previous element in the list.
273 if (priv->head->fake_timestamp == fake_timestamp) {
274 priv->head = node->next;
276 if (!priv->head->next)
277 priv->tail = priv->head;
284 * The list is processed at arm's length so that we have the
285 * previous element available to rewrite its next pointer.
288 OpaqueList *current = node->next;
289 if (current->fake_timestamp == fake_timestamp) {
290 node->next = current->next;
295 current->next = NULL;
302 av_log(priv->avctx, AV_LOG_VERBOSE,
303 "CrystalHD: Couldn't match fake_timestamp.\n");
308 /*****************************************************************************
309 * Video decoder API function definitions
310 ****************************************************************************/
312 static void flush(AVCodecContext *avctx)
314 CHDContext *priv = avctx->priv_data;
316 avctx->has_b_frames = 0;
317 priv->last_picture = -1;
318 priv->output_ready = 0;
319 priv->need_second_field = 0;
320 priv->skip_next_output = 0;
321 priv->decode_wait = BASE_WAIT;
323 if (priv->pic.data[0])
324 avctx->release_buffer(avctx, &priv->pic);
326 /* Flush mode 4 flushes all software and hardware buffers. */
327 DtsFlushInput(priv->dev, 4);
331 static av_cold int uninit(AVCodecContext *avctx)
333 CHDContext *priv = avctx->priv_data;
337 DtsStopDecoder(device);
338 DtsCloseDecoder(device);
339 DtsDeviceClose(device);
341 av_parser_close(priv->parser);
343 av_bitstream_filter_close(priv->bsfc);
346 av_free(priv->sps_pps_buf);
348 if (priv->pic.data[0])
349 avctx->release_buffer(avctx, &priv->pic);
352 OpaqueList *node = priv->head;
354 OpaqueList *next = node->next;
364 static av_cold int init(AVCodecContext *avctx)
368 BC_INFO_CRYSTAL version;
369 BC_INPUT_FORMAT format = {
372 .OptFlags = 0x80000000 | vdecFrameRate59_94 | 0x40,
373 .width = avctx->width,
374 .height = avctx->height,
377 BC_MEDIA_SUBTYPE subtype;
379 uint32_t mode = DTS_PLAYBACK_MODE |
380 DTS_LOAD_FILE_PLAY_FW |
381 DTS_SKIP_TX_CHK_CPB |
382 DTS_PLAYBACK_DROP_RPT_MODE |
383 DTS_SINGLE_THREADED_MODE |
384 DTS_DFLT_RESOLUTION(vdecRESOLUTION_1080p23_976);
386 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD Init for %s\n",
389 avctx->pix_fmt = PIX_FMT_YUYV422;
391 /* Initialize the library */
392 priv = avctx->priv_data;
394 priv->is_nal = avctx->extradata_size > 0 && *(avctx->extradata) == 1;
395 priv->last_picture = -1;
396 priv->decode_wait = BASE_WAIT;
398 subtype = id2subtype(priv, avctx->codec->id);
400 case BC_MSUBTYPE_AVC1:
405 priv->bsfc = av_bitstream_filter_init("h264_mp4toannexb");
407 av_log(avctx, AV_LOG_ERROR,
408 "Cannot open the h264_mp4toannexb BSF!\n");
409 return AVERROR_BSF_NOT_FOUND;
411 av_bitstream_filter_filter(priv->bsfc, avctx, NULL, &dummy_p,
412 &dummy_int, NULL, 0, 0);
414 subtype = BC_MSUBTYPE_H264;
416 case BC_MSUBTYPE_H264:
417 format.startCodeSz = 4;
419 case BC_MSUBTYPE_VC1:
420 case BC_MSUBTYPE_WVC1:
421 case BC_MSUBTYPE_WMV3:
422 case BC_MSUBTYPE_WMVA:
423 case BC_MSUBTYPE_MPEG2VIDEO:
424 case BC_MSUBTYPE_DIVX:
425 case BC_MSUBTYPE_DIVX311:
426 format.pMetaData = avctx->extradata;
427 format.metaDataSz = avctx->extradata_size;
430 av_log(avctx, AV_LOG_ERROR, "CrystalHD: Unknown codec name\n");
431 return AVERROR(EINVAL);
433 format.mSubtype = subtype;
436 format.bEnableScaling = 1;
437 format.ScalingParams.sWidth = priv->sWidth;
440 /* Get a decoder instance */
441 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: starting up\n");
442 // Initialize the Link and Decoder devices
443 ret = DtsDeviceOpen(&priv->dev, mode);
444 if (ret != BC_STS_SUCCESS) {
445 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: DtsDeviceOpen failed\n");
449 ret = DtsCrystalHDVersion(priv->dev, &version);
450 if (ret != BC_STS_SUCCESS) {
451 av_log(avctx, AV_LOG_VERBOSE,
452 "CrystalHD: DtsCrystalHDVersion failed\n");
455 priv->is_70012 = version.device == 0;
457 if (priv->is_70012 &&
458 (subtype == BC_MSUBTYPE_DIVX || subtype == BC_MSUBTYPE_DIVX311)) {
459 av_log(avctx, AV_LOG_VERBOSE,
460 "CrystalHD: BCM70012 doesn't support MPEG4-ASP/DivX/Xvid\n");
464 ret = DtsSetInputFormat(priv->dev, &format);
465 if (ret != BC_STS_SUCCESS) {
466 av_log(avctx, AV_LOG_ERROR, "CrystalHD: SetInputFormat failed\n");
470 ret = DtsOpenDecoder(priv->dev, BC_STREAM_TYPE_ES);
471 if (ret != BC_STS_SUCCESS) {
472 av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsOpenDecoder failed\n");
476 ret = DtsSetColorSpace(priv->dev, OUTPUT_MODE422_YUY2);
477 if (ret != BC_STS_SUCCESS) {
478 av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsSetColorSpace failed\n");
481 ret = DtsStartDecoder(priv->dev);
482 if (ret != BC_STS_SUCCESS) {
483 av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartDecoder failed\n");
486 ret = DtsStartCapture(priv->dev);
487 if (ret != BC_STS_SUCCESS) {
488 av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartCapture failed\n");
492 if (avctx->codec->id == CODEC_ID_H264) {
493 priv->parser = av_parser_init(avctx->codec->id);
495 av_log(avctx, AV_LOG_WARNING,
496 "Cannot open the h.264 parser! Interlaced h.264 content "
497 "will not be detected reliably.\n");
498 priv->parser->flags = PARSER_FLAG_COMPLETE_FRAMES;
500 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Init complete.\n");
510 static inline CopyRet copy_frame(AVCodecContext *avctx,
511 BC_DTS_PROC_OUT *output,
512 void *data, int *data_size)
515 BC_DTS_STATUS decoder_status;
516 uint8_t trust_interlaced;
519 CHDContext *priv = avctx->priv_data;
520 int64_t pkt_pts = AV_NOPTS_VALUE;
521 uint8_t pic_type = 0;
523 uint8_t bottom_field = (output->PicInfo.flags & VDEC_FLAG_BOTTOMFIELD) ==
524 VDEC_FLAG_BOTTOMFIELD;
525 uint8_t bottom_first = !!(output->PicInfo.flags & VDEC_FLAG_BOTTOM_FIRST);
527 int width = output->PicInfo.width;
528 int height = output->PicInfo.height;
530 uint8_t *src = output->Ybuff;
535 if (output->PicInfo.timeStamp != 0) {
536 OpaqueList *node = opaque_list_pop(priv, output->PicInfo.timeStamp);
538 pkt_pts = node->reordered_opaque;
539 pic_type = node->pic_type;
543 * We will encounter a situation where a timestamp cannot be
544 * popped if a second field is being returned. In this case,
545 * each field has the same timestamp and the first one will
546 * cause it to be popped. To keep subsequent calculations
547 * simple, pic_type should be set a FIELD value - doesn't
548 * matter which, but I chose BOTTOM.
550 pic_type = PICT_BOTTOM_FIELD;
552 av_log(avctx, AV_LOG_VERBOSE, "output \"pts\": %"PRIu64"\n",
553 output->PicInfo.timeStamp);
554 av_log(avctx, AV_LOG_VERBOSE, "output picture type %d\n",
558 ret = DtsGetDriverStatus(priv->dev, &decoder_status);
559 if (ret != BC_STS_SUCCESS) {
560 av_log(avctx, AV_LOG_ERROR,
561 "CrystalHD: GetDriverStatus failed: %u\n", ret);
566 * For most content, we can trust the interlaced flag returned
567 * by the hardware, but sometimes we can't. These are the
568 * conditions under which we can trust the flag:
570 * 1) It's not h.264 content
571 * 2) The UNKNOWN_SRC flag is not set
572 * 3) We know we're expecting a second field
573 * 4) The hardware reports this picture and the next picture
574 * have the same picture number.
576 * Note that there can still be interlaced content that will
577 * fail this check, if the hardware hasn't decoded the next
578 * picture or if there is a corruption in the stream. (In either
579 * case a 0 will be returned for the next picture number)
581 trust_interlaced = avctx->codec->id != CODEC_ID_H264 ||
582 !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ||
583 priv->need_second_field ||
584 (decoder_status.picNumFlags & ~0x40000000) ==
585 output->PicInfo.picture_number;
588 * If we got a false negative for trust_interlaced on the first field,
589 * we will realise our mistake here when we see that the picture number is that
590 * of the previous picture. We cannot recover the frame and should discard the
591 * second field to keep the correct number of output frames.
593 if (output->PicInfo.picture_number == priv->last_picture && !priv->need_second_field) {
594 av_log(avctx, AV_LOG_WARNING,
595 "Incorrectly guessed progressive frame. Discarding second field\n");
596 /* Returning without providing a picture. */
600 interlaced = (output->PicInfo.flags & VDEC_FLAG_INTERLACED_SRC) &&
603 if (!trust_interlaced && (decoder_status.picNumFlags & ~0x40000000) == 0) {
604 av_log(avctx, AV_LOG_VERBOSE,
605 "Next picture number unknown. Assuming progressive frame.\n");
608 av_log(avctx, AV_LOG_VERBOSE, "Interlaced state: %d | trust_interlaced %d\n",
609 interlaced, trust_interlaced);
611 if (priv->pic.data[0] && !priv->need_second_field)
612 avctx->release_buffer(avctx, &priv->pic);
614 priv->need_second_field = interlaced && !priv->need_second_field;
616 priv->pic.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE |
617 FF_BUFFER_HINTS_REUSABLE;
618 if (!priv->pic.data[0]) {
619 if (avctx->get_buffer(avctx, &priv->pic) < 0) {
620 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
625 bwidth = av_image_get_linesize(avctx->pix_fmt, width, 0);
626 if (priv->is_70012) {
631 else if (width <= 1280)
633 else if (width <= 1080)
635 sStride = av_image_get_linesize(avctx->pix_fmt, pStride, 0);
640 dStride = priv->pic.linesize[0];
641 dst = priv->pic.data[0];
643 av_log(priv->avctx, AV_LOG_VERBOSE, "CrystalHD: Copying out frame\n");
651 av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: bottom field\n");
654 av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: top field\n");
658 for (sY = 0; sY < height; dY++, sY++) {
659 memcpy(&(dst[dY * dStride]), &(src[sY * sStride]), bwidth);
663 av_image_copy_plane(dst, dStride, src, sStride, bwidth, height);
666 priv->pic.interlaced_frame = interlaced;
668 priv->pic.top_field_first = !bottom_first;
670 priv->pic.pkt_pts = pkt_pts;
672 if (!priv->need_second_field) {
673 *data_size = sizeof(AVFrame);
674 *(AVFrame *)data = priv->pic;
678 * Two types of PAFF content have been observed. One form causes the
679 * hardware to return a field pair and the other individual fields,
680 * even though the input is always individual fields. We must skip
681 * copying on the next decode() call to maintain pipeline length in
684 if (!interlaced && (output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) &&
685 (pic_type == PICT_TOP_FIELD || pic_type == PICT_BOTTOM_FIELD)) {
686 av_log(priv->avctx, AV_LOG_VERBOSE, "Fieldpair from two packets.\n");
687 return RET_SKIP_NEXT_COPY;
691 * Testing has shown that in all cases where we don't want to return the
692 * full frame immediately, VDEC_FLAG_UNKNOWN_SRC is set.
694 return priv->need_second_field &&
695 !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ?
696 RET_COPY_NEXT_FIELD : RET_OK;
700 static inline CopyRet receive_frame(AVCodecContext *avctx,
701 void *data, int *data_size)
704 BC_DTS_PROC_OUT output = {
705 .PicInfo.width = avctx->width,
706 .PicInfo.height = avctx->height,
708 CHDContext *priv = avctx->priv_data;
709 HANDLE dev = priv->dev;
713 // Request decoded data from the driver
714 ret = DtsProcOutputNoCopy(dev, OUTPUT_PROC_TIMEOUT, &output);
715 if (ret == BC_STS_FMT_CHANGE) {
716 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Initial format change\n");
717 avctx->width = output.PicInfo.width;
718 avctx->height = output.PicInfo.height;
719 return RET_COPY_AGAIN;
720 } else if (ret == BC_STS_SUCCESS) {
722 if (output.PoutFlags & BC_POUT_FLAGS_PIB_VALID) {
723 if (priv->last_picture == -1) {
725 * Init to one less, so that the incrementing code doesn't
726 * need to be special-cased.
728 priv->last_picture = output.PicInfo.picture_number - 1;
731 if (avctx->codec->id == CODEC_ID_MPEG4 &&
732 output.PicInfo.timeStamp == 0 && priv->bframe_bug) {
733 av_log(avctx, AV_LOG_VERBOSE,
734 "CrystalHD: Not returning packed frame twice.\n");
735 priv->last_picture++;
736 DtsReleaseOutputBuffs(dev, NULL, FALSE);
737 return RET_COPY_AGAIN;
740 print_frame_info(priv, &output);
742 if (priv->last_picture + 1 < output.PicInfo.picture_number) {
743 av_log(avctx, AV_LOG_WARNING,
744 "CrystalHD: Picture Number discontinuity\n");
746 * Have we lost frames? If so, we need to shrink the
747 * pipeline length appropriately.
749 * XXX: I have no idea what the semantics of this situation
750 * are so I don't even know if we've lost frames or which
753 * In any case, only warn the first time.
755 priv->last_picture = output.PicInfo.picture_number - 1;
758 copy_ret = copy_frame(avctx, &output, data, data_size);
759 if (*data_size > 0) {
760 avctx->has_b_frames--;
761 priv->last_picture++;
762 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Pipeline length: %u\n",
763 avctx->has_b_frames);
767 * An invalid frame has been consumed.
769 av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput succeeded with "
771 avctx->has_b_frames--;
774 DtsReleaseOutputBuffs(dev, NULL, FALSE);
777 } else if (ret == BC_STS_BUSY) {
778 return RET_COPY_AGAIN;
780 av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput failed %d\n", ret);
786 static int decode(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
789 BC_DTS_STATUS decoder_status;
791 CHDContext *priv = avctx->priv_data;
792 HANDLE dev = priv->dev;
793 uint8_t *in_data = avpkt->data;
794 int len = avpkt->size;
796 uint8_t pic_type = 0;
798 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: decode_frame\n");
800 if (avpkt->size == 7 && !priv->bframe_bug) {
802 * The use of a drop frame triggers the bug
804 av_log(avctx, AV_LOG_INFO,
805 "CrystalHD: Enabling work-around for packed b-frame bug\n");
806 priv->bframe_bug = 1;
807 } else if (avpkt->size == 8 && priv->bframe_bug) {
809 * Delay frames don't trigger the bug
811 av_log(avctx, AV_LOG_INFO,
812 "CrystalHD: Disabling work-around for packed b-frame bug\n");
813 priv->bframe_bug = 0;
817 int32_t tx_free = (int32_t)DtsTxFreeSize(dev);
823 ret = av_bitstream_filter_filter(priv->bsfc, avctx, NULL,
825 avpkt->data, len, 0);
833 H264Context *h = priv->parser->priv_data;
835 index = av_parser_parse2(priv->parser, avctx, &pout, &psize,
836 in_data, len, avctx->pkt->pts,
839 av_log(avctx, AV_LOG_WARNING,
840 "CrystalHD: Failed to parse h.264 packet to "
841 "detect interlacing.\n");
842 } else if (index != len) {
843 av_log(avctx, AV_LOG_WARNING,
844 "CrystalHD: Failed to parse h.264 packet "
845 "completely. Interlaced frames may be "
846 "incorrectly detected\n.");
848 av_log(avctx, AV_LOG_VERBOSE,
849 "CrystalHD: parser picture type %d\n",
850 h->s.picture_structure);
851 pic_type = h->s.picture_structure;
854 av_log(avctx, AV_LOG_WARNING,
855 "CrystalHD: mp4toannexb filter failed to filter "
856 "packet. Interlaced frames may be incorrectly "
861 if (len < tx_free - 1024) {
863 * Despite being notionally opaque, either libcrystalhd or
864 * the hardware itself will mangle pts values that are too
865 * small or too large. The docs claim it should be in units
866 * of 100ns. Given that we're nominally dealing with a black
867 * box on both sides, any transform we do has no guarantee of
868 * avoiding mangling so we need to build a mapping to values
869 * we know will not be mangled.
871 uint64_t pts = opaque_list_push(priv, avctx->pkt->pts, pic_type);
876 return AVERROR(ENOMEM);
878 av_log(priv->avctx, AV_LOG_VERBOSE,
879 "input \"pts\": %"PRIu64"\n", pts);
880 ret = DtsProcInput(dev, in_data, len, pts, 0);
884 if (ret == BC_STS_BUSY) {
885 av_log(avctx, AV_LOG_WARNING,
886 "CrystalHD: ProcInput returned busy\n");
888 return AVERROR(EBUSY);
889 } else if (ret != BC_STS_SUCCESS) {
890 av_log(avctx, AV_LOG_ERROR,
891 "CrystalHD: ProcInput failed: %u\n", ret);
894 avctx->has_b_frames++;
896 av_log(avctx, AV_LOG_WARNING, "CrystalHD: Input buffer full\n");
897 len = 0; // We didn't consume any bytes.
900 av_log(avctx, AV_LOG_INFO, "CrystalHD: No more input data\n");
903 if (priv->skip_next_output) {
904 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Skipping next output.\n");
905 priv->skip_next_output = 0;
906 avctx->has_b_frames--;
910 ret = DtsGetDriverStatus(dev, &decoder_status);
911 if (ret != BC_STS_SUCCESS) {
912 av_log(avctx, AV_LOG_ERROR, "CrystalHD: GetDriverStatus failed\n");
917 * No frames ready. Don't try to extract.
919 * Empirical testing shows that ReadyListCount can be a damn lie,
920 * and ProcOut still fails when count > 0. The same testing showed
921 * that two more iterations were needed before ProcOutput would
924 if (priv->output_ready < 2) {
925 if (decoder_status.ReadyListCount != 0)
926 priv->output_ready++;
928 av_log(avctx, AV_LOG_INFO, "CrystalHD: Filling pipeline.\n");
930 } else if (decoder_status.ReadyListCount == 0) {
932 * After the pipeline is established, if we encounter a lack of frames
933 * that probably means we're not giving the hardware enough time to
934 * decode them, so start increasing the wait time at the end of a
938 priv->decode_wait += WAIT_UNIT;
939 av_log(avctx, AV_LOG_INFO, "CrystalHD: No frames ready. Returning\n");
944 rec_ret = receive_frame(avctx, data, data_size);
945 if (rec_ret == RET_OK && *data_size == 0) {
947 * This case is for when the encoded fields are stored
948 * separately and we get a separate avpkt for each one. To keep
949 * the pipeline stable, we should return nothing and wait for
950 * the next time round to grab the second field.
951 * H.264 PAFF is an example of this.
953 av_log(avctx, AV_LOG_VERBOSE, "Returning after first field.\n");
954 avctx->has_b_frames--;
955 } else if (rec_ret == RET_COPY_NEXT_FIELD) {
957 * This case is for when the encoded fields are stored in a
958 * single avpkt but the hardware returns then separately. Unless
959 * we grab the second field before returning, we'll slip another
960 * frame in the pipeline and if that happens a lot, we're sunk.
961 * So we have to get that second field now.
962 * Interlaced mpeg2 and vc1 are examples of this.
964 av_log(avctx, AV_LOG_VERBOSE, "Trying to get second field.\n");
966 usleep(priv->decode_wait);
967 ret = DtsGetDriverStatus(dev, &decoder_status);
968 if (ret == BC_STS_SUCCESS &&
969 decoder_status.ReadyListCount > 0) {
970 rec_ret = receive_frame(avctx, data, data_size);
971 if ((rec_ret == RET_OK && *data_size > 0) ||
972 rec_ret == RET_ERROR)
976 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Got second field.\n");
977 } else if (rec_ret == RET_SKIP_NEXT_COPY) {
979 * Two input packets got turned into a field pair. Gawd.
981 av_log(avctx, AV_LOG_VERBOSE,
982 "Don't output on next decode call.\n");
983 priv->skip_next_output = 1;
986 * If rec_ret == RET_COPY_AGAIN, that means that either we just handled
987 * a FMT_CHANGE event and need to go around again for the actual frame,
988 * we got a busy status and need to try again, or we're dealing with
989 * packed b-frames, where the hardware strangely returns the packed
990 * p-frame twice. We choose to keep the second copy as it carries the
993 } while (rec_ret == RET_COPY_AGAIN);
994 usleep(priv->decode_wait);
999 #if CONFIG_H264_CRYSTALHD_DECODER
1000 static AVClass h264_class = {
1002 av_default_item_name,
1004 LIBAVUTIL_VERSION_INT,
1007 AVCodec ff_h264_crystalhd_decoder = {
1008 .name = "h264_crystalhd",
1009 .type = AVMEDIA_TYPE_VIDEO,
1010 .id = CODEC_ID_H264,
1011 .priv_data_size = sizeof(CHDContext),
1015 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1017 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (CrystalHD acceleration)"),
1018 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1019 .priv_class = &h264_class,
1023 #if CONFIG_MPEG2_CRYSTALHD_DECODER
1024 static AVClass mpeg2_class = {
1026 av_default_item_name,
1028 LIBAVUTIL_VERSION_INT,
1031 AVCodec ff_mpeg2_crystalhd_decoder = {
1032 .name = "mpeg2_crystalhd",
1033 .type = AVMEDIA_TYPE_VIDEO,
1034 .id = CODEC_ID_MPEG2VIDEO,
1035 .priv_data_size = sizeof(CHDContext),
1039 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1041 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 Video (CrystalHD acceleration)"),
1042 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1043 .priv_class = &mpeg2_class,
1047 #if CONFIG_MPEG4_CRYSTALHD_DECODER
1048 static AVClass mpeg4_class = {
1050 av_default_item_name,
1052 LIBAVUTIL_VERSION_INT,
1055 AVCodec ff_mpeg4_crystalhd_decoder = {
1056 .name = "mpeg4_crystalhd",
1057 .type = AVMEDIA_TYPE_VIDEO,
1058 .id = CODEC_ID_MPEG4,
1059 .priv_data_size = sizeof(CHDContext),
1063 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1065 .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 (CrystalHD acceleration)"),
1066 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1067 .priv_class = &mpeg4_class,
1071 #if CONFIG_MSMPEG4_CRYSTALHD_DECODER
1072 static AVClass msmpeg4_class = {
1073 "msmpeg4_crystalhd",
1074 av_default_item_name,
1076 LIBAVUTIL_VERSION_INT,
1079 AVCodec ff_msmpeg4_crystalhd_decoder = {
1080 .name = "msmpeg4_crystalhd",
1081 .type = AVMEDIA_TYPE_VIDEO,
1082 .id = CODEC_ID_MSMPEG4V3,
1083 .priv_data_size = sizeof(CHDContext),
1087 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1089 .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 Microsoft variant version 3 (CrystalHD acceleration)"),
1090 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1091 .priv_class = &msmpeg4_class,
1095 #if CONFIG_VC1_CRYSTALHD_DECODER
1096 static AVClass vc1_class = {
1098 av_default_item_name,
1100 LIBAVUTIL_VERSION_INT,
1103 AVCodec ff_vc1_crystalhd_decoder = {
1104 .name = "vc1_crystalhd",
1105 .type = AVMEDIA_TYPE_VIDEO,
1107 .priv_data_size = sizeof(CHDContext),
1111 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1113 .long_name = NULL_IF_CONFIG_SMALL("SMPTE VC-1 (CrystalHD acceleration)"),
1114 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1115 .priv_class = &vc1_class,
1119 #if CONFIG_WMV3_CRYSTALHD_DECODER
1120 static AVClass wmv3_class = {
1122 av_default_item_name,
1124 LIBAVUTIL_VERSION_INT,
1127 AVCodec ff_wmv3_crystalhd_decoder = {
1128 .name = "wmv3_crystalhd",
1129 .type = AVMEDIA_TYPE_VIDEO,
1130 .id = CODEC_ID_WMV3,
1131 .priv_data_size = sizeof(CHDContext),
1135 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1137 .long_name = NULL_IF_CONFIG_SMALL("Windows Media Video 9 (CrystalHD acceleration)"),
1138 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1139 .priv_class = &wmv3_class,