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 AVCodecParserContext *parser;
130 uint8_t *sps_pps_buf;
131 uint32_t sps_pps_size;
133 uint8_t output_ready;
134 uint8_t need_second_field;
135 uint8_t skip_next_output;
136 uint64_t decode_wait;
138 uint64_t last_picture;
148 static const AVOption options[] = {
149 { "crystalhd_downscale_width",
150 "Turn on downscaling to the specified width",
151 offsetof(CHDContext, sWidth),
152 FF_OPT_TYPE_INT, 0, 0, UINT32_MAX,
153 AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM, },
158 /*****************************************************************************
160 ****************************************************************************/
162 static inline BC_MEDIA_SUBTYPE id2subtype(CHDContext *priv, enum CodecID id)
166 return BC_MSUBTYPE_DIVX;
167 case CODEC_ID_MSMPEG4V3:
168 return BC_MSUBTYPE_DIVX311;
169 case CODEC_ID_MPEG2VIDEO:
170 return BC_MSUBTYPE_MPEG2VIDEO;
172 return BC_MSUBTYPE_VC1;
174 return BC_MSUBTYPE_WMV3;
176 return priv->is_nal ? BC_MSUBTYPE_AVC1 : BC_MSUBTYPE_H264;
178 return BC_MSUBTYPE_INVALID;
182 static inline void print_frame_info(CHDContext *priv, BC_DTS_PROC_OUT *output)
184 av_log(priv->avctx, AV_LOG_VERBOSE, "\tYBuffSz: %u\n", output->YbuffSz);
185 av_log(priv->avctx, AV_LOG_VERBOSE, "\tYBuffDoneSz: %u\n",
186 output->YBuffDoneSz);
187 av_log(priv->avctx, AV_LOG_VERBOSE, "\tUVBuffDoneSz: %u\n",
188 output->UVBuffDoneSz);
189 av_log(priv->avctx, AV_LOG_VERBOSE, "\tTimestamp: %"PRIu64"\n",
190 output->PicInfo.timeStamp);
191 av_log(priv->avctx, AV_LOG_VERBOSE, "\tPicture Number: %u\n",
192 output->PicInfo.picture_number);
193 av_log(priv->avctx, AV_LOG_VERBOSE, "\tWidth: %u\n",
194 output->PicInfo.width);
195 av_log(priv->avctx, AV_LOG_VERBOSE, "\tHeight: %u\n",
196 output->PicInfo.height);
197 av_log(priv->avctx, AV_LOG_VERBOSE, "\tChroma: 0x%03x\n",
198 output->PicInfo.chroma_format);
199 av_log(priv->avctx, AV_LOG_VERBOSE, "\tPulldown: %u\n",
200 output->PicInfo.pulldown);
201 av_log(priv->avctx, AV_LOG_VERBOSE, "\tFlags: 0x%08x\n",
202 output->PicInfo.flags);
203 av_log(priv->avctx, AV_LOG_VERBOSE, "\tFrame Rate/Res: %u\n",
204 output->PicInfo.frame_rate);
205 av_log(priv->avctx, AV_LOG_VERBOSE, "\tAspect Ratio: %u\n",
206 output->PicInfo.aspect_ratio);
207 av_log(priv->avctx, AV_LOG_VERBOSE, "\tColor Primaries: %u\n",
208 output->PicInfo.colour_primaries);
209 av_log(priv->avctx, AV_LOG_VERBOSE, "\tMetaData: %u\n",
210 output->PicInfo.picture_meta_payload);
211 av_log(priv->avctx, AV_LOG_VERBOSE, "\tSession Number: %u\n",
212 output->PicInfo.sess_num);
213 av_log(priv->avctx, AV_LOG_VERBOSE, "\tycom: %u\n",
214 output->PicInfo.ycom);
215 av_log(priv->avctx, AV_LOG_VERBOSE, "\tCustom Aspect: %u\n",
216 output->PicInfo.custom_aspect_ratio_width_height);
217 av_log(priv->avctx, AV_LOG_VERBOSE, "\tFrames to Drop: %u\n",
218 output->PicInfo.n_drop);
219 av_log(priv->avctx, AV_LOG_VERBOSE, "\tH264 Valid Fields: 0x%08x\n",
220 output->PicInfo.other.h264.valid);
224 /*****************************************************************************
225 * OpaqueList functions
226 ****************************************************************************/
228 static uint64_t opaque_list_push(CHDContext *priv, uint64_t reordered_opaque,
231 OpaqueList *newNode = av_mallocz(sizeof (OpaqueList));
233 av_log(priv->avctx, AV_LOG_ERROR,
234 "Unable to allocate new node in OpaqueList.\n");
238 newNode->fake_timestamp = TIMESTAMP_UNIT;
239 priv->head = newNode;
241 newNode->fake_timestamp = priv->tail->fake_timestamp + TIMESTAMP_UNIT;
242 priv->tail->next = newNode;
244 priv->tail = newNode;
245 newNode->reordered_opaque = reordered_opaque;
246 newNode->pic_type = pic_type;
248 return newNode->fake_timestamp;
252 * The OpaqueList is built in decode order, while elements will be removed
253 * in presentation order. If frames are reordered, this means we must be
254 * able to remove elements that are not the first element.
256 * Returned node must be freed by caller.
258 static OpaqueList *opaque_list_pop(CHDContext *priv, uint64_t fake_timestamp)
260 OpaqueList *node = priv->head;
263 av_log(priv->avctx, AV_LOG_ERROR,
264 "CrystalHD: Attempted to query non-existent timestamps.\n");
269 * The first element is special-cased because we have to manipulate
270 * the head pointer rather than the previous element in the list.
272 if (priv->head->fake_timestamp == fake_timestamp) {
273 priv->head = node->next;
275 if (!priv->head->next)
276 priv->tail = priv->head;
283 * The list is processed at arm's length so that we have the
284 * previous element available to rewrite its next pointer.
287 OpaqueList *current = node->next;
288 if (current->fake_timestamp == fake_timestamp) {
289 node->next = current->next;
294 current->next = NULL;
301 av_log(priv->avctx, AV_LOG_VERBOSE,
302 "CrystalHD: Couldn't match fake_timestamp.\n");
307 /*****************************************************************************
308 * Video decoder API function definitions
309 ****************************************************************************/
311 static void flush(AVCodecContext *avctx)
313 CHDContext *priv = avctx->priv_data;
315 avctx->has_b_frames = 0;
316 priv->last_picture = -1;
317 priv->output_ready = 0;
318 priv->need_second_field = 0;
319 priv->skip_next_output = 0;
320 priv->decode_wait = BASE_WAIT;
322 if (priv->pic.data[0])
323 avctx->release_buffer(avctx, &priv->pic);
325 /* Flush mode 4 flushes all software and hardware buffers. */
326 DtsFlushInput(priv->dev, 4);
330 static av_cold int uninit(AVCodecContext *avctx)
332 CHDContext *priv = avctx->priv_data;
336 DtsStopDecoder(device);
337 DtsCloseDecoder(device);
338 DtsDeviceClose(device);
340 av_parser_close(priv->parser);
342 av_free(priv->sps_pps_buf);
344 if (priv->pic.data[0])
345 avctx->release_buffer(avctx, &priv->pic);
348 OpaqueList *node = priv->head;
350 OpaqueList *next = node->next;
360 static av_cold int init(AVCodecContext *avctx)
364 BC_INFO_CRYSTAL version;
365 BC_INPUT_FORMAT format = {
368 .OptFlags = 0x80000000 | vdecFrameRate59_94 | 0x40,
369 .width = avctx->width,
370 .height = avctx->height,
373 BC_MEDIA_SUBTYPE subtype;
375 uint32_t mode = DTS_PLAYBACK_MODE |
376 DTS_LOAD_FILE_PLAY_FW |
377 DTS_SKIP_TX_CHK_CPB |
378 DTS_PLAYBACK_DROP_RPT_MODE |
379 DTS_SINGLE_THREADED_MODE |
380 DTS_DFLT_RESOLUTION(vdecRESOLUTION_1080p23_976);
382 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD Init for %s\n",
385 avctx->pix_fmt = PIX_FMT_YUYV422;
387 /* Initialize the library */
388 priv = avctx->priv_data;
390 priv->is_nal = avctx->extradata_size > 0 && *(avctx->extradata) == 1;
391 priv->last_picture = -1;
392 priv->decode_wait = BASE_WAIT;
394 subtype = id2subtype(priv, avctx->codec->id);
396 case BC_MSUBTYPE_AVC1:
400 AVBitStreamFilterContext *bsfc;
402 uint32_t orig_data_size = avctx->extradata_size;
403 uint8_t *orig_data = av_malloc(orig_data_size);
405 av_log(avctx, AV_LOG_ERROR,
406 "Failed to allocate copy of extradata\n");
407 return AVERROR(ENOMEM);
409 memcpy(orig_data, avctx->extradata, orig_data_size);
412 bsfc = av_bitstream_filter_init("h264_mp4toannexb");
414 av_log(avctx, AV_LOG_ERROR,
415 "Cannot open the h264_mp4toannexb BSF!\n");
417 return AVERROR_BSF_NOT_FOUND;
419 av_bitstream_filter_filter(bsfc, avctx, NULL, &dummy_p,
420 &dummy_int, NULL, 0, 0);
421 av_bitstream_filter_close(bsfc);
423 priv->sps_pps_buf = avctx->extradata;
424 priv->sps_pps_size = avctx->extradata_size;
425 avctx->extradata = orig_data;
426 avctx->extradata_size = orig_data_size;
428 format.pMetaData = priv->sps_pps_buf;
429 format.metaDataSz = priv->sps_pps_size;
430 format.startCodeSz = (avctx->extradata[4] & 0x03) + 1;
433 case BC_MSUBTYPE_H264:
434 format.startCodeSz = 4;
436 case BC_MSUBTYPE_VC1:
437 case BC_MSUBTYPE_WVC1:
438 case BC_MSUBTYPE_WMV3:
439 case BC_MSUBTYPE_WMVA:
440 case BC_MSUBTYPE_MPEG2VIDEO:
441 case BC_MSUBTYPE_DIVX:
442 case BC_MSUBTYPE_DIVX311:
443 format.pMetaData = avctx->extradata;
444 format.metaDataSz = avctx->extradata_size;
447 av_log(avctx, AV_LOG_ERROR, "CrystalHD: Unknown codec name\n");
448 return AVERROR(EINVAL);
450 format.mSubtype = subtype;
453 format.bEnableScaling = 1;
454 format.ScalingParams.sWidth = priv->sWidth;
457 /* Get a decoder instance */
458 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: starting up\n");
459 // Initialize the Link and Decoder devices
460 ret = DtsDeviceOpen(&priv->dev, mode);
461 if (ret != BC_STS_SUCCESS) {
462 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: DtsDeviceOpen failed\n");
466 ret = DtsCrystalHDVersion(priv->dev, &version);
467 if (ret != BC_STS_SUCCESS) {
468 av_log(avctx, AV_LOG_VERBOSE,
469 "CrystalHD: DtsCrystalHDVersion failed\n");
472 priv->is_70012 = version.device == 0;
474 if (priv->is_70012 &&
475 (subtype == BC_MSUBTYPE_DIVX || subtype == BC_MSUBTYPE_DIVX311)) {
476 av_log(avctx, AV_LOG_VERBOSE,
477 "CrystalHD: BCM70012 doesn't support MPEG4-ASP/DivX/Xvid\n");
481 ret = DtsSetInputFormat(priv->dev, &format);
482 if (ret != BC_STS_SUCCESS) {
483 av_log(avctx, AV_LOG_ERROR, "CrystalHD: SetInputFormat failed\n");
487 ret = DtsOpenDecoder(priv->dev, BC_STREAM_TYPE_ES);
488 if (ret != BC_STS_SUCCESS) {
489 av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsOpenDecoder failed\n");
493 ret = DtsSetColorSpace(priv->dev, OUTPUT_MODE422_YUY2);
494 if (ret != BC_STS_SUCCESS) {
495 av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsSetColorSpace failed\n");
498 ret = DtsStartDecoder(priv->dev);
499 if (ret != BC_STS_SUCCESS) {
500 av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartDecoder failed\n");
503 ret = DtsStartCapture(priv->dev);
504 if (ret != BC_STS_SUCCESS) {
505 av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartCapture failed\n");
509 if (avctx->codec->id == CODEC_ID_H264) {
510 priv->parser = av_parser_init(avctx->codec->id);
512 av_log(avctx, AV_LOG_WARNING,
513 "Cannot open the h.264 parser! Interlaced h.264 content "
514 "will not be detected reliably.\n");
516 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Init complete.\n");
526 static inline CopyRet copy_frame(AVCodecContext *avctx,
527 BC_DTS_PROC_OUT *output,
528 void *data, int *data_size)
531 BC_DTS_STATUS decoder_status;
532 uint8_t trust_interlaced;
535 CHDContext *priv = avctx->priv_data;
536 int64_t pkt_pts = AV_NOPTS_VALUE;
537 uint8_t pic_type = 0;
539 uint8_t bottom_field = (output->PicInfo.flags & VDEC_FLAG_BOTTOMFIELD) ==
540 VDEC_FLAG_BOTTOMFIELD;
541 uint8_t bottom_first = !!(output->PicInfo.flags & VDEC_FLAG_BOTTOM_FIRST);
543 int width = output->PicInfo.width;
544 int height = output->PicInfo.height;
546 uint8_t *src = output->Ybuff;
551 if (output->PicInfo.timeStamp != 0) {
552 OpaqueList *node = opaque_list_pop(priv, output->PicInfo.timeStamp);
554 pkt_pts = node->reordered_opaque;
555 pic_type = node->pic_type;
559 * We will encounter a situation where a timestamp cannot be
560 * popped if a second field is being returned. In this case,
561 * each field has the same timestamp and the first one will
562 * cause it to be popped. To keep subsequent calculations
563 * simple, pic_type should be set a FIELD value - doesn't
564 * matter which, but I chose BOTTOM.
566 pic_type = PICT_BOTTOM_FIELD;
568 av_log(avctx, AV_LOG_VERBOSE, "output \"pts\": %"PRIu64"\n",
569 output->PicInfo.timeStamp);
570 av_log(avctx, AV_LOG_VERBOSE, "output picture type %d\n",
574 ret = DtsGetDriverStatus(priv->dev, &decoder_status);
575 if (ret != BC_STS_SUCCESS) {
576 av_log(avctx, AV_LOG_ERROR,
577 "CrystalHD: GetDriverStatus failed: %u\n", ret);
582 * For most content, we can trust the interlaced flag returned
583 * by the hardware, but sometimes we can't. These are the
584 * conditions under which we can trust the flag:
586 * 1) It's not h.264 content
587 * 2) The UNKNOWN_SRC flag is not set
588 * 3) We know we're expecting a second field
589 * 4) The hardware reports this picture and the next picture
590 * have the same picture number.
592 * Note that there can still be interlaced content that will
593 * fail this check, if the hardware hasn't decoded the next
594 * picture or if there is a corruption in the stream. (In either
595 * case a 0 will be returned for the next picture number)
597 trust_interlaced = avctx->codec->id != CODEC_ID_H264 ||
598 !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ||
599 priv->need_second_field ||
600 (decoder_status.picNumFlags & ~0x40000000) ==
601 output->PicInfo.picture_number;
604 * If we got a false negative for trust_interlaced on the first field,
605 * we will realise our mistake here when we see that the picture number is that
606 * of the previous picture. We cannot recover the frame and should discard the
607 * second field to keep the correct number of output frames.
609 if (output->PicInfo.picture_number == priv->last_picture && !priv->need_second_field) {
610 av_log(avctx, AV_LOG_WARNING,
611 "Incorrectly guessed progressive frame. Discarding second field\n");
612 /* Returning without providing a picture. */
616 interlaced = (output->PicInfo.flags & VDEC_FLAG_INTERLACED_SRC) &&
619 if (!trust_interlaced && (decoder_status.picNumFlags & ~0x40000000) == 0) {
620 av_log(avctx, AV_LOG_VERBOSE,
621 "Next picture number unknown. Assuming progressive frame.\n");
624 av_log(avctx, AV_LOG_VERBOSE, "Interlaced state: %d | trust_interlaced %d\n",
625 interlaced, trust_interlaced);
627 if (priv->pic.data[0] && !priv->need_second_field)
628 avctx->release_buffer(avctx, &priv->pic);
630 priv->need_second_field = interlaced && !priv->need_second_field;
632 priv->pic.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE |
633 FF_BUFFER_HINTS_REUSABLE;
634 if (!priv->pic.data[0]) {
635 if (avctx->get_buffer(avctx, &priv->pic) < 0) {
636 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
641 bwidth = av_image_get_linesize(avctx->pix_fmt, width, 0);
642 if (priv->is_70012) {
647 else if (width <= 1280)
649 else if (width <= 1080)
651 sStride = av_image_get_linesize(avctx->pix_fmt, pStride, 0);
656 dStride = priv->pic.linesize[0];
657 dst = priv->pic.data[0];
659 av_log(priv->avctx, AV_LOG_VERBOSE, "CrystalHD: Copying out frame\n");
667 av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: bottom field\n");
670 av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: top field\n");
674 for (sY = 0; sY < height; dY++, sY++) {
675 memcpy(&(dst[dY * dStride]), &(src[sY * sStride]), bwidth);
679 av_image_copy_plane(dst, dStride, src, sStride, bwidth, height);
682 priv->pic.interlaced_frame = interlaced;
684 priv->pic.top_field_first = !bottom_first;
686 priv->pic.pkt_pts = pkt_pts;
688 if (!priv->need_second_field) {
689 *data_size = sizeof(AVFrame);
690 *(AVFrame *)data = priv->pic;
694 * Two types of PAFF content have been observed. One form causes the
695 * hardware to return a field pair and the other individual fields,
696 * even though the input is always individual fields. We must skip
697 * copying on the next decode() call to maintain pipeline length in
700 if (!interlaced && (output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) &&
701 (pic_type == PICT_TOP_FIELD || pic_type == PICT_BOTTOM_FIELD)) {
702 av_log(priv->avctx, AV_LOG_VERBOSE, "Fieldpair from two packets.\n");
703 return RET_SKIP_NEXT_COPY;
707 * Testing has shown that in all cases where we don't want to return the
708 * full frame immediately, VDEC_FLAG_UNKNOWN_SRC is set.
710 return priv->need_second_field &&
711 !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ?
712 RET_COPY_NEXT_FIELD : RET_OK;
716 static inline CopyRet receive_frame(AVCodecContext *avctx,
717 void *data, int *data_size)
720 BC_DTS_PROC_OUT output = {
721 .PicInfo.width = avctx->width,
722 .PicInfo.height = avctx->height,
724 CHDContext *priv = avctx->priv_data;
725 HANDLE dev = priv->dev;
729 // Request decoded data from the driver
730 ret = DtsProcOutputNoCopy(dev, OUTPUT_PROC_TIMEOUT, &output);
731 if (ret == BC_STS_FMT_CHANGE) {
732 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Initial format change\n");
733 avctx->width = output.PicInfo.width;
734 avctx->height = output.PicInfo.height;
735 return RET_COPY_AGAIN;
736 } else if (ret == BC_STS_SUCCESS) {
738 if (output.PoutFlags & BC_POUT_FLAGS_PIB_VALID) {
739 if (priv->last_picture == -1) {
741 * Init to one less, so that the incrementing code doesn't
742 * need to be special-cased.
744 priv->last_picture = output.PicInfo.picture_number - 1;
747 if (avctx->codec->id == CODEC_ID_MPEG4 &&
748 output.PicInfo.timeStamp == 0 && priv->bframe_bug) {
749 av_log(avctx, AV_LOG_VERBOSE,
750 "CrystalHD: Not returning packed frame twice.\n");
751 priv->last_picture++;
752 DtsReleaseOutputBuffs(dev, NULL, FALSE);
753 return RET_COPY_AGAIN;
756 print_frame_info(priv, &output);
758 if (priv->last_picture + 1 < output.PicInfo.picture_number) {
759 av_log(avctx, AV_LOG_WARNING,
760 "CrystalHD: Picture Number discontinuity\n");
762 * Have we lost frames? If so, we need to shrink the
763 * pipeline length appropriately.
765 * XXX: I have no idea what the semantics of this situation
766 * are so I don't even know if we've lost frames or which
769 * In any case, only warn the first time.
771 priv->last_picture = output.PicInfo.picture_number - 1;
774 copy_ret = copy_frame(avctx, &output, data, data_size);
775 if (*data_size > 0) {
776 avctx->has_b_frames--;
777 priv->last_picture++;
778 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Pipeline length: %u\n",
779 avctx->has_b_frames);
783 * An invalid frame has been consumed.
785 av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput succeeded with "
787 avctx->has_b_frames--;
790 DtsReleaseOutputBuffs(dev, NULL, FALSE);
793 } else if (ret == BC_STS_BUSY) {
794 return RET_COPY_AGAIN;
796 av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput failed %d\n", ret);
802 static int decode(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
805 BC_DTS_STATUS decoder_status;
807 CHDContext *priv = avctx->priv_data;
808 HANDLE dev = priv->dev;
809 int len = avpkt->size;
810 uint8_t pic_type = 0;
812 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: decode_frame\n");
814 if (avpkt->size == 7 && !priv->bframe_bug) {
816 * The use of a drop frame triggers the bug
818 av_log(avctx, AV_LOG_INFO,
819 "CrystalHD: Enabling work-around for packed b-frame bug\n");
820 priv->bframe_bug = 1;
821 } else if (avpkt->size == 8 && priv->bframe_bug) {
823 * Delay frames don't trigger the bug
825 av_log(avctx, AV_LOG_INFO,
826 "CrystalHD: Disabling work-around for packed b-frame bug\n");
827 priv->bframe_bug = 0;
831 int32_t tx_free = (int32_t)DtsTxFreeSize(dev);
836 const uint8_t *in_data = avpkt->data;
838 H264Context *h = priv->parser->priv_data;
842 index = av_parser_parse2(priv->parser, avctx, &pout, &psize,
843 in_data, in_len, avctx->pkt->pts,
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 if (len < tx_free - 1024) {
856 * Despite being notionally opaque, either libcrystalhd or
857 * the hardware itself will mangle pts values that are too
858 * small or too large. The docs claim it should be in units
859 * of 100ns. Given that we're nominally dealing with a black
860 * box on both sides, any transform we do has no guarantee of
861 * avoiding mangling so we need to build a mapping to values
862 * we know will not be mangled.
864 uint64_t pts = opaque_list_push(priv, avctx->pkt->pts, pic_type);
866 return AVERROR(ENOMEM);
868 av_log(priv->avctx, AV_LOG_VERBOSE,
869 "input \"pts\": %"PRIu64"\n", pts);
870 ret = DtsProcInput(dev, avpkt->data, len, pts, 0);
871 if (ret == BC_STS_BUSY) {
872 av_log(avctx, AV_LOG_WARNING,
873 "CrystalHD: ProcInput returned busy\n");
875 return AVERROR(EBUSY);
876 } else if (ret != BC_STS_SUCCESS) {
877 av_log(avctx, AV_LOG_ERROR,
878 "CrystalHD: ProcInput failed: %u\n", ret);
881 avctx->has_b_frames++;
883 av_log(avctx, AV_LOG_WARNING, "CrystalHD: Input buffer full\n");
884 len = 0; // We didn't consume any bytes.
887 av_log(avctx, AV_LOG_INFO, "CrystalHD: No more input data\n");
890 if (priv->skip_next_output) {
891 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Skipping next output.\n");
892 priv->skip_next_output = 0;
893 avctx->has_b_frames--;
897 ret = DtsGetDriverStatus(dev, &decoder_status);
898 if (ret != BC_STS_SUCCESS) {
899 av_log(avctx, AV_LOG_ERROR, "CrystalHD: GetDriverStatus failed\n");
904 * No frames ready. Don't try to extract.
906 * Empirical testing shows that ReadyListCount can be a damn lie,
907 * and ProcOut still fails when count > 0. The same testing showed
908 * that two more iterations were needed before ProcOutput would
911 if (priv->output_ready < 2) {
912 if (decoder_status.ReadyListCount != 0)
913 priv->output_ready++;
915 av_log(avctx, AV_LOG_INFO, "CrystalHD: Filling pipeline.\n");
917 } else if (decoder_status.ReadyListCount == 0) {
919 * After the pipeline is established, if we encounter a lack of frames
920 * that probably means we're not giving the hardware enough time to
921 * decode them, so start increasing the wait time at the end of a
925 priv->decode_wait += WAIT_UNIT;
926 av_log(avctx, AV_LOG_INFO, "CrystalHD: No frames ready. Returning\n");
931 rec_ret = receive_frame(avctx, data, data_size);
932 if (rec_ret == RET_OK && *data_size == 0) {
934 * This case is for when the encoded fields are stored
935 * separately and we get a separate avpkt for each one. To keep
936 * the pipeline stable, we should return nothing and wait for
937 * the next time round to grab the second field.
938 * H.264 PAFF is an example of this.
940 av_log(avctx, AV_LOG_VERBOSE, "Returning after first field.\n");
941 avctx->has_b_frames--;
942 } else if (rec_ret == RET_COPY_NEXT_FIELD) {
944 * This case is for when the encoded fields are stored in a
945 * single avpkt but the hardware returns then separately. Unless
946 * we grab the second field before returning, we'll slip another
947 * frame in the pipeline and if that happens a lot, we're sunk.
948 * So we have to get that second field now.
949 * Interlaced mpeg2 and vc1 are examples of this.
951 av_log(avctx, AV_LOG_VERBOSE, "Trying to get second field.\n");
953 usleep(priv->decode_wait);
954 ret = DtsGetDriverStatus(dev, &decoder_status);
955 if (ret == BC_STS_SUCCESS &&
956 decoder_status.ReadyListCount > 0) {
957 rec_ret = receive_frame(avctx, data, data_size);
958 if ((rec_ret == RET_OK && *data_size > 0) ||
959 rec_ret == RET_ERROR)
963 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Got second field.\n");
964 } else if (rec_ret == RET_SKIP_NEXT_COPY) {
966 * Two input packets got turned into a field pair. Gawd.
968 av_log(avctx, AV_LOG_VERBOSE,
969 "Don't output on next decode call.\n");
970 priv->skip_next_output = 1;
973 * If rec_ret == RET_COPY_AGAIN, that means that either we just handled
974 * a FMT_CHANGE event and need to go around again for the actual frame,
975 * we got a busy status and need to try again, or we're dealing with
976 * packed b-frames, where the hardware strangely returns the packed
977 * p-frame twice. We choose to keep the second copy as it carries the
980 } while (rec_ret == RET_COPY_AGAIN);
981 usleep(priv->decode_wait);
986 #if CONFIG_H264_CRYSTALHD_DECODER
987 static AVClass h264_class = {
989 av_default_item_name,
991 LIBAVUTIL_VERSION_INT,
994 AVCodec ff_h264_crystalhd_decoder = {
995 .name = "h264_crystalhd",
996 .type = AVMEDIA_TYPE_VIDEO,
998 .priv_data_size = sizeof(CHDContext),
1002 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1004 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (CrystalHD acceleration)"),
1005 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1006 .priv_class = &h264_class,
1010 #if CONFIG_MPEG2_CRYSTALHD_DECODER
1011 static AVClass mpeg2_class = {
1013 av_default_item_name,
1015 LIBAVUTIL_VERSION_INT,
1018 AVCodec ff_mpeg2_crystalhd_decoder = {
1019 .name = "mpeg2_crystalhd",
1020 .type = AVMEDIA_TYPE_VIDEO,
1021 .id = CODEC_ID_MPEG2VIDEO,
1022 .priv_data_size = sizeof(CHDContext),
1026 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1028 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 Video (CrystalHD acceleration)"),
1029 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1030 .priv_class = &mpeg2_class,
1034 #if CONFIG_MPEG4_CRYSTALHD_DECODER
1035 static AVClass mpeg4_class = {
1037 av_default_item_name,
1039 LIBAVUTIL_VERSION_INT,
1042 AVCodec ff_mpeg4_crystalhd_decoder = {
1043 .name = "mpeg4_crystalhd",
1044 .type = AVMEDIA_TYPE_VIDEO,
1045 .id = CODEC_ID_MPEG4,
1046 .priv_data_size = sizeof(CHDContext),
1050 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1052 .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 (CrystalHD acceleration)"),
1053 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1054 .priv_class = &mpeg4_class,
1058 #if CONFIG_MSMPEG4_CRYSTALHD_DECODER
1059 static AVClass msmpeg4_class = {
1060 "msmpeg4_crystalhd",
1061 av_default_item_name,
1063 LIBAVUTIL_VERSION_INT,
1066 AVCodec ff_msmpeg4_crystalhd_decoder = {
1067 .name = "msmpeg4_crystalhd",
1068 .type = AVMEDIA_TYPE_VIDEO,
1069 .id = CODEC_ID_MSMPEG4V3,
1070 .priv_data_size = sizeof(CHDContext),
1074 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1076 .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 Microsoft variant version 3 (CrystalHD acceleration)"),
1077 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1078 .priv_class = &msmpeg4_class,
1082 #if CONFIG_VC1_CRYSTALHD_DECODER
1083 static AVClass vc1_class = {
1085 av_default_item_name,
1087 LIBAVUTIL_VERSION_INT,
1090 AVCodec ff_vc1_crystalhd_decoder = {
1091 .name = "vc1_crystalhd",
1092 .type = AVMEDIA_TYPE_VIDEO,
1094 .priv_data_size = sizeof(CHDContext),
1098 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1100 .long_name = NULL_IF_CONFIG_SMALL("SMPTE VC-1 (CrystalHD acceleration)"),
1101 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1102 .priv_class = &vc1_class,
1106 #if CONFIG_WMV3_CRYSTALHD_DECODER
1107 static AVClass wmv3_class = {
1109 av_default_item_name,
1111 LIBAVUTIL_VERSION_INT,
1114 AVCodec ff_wmv3_crystalhd_decoder = {
1115 .name = "wmv3_crystalhd",
1116 .type = AVMEDIA_TYPE_VIDEO,
1117 .id = CODEC_ID_WMV3,
1118 .priv_data_size = sizeof(CHDContext),
1122 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1124 .long_name = NULL_IF_CONFIG_SMALL("Windows Media Video 9 (CrystalHD acceleration)"),
1125 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1126 .priv_class = &wmv3_class,