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 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.
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
81 #include <libcrystalhd/bc_dts_types.h>
82 #include <libcrystalhd/bc_dts_defs.h>
83 #include <libcrystalhd/libcrystalhd_if.h>
88 #include "libavutil/imgutils.h"
89 #include "libavutil/intreadwrite.h"
90 #include "libavutil/opt.h"
96 /** Timeout parameter passed to DtsProcOutput() in us */
97 #define OUTPUT_PROC_TIMEOUT 50
98 /** Step between fake timestamps passed to hardware in units of 100ns */
99 #define TIMESTAMP_UNIT 100000
100 /** Initial value in us of the wait in decode() */
101 #define BASE_WAIT 10000
102 /** Increment in us to adjust wait in decode() */
103 #define WAIT_UNIT 1000
106 /*****************************************************************************
107 * Module private data
108 ****************************************************************************/
114 RET_SKIP_NEXT_COPY = 2,
115 RET_COPY_NEXT_FIELD = 3,
118 typedef struct OpaqueList {
119 struct OpaqueList *next;
120 uint64_t fake_timestamp;
121 uint64_t reordered_opaque;
127 AVCodecContext *avctx;
131 uint8_t *orig_extradata;
132 uint32_t orig_extradata_size;
135 AVCodecParserContext *parser;
138 uint8_t *sps_pps_buf;
139 uint32_t sps_pps_size;
141 uint8_t output_ready;
142 uint8_t need_second_field;
143 uint8_t skip_next_output;
144 uint64_t decode_wait;
146 uint64_t last_picture;
156 static const AVOption options[] = {
157 { "crystalhd_downscale_width",
158 "Turn on downscaling to the specified width",
159 offsetof(CHDContext, sWidth),
160 AV_OPT_TYPE_INT, {.i64 = 0}, 0, UINT32_MAX,
161 AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM, },
166 /*****************************************************************************
168 ****************************************************************************/
170 static inline BC_MEDIA_SUBTYPE id2subtype(CHDContext *priv, enum AVCodecID id)
173 case AV_CODEC_ID_MPEG4:
174 return BC_MSUBTYPE_DIVX;
175 case AV_CODEC_ID_MSMPEG4V3:
176 return BC_MSUBTYPE_DIVX311;
177 case AV_CODEC_ID_MPEG2VIDEO:
178 return BC_MSUBTYPE_MPEG2VIDEO;
179 case AV_CODEC_ID_VC1:
180 return BC_MSUBTYPE_VC1;
181 case AV_CODEC_ID_WMV3:
182 return BC_MSUBTYPE_WMV3;
183 case AV_CODEC_ID_H264:
184 return priv->is_nal ? BC_MSUBTYPE_AVC1 : BC_MSUBTYPE_H264;
186 return BC_MSUBTYPE_INVALID;
190 static inline void print_frame_info(CHDContext *priv, BC_DTS_PROC_OUT *output)
192 av_log(priv->avctx, AV_LOG_VERBOSE, "\tYBuffSz: %u\n", output->YbuffSz);
193 av_log(priv->avctx, AV_LOG_VERBOSE, "\tYBuffDoneSz: %u\n",
194 output->YBuffDoneSz);
195 av_log(priv->avctx, AV_LOG_VERBOSE, "\tUVBuffDoneSz: %u\n",
196 output->UVBuffDoneSz);
197 av_log(priv->avctx, AV_LOG_VERBOSE, "\tTimestamp: %"PRIu64"\n",
198 output->PicInfo.timeStamp);
199 av_log(priv->avctx, AV_LOG_VERBOSE, "\tPicture Number: %u\n",
200 output->PicInfo.picture_number);
201 av_log(priv->avctx, AV_LOG_VERBOSE, "\tWidth: %u\n",
202 output->PicInfo.width);
203 av_log(priv->avctx, AV_LOG_VERBOSE, "\tHeight: %u\n",
204 output->PicInfo.height);
205 av_log(priv->avctx, AV_LOG_VERBOSE, "\tChroma: 0x%03x\n",
206 output->PicInfo.chroma_format);
207 av_log(priv->avctx, AV_LOG_VERBOSE, "\tPulldown: %u\n",
208 output->PicInfo.pulldown);
209 av_log(priv->avctx, AV_LOG_VERBOSE, "\tFlags: 0x%08x\n",
210 output->PicInfo.flags);
211 av_log(priv->avctx, AV_LOG_VERBOSE, "\tFrame Rate/Res: %u\n",
212 output->PicInfo.frame_rate);
213 av_log(priv->avctx, AV_LOG_VERBOSE, "\tAspect Ratio: %u\n",
214 output->PicInfo.aspect_ratio);
215 av_log(priv->avctx, AV_LOG_VERBOSE, "\tColor Primaries: %u\n",
216 output->PicInfo.colour_primaries);
217 av_log(priv->avctx, AV_LOG_VERBOSE, "\tMetaData: %u\n",
218 output->PicInfo.picture_meta_payload);
219 av_log(priv->avctx, AV_LOG_VERBOSE, "\tSession Number: %u\n",
220 output->PicInfo.sess_num);
221 av_log(priv->avctx, AV_LOG_VERBOSE, "\tycom: %u\n",
222 output->PicInfo.ycom);
223 av_log(priv->avctx, AV_LOG_VERBOSE, "\tCustom Aspect: %u\n",
224 output->PicInfo.custom_aspect_ratio_width_height);
225 av_log(priv->avctx, AV_LOG_VERBOSE, "\tFrames to Drop: %u\n",
226 output->PicInfo.n_drop);
227 av_log(priv->avctx, AV_LOG_VERBOSE, "\tH264 Valid Fields: 0x%08x\n",
228 output->PicInfo.other.h264.valid);
232 /*****************************************************************************
233 * OpaqueList functions
234 ****************************************************************************/
236 static uint64_t opaque_list_push(CHDContext *priv, uint64_t reordered_opaque,
239 OpaqueList *newNode = av_mallocz(sizeof (OpaqueList));
241 av_log(priv->avctx, AV_LOG_ERROR,
242 "Unable to allocate new node in OpaqueList.\n");
246 newNode->fake_timestamp = TIMESTAMP_UNIT;
247 priv->head = newNode;
249 newNode->fake_timestamp = priv->tail->fake_timestamp + TIMESTAMP_UNIT;
250 priv->tail->next = newNode;
252 priv->tail = newNode;
253 newNode->reordered_opaque = reordered_opaque;
254 newNode->pic_type = pic_type;
256 return newNode->fake_timestamp;
260 * The OpaqueList is built in decode order, while elements will be removed
261 * in presentation order. If frames are reordered, this means we must be
262 * able to remove elements that are not the first element.
264 * Returned node must be freed by caller.
266 static OpaqueList *opaque_list_pop(CHDContext *priv, uint64_t fake_timestamp)
268 OpaqueList *node = priv->head;
271 av_log(priv->avctx, AV_LOG_ERROR,
272 "CrystalHD: Attempted to query non-existent timestamps.\n");
277 * The first element is special-cased because we have to manipulate
278 * the head pointer rather than the previous element in the list.
280 if (priv->head->fake_timestamp == fake_timestamp) {
281 priv->head = node->next;
283 if (!priv->head->next)
284 priv->tail = priv->head;
291 * The list is processed at arm's length so that we have the
292 * previous element available to rewrite its next pointer.
295 OpaqueList *current = node->next;
296 if (current->fake_timestamp == fake_timestamp) {
297 node->next = current->next;
302 current->next = NULL;
309 av_log(priv->avctx, AV_LOG_VERBOSE,
310 "CrystalHD: Couldn't match fake_timestamp.\n");
315 /*****************************************************************************
316 * Video decoder API function definitions
317 ****************************************************************************/
319 static void flush(AVCodecContext *avctx)
321 CHDContext *priv = avctx->priv_data;
323 avctx->has_b_frames = 0;
324 priv->last_picture = -1;
325 priv->output_ready = 0;
326 priv->need_second_field = 0;
327 priv->skip_next_output = 0;
328 priv->decode_wait = BASE_WAIT;
330 av_frame_unref (priv->pic);
332 /* Flush mode 4 flushes all software and hardware buffers. */
333 DtsFlushInput(priv->dev, 4);
337 static av_cold int uninit(AVCodecContext *avctx)
339 CHDContext *priv = avctx->priv_data;
343 DtsStopDecoder(device);
344 DtsCloseDecoder(device);
345 DtsDeviceClose(device);
348 * Restore original extradata, so that if the decoder is
349 * reinitialised, the bitstream detection and filtering
350 * will work as expected.
352 if (priv->orig_extradata) {
353 av_free(avctx->extradata);
354 avctx->extradata = priv->orig_extradata;
355 avctx->extradata_size = priv->orig_extradata_size;
356 priv->orig_extradata = NULL;
357 priv->orig_extradata_size = 0;
360 av_parser_close(priv->parser);
362 av_bsf_free(&priv->bsfc);
365 av_freep(&priv->sps_pps_buf);
367 av_frame_free (&priv->pic);
370 OpaqueList *node = priv->head;
372 OpaqueList *next = node->next;
382 static av_cold int init(AVCodecContext *avctx)
386 BC_INFO_CRYSTAL version;
387 BC_INPUT_FORMAT format = {
390 .OptFlags = 0x80000000 | vdecFrameRate59_94 | 0x40,
391 .width = avctx->width,
392 .height = avctx->height,
395 BC_MEDIA_SUBTYPE subtype;
397 uint32_t mode = DTS_PLAYBACK_MODE |
398 DTS_LOAD_FILE_PLAY_FW |
399 DTS_SKIP_TX_CHK_CPB |
400 DTS_PLAYBACK_DROP_RPT_MODE |
401 DTS_SINGLE_THREADED_MODE |
402 DTS_DFLT_RESOLUTION(vdecRESOLUTION_1080p23_976);
404 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD Init for %s\n",
407 avctx->pix_fmt = AV_PIX_FMT_YUYV422;
409 /* Initialize the library */
410 priv = avctx->priv_data;
412 priv->is_nal = avctx->extradata_size > 0 && *(avctx->extradata) == 1;
413 priv->last_picture = -1;
414 priv->decode_wait = BASE_WAIT;
415 priv->pic = av_frame_alloc();
417 subtype = id2subtype(priv, avctx->codec->id);
419 case BC_MSUBTYPE_AVC1:
421 const AVBitStreamFilter *bsf;
424 bsf = av_bsf_get_by_name("h264_mp4toannexb");
426 av_log(avctx, AV_LOG_ERROR,
427 "Cannot open the h264_mp4toannexb BSF!\n");
428 return AVERROR_BSF_NOT_FOUND;
430 avret = av_bsf_alloc(bsf, &priv->bsfc);
432 return AVERROR(ENOMEM);
434 avret = avcodec_parameters_from_context(priv->bsfc->par_in, avctx);
436 return AVERROR(ENOMEM);
438 avret = av_bsf_init(priv->bsfc);
440 return AVERROR(ENOMEM);
443 format.metaDataSz = priv->bsfc->par_out->extradata_size;
444 format.pMetaData = av_malloc(format.metaDataSz + AV_INPUT_BUFFER_PADDING_SIZE);
445 if (!format.pMetaData) {
446 av_log(avctx, AV_LOG_ERROR,
447 "Failed to allocate copy of extradata\n");
448 return AVERROR(ENOMEM);
450 memcpy(format.pMetaData, priv->bsfc->par_out->extradata, format.metaDataSz);
452 /* Back up the extradata so it can be restored at close time. */
453 priv->orig_extradata = avctx->extradata;
454 priv->orig_extradata_size = avctx->extradata_size;
455 avctx->extradata = format.pMetaData;
456 avctx->extradata_size = format.metaDataSz;
458 subtype = BC_MSUBTYPE_H264;
459 format.startCodeSz = 4;
461 case BC_MSUBTYPE_H264:
462 format.startCodeSz = 4;
464 case BC_MSUBTYPE_VC1:
465 case BC_MSUBTYPE_WVC1:
466 case BC_MSUBTYPE_WMV3:
467 case BC_MSUBTYPE_WMVA:
468 case BC_MSUBTYPE_MPEG2VIDEO:
469 case BC_MSUBTYPE_DIVX:
470 case BC_MSUBTYPE_DIVX311:
471 format.pMetaData = avctx->extradata;
472 format.metaDataSz = avctx->extradata_size;
475 av_log(avctx, AV_LOG_ERROR, "CrystalHD: Unknown codec name\n");
476 return AVERROR(EINVAL);
478 format.mSubtype = subtype;
481 format.bEnableScaling = 1;
482 format.ScalingParams.sWidth = priv->sWidth;
485 /* Get a decoder instance */
486 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: starting up\n");
487 // Initialize the Link and Decoder devices
488 ret = DtsDeviceOpen(&priv->dev, mode);
489 if (ret != BC_STS_SUCCESS) {
490 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: DtsDeviceOpen failed\n");
494 ret = DtsCrystalHDVersion(priv->dev, &version);
495 if (ret != BC_STS_SUCCESS) {
496 av_log(avctx, AV_LOG_VERBOSE,
497 "CrystalHD: DtsCrystalHDVersion failed\n");
500 priv->is_70012 = version.device == 0;
502 if (priv->is_70012 &&
503 (subtype == BC_MSUBTYPE_DIVX || subtype == BC_MSUBTYPE_DIVX311)) {
504 av_log(avctx, AV_LOG_VERBOSE,
505 "CrystalHD: BCM70012 doesn't support MPEG4-ASP/DivX/Xvid\n");
509 ret = DtsSetInputFormat(priv->dev, &format);
510 if (ret != BC_STS_SUCCESS) {
511 av_log(avctx, AV_LOG_ERROR, "CrystalHD: SetInputFormat failed\n");
515 ret = DtsOpenDecoder(priv->dev, BC_STREAM_TYPE_ES);
516 if (ret != BC_STS_SUCCESS) {
517 av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsOpenDecoder failed\n");
521 ret = DtsSetColorSpace(priv->dev, OUTPUT_MODE422_YUY2);
522 if (ret != BC_STS_SUCCESS) {
523 av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsSetColorSpace failed\n");
526 ret = DtsStartDecoder(priv->dev);
527 if (ret != BC_STS_SUCCESS) {
528 av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartDecoder failed\n");
531 ret = DtsStartCapture(priv->dev);
532 if (ret != BC_STS_SUCCESS) {
533 av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartCapture failed\n");
537 if (avctx->codec->id == AV_CODEC_ID_H264) {
538 priv->parser = av_parser_init(avctx->codec->id);
540 av_log(avctx, AV_LOG_WARNING,
541 "Cannot open the h.264 parser! Interlaced h.264 content "
542 "will not be detected reliably.\n");
543 priv->parser->flags = PARSER_FLAG_COMPLETE_FRAMES;
545 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Init complete.\n");
555 static inline CopyRet copy_frame(AVCodecContext *avctx,
556 BC_DTS_PROC_OUT *output,
557 void *data, int *got_frame)
560 BC_DTS_STATUS decoder_status = { 0, };
561 uint8_t trust_interlaced;
564 CHDContext *priv = avctx->priv_data;
565 int64_t pkt_pts = AV_NOPTS_VALUE;
566 uint8_t pic_type = 0;
568 uint8_t bottom_field = (output->PicInfo.flags & VDEC_FLAG_BOTTOMFIELD) ==
569 VDEC_FLAG_BOTTOMFIELD;
570 uint8_t bottom_first = !!(output->PicInfo.flags & VDEC_FLAG_BOTTOM_FIRST);
572 int width = output->PicInfo.width;
573 int height = output->PicInfo.height;
575 uint8_t *src = output->Ybuff;
580 if (output->PicInfo.timeStamp != 0) {
581 OpaqueList *node = opaque_list_pop(priv, output->PicInfo.timeStamp);
583 pkt_pts = node->reordered_opaque;
584 pic_type = node->pic_type;
588 * We will encounter a situation where a timestamp cannot be
589 * popped if a second field is being returned. In this case,
590 * each field has the same timestamp and the first one will
591 * cause it to be popped. To keep subsequent calculations
592 * simple, pic_type should be set a FIELD value - doesn't
593 * matter which, but I chose BOTTOM.
595 pic_type = PICT_BOTTOM_FIELD;
597 av_log(avctx, AV_LOG_VERBOSE, "output \"pts\": %"PRIu64"\n",
598 output->PicInfo.timeStamp);
599 av_log(avctx, AV_LOG_VERBOSE, "output picture type %d\n",
603 ret = DtsGetDriverStatus(priv->dev, &decoder_status);
604 if (ret != BC_STS_SUCCESS) {
605 av_log(avctx, AV_LOG_ERROR,
606 "CrystalHD: GetDriverStatus failed: %u\n", ret);
611 * For most content, we can trust the interlaced flag returned
612 * by the hardware, but sometimes we can't. These are the
613 * conditions under which we can trust the flag:
615 * 1) It's not h.264 content
616 * 2) The UNKNOWN_SRC flag is not set
617 * 3) We know we're expecting a second field
618 * 4) The hardware reports this picture and the next picture
619 * have the same picture number.
621 * Note that there can still be interlaced content that will
622 * fail this check, if the hardware hasn't decoded the next
623 * picture or if there is a corruption in the stream. (In either
624 * case a 0 will be returned for the next picture number)
626 trust_interlaced = avctx->codec->id != AV_CODEC_ID_H264 ||
627 !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ||
628 priv->need_second_field ||
629 (decoder_status.picNumFlags & ~0x40000000) ==
630 output->PicInfo.picture_number;
633 * If we got a false negative for trust_interlaced on the first field,
634 * we will realise our mistake here when we see that the picture number is that
635 * of the previous picture. We cannot recover the frame and should discard the
636 * second field to keep the correct number of output frames.
638 if (output->PicInfo.picture_number == priv->last_picture && !priv->need_second_field) {
639 av_log(avctx, AV_LOG_WARNING,
640 "Incorrectly guessed progressive frame. Discarding second field\n");
641 /* Returning without providing a picture. */
645 interlaced = (output->PicInfo.flags & VDEC_FLAG_INTERLACED_SRC) &&
648 if (!trust_interlaced && (decoder_status.picNumFlags & ~0x40000000) == 0) {
649 av_log(avctx, AV_LOG_VERBOSE,
650 "Next picture number unknown. Assuming progressive frame.\n");
653 av_log(avctx, AV_LOG_VERBOSE, "Interlaced state: %d | trust_interlaced %d\n",
654 interlaced, trust_interlaced);
656 if (priv->pic->data[0] && !priv->need_second_field)
657 av_frame_unref(priv->pic);
659 priv->need_second_field = interlaced && !priv->need_second_field;
661 if (!priv->pic->data[0]) {
662 if (ff_get_buffer(avctx, priv->pic, AV_GET_BUFFER_FLAG_REF) < 0)
666 bwidth = av_image_get_linesize(avctx->pix_fmt, width, 0);
667 if (priv->is_70012) {
672 else if (width <= 1280)
675 sStride = av_image_get_linesize(avctx->pix_fmt, pStride, 0);
680 dStride = priv->pic->linesize[0];
681 dst = priv->pic->data[0];
683 av_log(priv->avctx, AV_LOG_VERBOSE, "CrystalHD: Copying out frame\n");
691 av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: bottom field\n");
694 av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: top field\n");
698 for (sY = 0; sY < height; dY++, sY++) {
699 memcpy(&(dst[dY * dStride]), &(src[sY * sStride]), bwidth);
703 av_image_copy_plane(dst, dStride, src, sStride, bwidth, height);
706 priv->pic->interlaced_frame = interlaced;
708 priv->pic->top_field_first = !bottom_first;
710 priv->pic->pts = pkt_pts;
712 FF_DISABLE_DEPRECATION_WARNINGS
713 priv->pic->pkt_pts = pkt_pts;
714 FF_ENABLE_DEPRECATION_WARNINGS
717 if (!priv->need_second_field) {
719 if ((ret = av_frame_ref(data, priv->pic)) < 0) {
725 * Two types of PAFF content have been observed. One form causes the
726 * hardware to return a field pair and the other individual fields,
727 * even though the input is always individual fields. We must skip
728 * copying on the next decode() call to maintain pipeline length in
731 if (!interlaced && (output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) &&
732 (pic_type == PICT_TOP_FIELD || pic_type == PICT_BOTTOM_FIELD)) {
733 av_log(priv->avctx, AV_LOG_VERBOSE, "Fieldpair from two packets.\n");
734 return RET_SKIP_NEXT_COPY;
738 * The logic here is purely based on empirical testing with samples.
739 * If we need a second field, it could come from a second input packet,
740 * or it could come from the same field-pair input packet at the current
741 * field. In the first case, we should return and wait for the next time
742 * round to get the second field, while in the second case, we should
743 * ask the decoder for it immediately.
745 * Testing has shown that we are dealing with the fieldpair -> two fields
746 * case if the VDEC_FLAG_UNKNOWN_SRC is not set or if the input picture
747 * type was PICT_FRAME (in this second case, the flag might still be set)
749 return priv->need_second_field &&
750 (!(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ||
751 pic_type == PICT_FRAME) ?
752 RET_COPY_NEXT_FIELD : RET_OK;
756 static inline CopyRet receive_frame(AVCodecContext *avctx,
757 void *data, int *got_frame)
760 BC_DTS_PROC_OUT output = {
761 .PicInfo.width = avctx->width,
762 .PicInfo.height = avctx->height,
764 CHDContext *priv = avctx->priv_data;
765 HANDLE dev = priv->dev;
769 // Request decoded data from the driver
770 ret = DtsProcOutputNoCopy(dev, OUTPUT_PROC_TIMEOUT, &output);
771 if (ret == BC_STS_FMT_CHANGE) {
772 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Initial format change\n");
773 avctx->width = output.PicInfo.width;
774 avctx->height = output.PicInfo.height;
775 switch ( output.PicInfo.aspect_ratio ) {
776 case vdecAspectRatioSquare:
777 avctx->sample_aspect_ratio = (AVRational) { 1, 1};
779 case vdecAspectRatio12_11:
780 avctx->sample_aspect_ratio = (AVRational) { 12, 11};
782 case vdecAspectRatio10_11:
783 avctx->sample_aspect_ratio = (AVRational) { 10, 11};
785 case vdecAspectRatio16_11:
786 avctx->sample_aspect_ratio = (AVRational) { 16, 11};
788 case vdecAspectRatio40_33:
789 avctx->sample_aspect_ratio = (AVRational) { 40, 33};
791 case vdecAspectRatio24_11:
792 avctx->sample_aspect_ratio = (AVRational) { 24, 11};
794 case vdecAspectRatio20_11:
795 avctx->sample_aspect_ratio = (AVRational) { 20, 11};
797 case vdecAspectRatio32_11:
798 avctx->sample_aspect_ratio = (AVRational) { 32, 11};
800 case vdecAspectRatio80_33:
801 avctx->sample_aspect_ratio = (AVRational) { 80, 33};
803 case vdecAspectRatio18_11:
804 avctx->sample_aspect_ratio = (AVRational) { 18, 11};
806 case vdecAspectRatio15_11:
807 avctx->sample_aspect_ratio = (AVRational) { 15, 11};
809 case vdecAspectRatio64_33:
810 avctx->sample_aspect_ratio = (AVRational) { 64, 33};
812 case vdecAspectRatio160_99:
813 avctx->sample_aspect_ratio = (AVRational) {160, 99};
815 case vdecAspectRatio4_3:
816 avctx->sample_aspect_ratio = (AVRational) { 4, 3};
818 case vdecAspectRatio16_9:
819 avctx->sample_aspect_ratio = (AVRational) { 16, 9};
821 case vdecAspectRatio221_1:
822 avctx->sample_aspect_ratio = (AVRational) {221, 1};
825 return RET_COPY_AGAIN;
826 } else if (ret == BC_STS_SUCCESS) {
828 if (output.PoutFlags & BC_POUT_FLAGS_PIB_VALID) {
829 if (priv->last_picture == -1) {
831 * Init to one less, so that the incrementing code doesn't
832 * need to be special-cased.
834 priv->last_picture = output.PicInfo.picture_number - 1;
837 if (avctx->codec->id == AV_CODEC_ID_MPEG4 &&
838 output.PicInfo.timeStamp == 0 && priv->bframe_bug) {
839 av_log(avctx, AV_LOG_VERBOSE,
840 "CrystalHD: Not returning packed frame twice.\n");
841 priv->last_picture++;
842 DtsReleaseOutputBuffs(dev, NULL, FALSE);
843 return RET_COPY_AGAIN;
846 print_frame_info(priv, &output);
848 if (priv->last_picture + 1 < output.PicInfo.picture_number) {
849 av_log(avctx, AV_LOG_WARNING,
850 "CrystalHD: Picture Number discontinuity\n");
852 * Have we lost frames? If so, we need to shrink the
853 * pipeline length appropriately.
855 * XXX: I have no idea what the semantics of this situation
856 * are so I don't even know if we've lost frames or which
859 * In any case, only warn the first time.
861 priv->last_picture = output.PicInfo.picture_number - 1;
864 copy_ret = copy_frame(avctx, &output, data, got_frame);
865 if (*got_frame > 0) {
866 avctx->has_b_frames--;
867 priv->last_picture++;
868 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Pipeline length: %u\n",
869 avctx->has_b_frames);
873 * An invalid frame has been consumed.
875 av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput succeeded with "
877 avctx->has_b_frames--;
880 DtsReleaseOutputBuffs(dev, NULL, FALSE);
883 } else if (ret == BC_STS_BUSY) {
884 return RET_COPY_AGAIN;
886 av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput failed %d\n", ret);
892 static int decode(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt)
895 BC_DTS_STATUS decoder_status = { 0, };
897 CHDContext *priv = avctx->priv_data;
898 HANDLE dev = priv->dev;
899 uint8_t *in_data = avpkt->data;
900 int len = avpkt->size;
902 uint8_t pic_type = 0;
904 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: decode_frame\n");
906 if (avpkt->size == 7 && !priv->bframe_bug) {
908 * The use of a drop frame triggers the bug
910 av_log(avctx, AV_LOG_INFO,
911 "CrystalHD: Enabling work-around for packed b-frame bug\n");
912 priv->bframe_bug = 1;
913 } else if (avpkt->size == 8 && priv->bframe_bug) {
915 * Delay frames don't trigger the bug
917 av_log(avctx, AV_LOG_INFO,
918 "CrystalHD: Disabling work-around for packed b-frame bug\n");
919 priv->bframe_bug = 0;
923 int32_t tx_free = (int32_t)DtsTxFreeSize(dev);
927 AVPacket filter_packet = { 0 };
928 AVPacket filtered_packet = { 0 };
930 ret = av_packet_ref(&filter_packet, avpkt);
932 av_log(avctx, AV_LOG_ERROR, "CrystalHD: mpv4toannexb filter "
933 "failed to ref input packet\n");
937 ret = av_bsf_send_packet(priv->bsfc, &filter_packet);
939 av_log(avctx, AV_LOG_ERROR, "CrystalHD: mpv4toannexb filter "
940 "failed to send input packet\n");
944 ret = av_bsf_receive_packet(priv->bsfc, &filtered_packet);
946 av_log(avctx, AV_LOG_ERROR, "CrystalHD: mpv4toannexb filter "
947 "failed to receive output packet\n");
951 in_data = filtered_packet.data;
952 len = filtered_packet.size;
954 av_packet_unref(&filter_packet);
966 H264Context *h = priv->parser->priv_data;
968 index = av_parser_parse2(priv->parser, avctx, &pout, &psize,
969 in_data, len, avctx->internal->pkt->pts,
970 avctx->internal->pkt->dts, 0);
972 av_log(avctx, AV_LOG_WARNING,
973 "CrystalHD: Failed to parse h.264 packet to "
974 "detect interlacing.\n");
975 } else if (index != len) {
976 av_log(avctx, AV_LOG_WARNING,
977 "CrystalHD: Failed to parse h.264 packet "
978 "completely. Interlaced frames may be "
979 "incorrectly detected.\n");
981 av_log(avctx, AV_LOG_VERBOSE,
982 "CrystalHD: parser picture type %d\n",
983 h->picture_structure);
984 pic_type = h->picture_structure;
987 av_log(avctx, AV_LOG_WARNING,
988 "CrystalHD: mp4toannexb filter failed to filter "
989 "packet. Interlaced frames may be incorrectly "
994 if (len < tx_free - 1024) {
996 * Despite being notionally opaque, either libcrystalhd or
997 * the hardware itself will mangle pts values that are too
998 * small or too large. The docs claim it should be in units
999 * of 100ns. Given that we're nominally dealing with a black
1000 * box on both sides, any transform we do has no guarantee of
1001 * avoiding mangling so we need to build a mapping to values
1002 * we know will not be mangled.
1004 uint64_t pts = opaque_list_push(priv, avctx->internal->pkt->pts, pic_type);
1009 return AVERROR(ENOMEM);
1011 av_log(priv->avctx, AV_LOG_VERBOSE,
1012 "input \"pts\": %"PRIu64"\n", pts);
1013 ret = DtsProcInput(dev, in_data, len, pts, 0);
1017 if (ret == BC_STS_BUSY) {
1018 av_log(avctx, AV_LOG_WARNING,
1019 "CrystalHD: ProcInput returned busy\n");
1021 return AVERROR(EBUSY);
1022 } else if (ret != BC_STS_SUCCESS) {
1023 av_log(avctx, AV_LOG_ERROR,
1024 "CrystalHD: ProcInput failed: %u\n", ret);
1027 avctx->has_b_frames++;
1029 av_log(avctx, AV_LOG_WARNING, "CrystalHD: Input buffer full\n");
1030 len = 0; // We didn't consume any bytes.
1033 av_log(avctx, AV_LOG_INFO, "CrystalHD: No more input data\n");
1036 if (priv->skip_next_output) {
1037 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Skipping next output.\n");
1038 priv->skip_next_output = 0;
1039 avctx->has_b_frames--;
1043 ret = DtsGetDriverStatus(dev, &decoder_status);
1044 if (ret != BC_STS_SUCCESS) {
1045 av_log(avctx, AV_LOG_ERROR, "CrystalHD: GetDriverStatus failed\n");
1050 * No frames ready. Don't try to extract.
1052 * Empirical testing shows that ReadyListCount can be a damn lie,
1053 * and ProcOut still fails when count > 0. The same testing showed
1054 * that two more iterations were needed before ProcOutput would
1057 if (priv->output_ready < 2) {
1058 if (decoder_status.ReadyListCount != 0)
1059 priv->output_ready++;
1061 av_log(avctx, AV_LOG_INFO, "CrystalHD: Filling pipeline.\n");
1063 } else if (decoder_status.ReadyListCount == 0) {
1065 * After the pipeline is established, if we encounter a lack of frames
1066 * that probably means we're not giving the hardware enough time to
1067 * decode them, so start increasing the wait time at the end of a
1071 priv->decode_wait += WAIT_UNIT;
1072 av_log(avctx, AV_LOG_INFO, "CrystalHD: No frames ready. Returning\n");
1077 rec_ret = receive_frame(avctx, data, got_frame);
1078 if (rec_ret == RET_OK && *got_frame == 0) {
1080 * This case is for when the encoded fields are stored
1081 * separately and we get a separate avpkt for each one. To keep
1082 * the pipeline stable, we should return nothing and wait for
1083 * the next time round to grab the second field.
1084 * H.264 PAFF is an example of this.
1086 av_log(avctx, AV_LOG_VERBOSE, "Returning after first field.\n");
1087 avctx->has_b_frames--;
1088 } else if (rec_ret == RET_COPY_NEXT_FIELD) {
1090 * This case is for when the encoded fields are stored in a
1091 * single avpkt but the hardware returns then separately. Unless
1092 * we grab the second field before returning, we'll slip another
1093 * frame in the pipeline and if that happens a lot, we're sunk.
1094 * So we have to get that second field now.
1095 * Interlaced mpeg2 and vc1 are examples of this.
1097 av_log(avctx, AV_LOG_VERBOSE, "Trying to get second field.\n");
1099 usleep(priv->decode_wait);
1100 ret = DtsGetDriverStatus(dev, &decoder_status);
1101 if (ret == BC_STS_SUCCESS &&
1102 decoder_status.ReadyListCount > 0) {
1103 rec_ret = receive_frame(avctx, data, got_frame);
1104 if ((rec_ret == RET_OK && *got_frame > 0) ||
1105 rec_ret == RET_ERROR)
1109 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Got second field.\n");
1110 } else if (rec_ret == RET_SKIP_NEXT_COPY) {
1112 * Two input packets got turned into a field pair. Gawd.
1114 av_log(avctx, AV_LOG_VERBOSE,
1115 "Don't output on next decode call.\n");
1116 priv->skip_next_output = 1;
1119 * If rec_ret == RET_COPY_AGAIN, that means that either we just handled
1120 * a FMT_CHANGE event and need to go around again for the actual frame,
1121 * we got a busy status and need to try again, or we're dealing with
1122 * packed b-frames, where the hardware strangely returns the packed
1123 * p-frame twice. We choose to keep the second copy as it carries the
1126 } while (rec_ret == RET_COPY_AGAIN);
1127 usleep(priv->decode_wait);
1132 #if CONFIG_H264_CRYSTALHD_DECODER
1133 static AVClass h264_class = {
1135 av_default_item_name,
1137 LIBAVUTIL_VERSION_INT,
1140 AVCodec ff_h264_crystalhd_decoder = {
1141 .name = "h264_crystalhd",
1142 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (CrystalHD acceleration)"),
1143 .type = AVMEDIA_TYPE_VIDEO,
1144 .id = AV_CODEC_ID_H264,
1145 .priv_data_size = sizeof(CHDContext),
1149 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY,
1151 .pix_fmts = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
1152 .priv_class = &h264_class,
1156 #if CONFIG_MPEG2_CRYSTALHD_DECODER
1157 static AVClass mpeg2_class = {
1159 av_default_item_name,
1161 LIBAVUTIL_VERSION_INT,
1164 AVCodec ff_mpeg2_crystalhd_decoder = {
1165 .name = "mpeg2_crystalhd",
1166 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 Video (CrystalHD acceleration)"),
1167 .type = AVMEDIA_TYPE_VIDEO,
1168 .id = AV_CODEC_ID_MPEG2VIDEO,
1169 .priv_data_size = sizeof(CHDContext),
1173 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY,
1175 .pix_fmts = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
1176 .priv_class = &mpeg2_class,
1180 #if CONFIG_MPEG4_CRYSTALHD_DECODER
1181 static AVClass mpeg4_class = {
1183 av_default_item_name,
1185 LIBAVUTIL_VERSION_INT,
1188 AVCodec ff_mpeg4_crystalhd_decoder = {
1189 .name = "mpeg4_crystalhd",
1190 .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 (CrystalHD acceleration)"),
1191 .type = AVMEDIA_TYPE_VIDEO,
1192 .id = AV_CODEC_ID_MPEG4,
1193 .priv_data_size = sizeof(CHDContext),
1197 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY,
1199 .pix_fmts = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
1200 .priv_class = &mpeg4_class,
1204 #if CONFIG_MSMPEG4_CRYSTALHD_DECODER
1205 static AVClass msmpeg4_class = {
1206 "msmpeg4_crystalhd",
1207 av_default_item_name,
1209 LIBAVUTIL_VERSION_INT,
1212 AVCodec ff_msmpeg4_crystalhd_decoder = {
1213 .name = "msmpeg4_crystalhd",
1214 .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 Microsoft variant version 3 (CrystalHD acceleration)"),
1215 .type = AVMEDIA_TYPE_VIDEO,
1216 .id = AV_CODEC_ID_MSMPEG4V3,
1217 .priv_data_size = sizeof(CHDContext),
1221 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_EXPERIMENTAL,
1223 .pix_fmts = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
1224 .priv_class = &msmpeg4_class,
1228 #if CONFIG_VC1_CRYSTALHD_DECODER
1229 static AVClass vc1_class = {
1231 av_default_item_name,
1233 LIBAVUTIL_VERSION_INT,
1236 AVCodec ff_vc1_crystalhd_decoder = {
1237 .name = "vc1_crystalhd",
1238 .long_name = NULL_IF_CONFIG_SMALL("SMPTE VC-1 (CrystalHD acceleration)"),
1239 .type = AVMEDIA_TYPE_VIDEO,
1240 .id = AV_CODEC_ID_VC1,
1241 .priv_data_size = sizeof(CHDContext),
1245 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY,
1247 .pix_fmts = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
1248 .priv_class = &vc1_class,
1252 #if CONFIG_WMV3_CRYSTALHD_DECODER
1253 static AVClass wmv3_class = {
1255 av_default_item_name,
1257 LIBAVUTIL_VERSION_INT,
1260 AVCodec ff_wmv3_crystalhd_decoder = {
1261 .name = "wmv3_crystalhd",
1262 .long_name = NULL_IF_CONFIG_SMALL("Windows Media Video 9 (CrystalHD acceleration)"),
1263 .type = AVMEDIA_TYPE_VIDEO,
1264 .id = AV_CODEC_ID_WMV3,
1265 .priv_data_size = sizeof(CHDContext),
1269 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY,
1271 .pix_fmts = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE},
1272 .priv_class = &wmv3_class,