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 uint32_t orig_data_size = avctx->extradata_size;
406 uint8_t *orig_data = av_malloc(orig_data_size);
408 av_log(avctx, AV_LOG_ERROR,
409 "Failed to allocate copy of extradata\n");
410 return AVERROR(ENOMEM);
412 memcpy(orig_data, avctx->extradata, orig_data_size);
415 priv->bsfc = av_bitstream_filter_init("h264_mp4toannexb");
417 av_log(avctx, AV_LOG_ERROR,
418 "Cannot open the h264_mp4toannexb BSF!\n");
420 return AVERROR_BSF_NOT_FOUND;
422 av_bitstream_filter_filter(priv->bsfc, avctx, NULL, &dummy_p,
423 &dummy_int, NULL, 0, 0);
425 priv->sps_pps_buf = avctx->extradata;
426 priv->sps_pps_size = avctx->extradata_size;
427 avctx->extradata = orig_data;
428 avctx->extradata_size = orig_data_size;
430 format.pMetaData = priv->sps_pps_buf;
431 format.metaDataSz = priv->sps_pps_size;
432 format.startCodeSz = (avctx->extradata[4] & 0x03) + 1;
435 case BC_MSUBTYPE_H264:
436 format.startCodeSz = 4;
438 case BC_MSUBTYPE_VC1:
439 case BC_MSUBTYPE_WVC1:
440 case BC_MSUBTYPE_WMV3:
441 case BC_MSUBTYPE_WMVA:
442 case BC_MSUBTYPE_MPEG2VIDEO:
443 case BC_MSUBTYPE_DIVX:
444 case BC_MSUBTYPE_DIVX311:
445 format.pMetaData = avctx->extradata;
446 format.metaDataSz = avctx->extradata_size;
449 av_log(avctx, AV_LOG_ERROR, "CrystalHD: Unknown codec name\n");
450 return AVERROR(EINVAL);
452 format.mSubtype = subtype;
455 format.bEnableScaling = 1;
456 format.ScalingParams.sWidth = priv->sWidth;
459 /* Get a decoder instance */
460 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: starting up\n");
461 // Initialize the Link and Decoder devices
462 ret = DtsDeviceOpen(&priv->dev, mode);
463 if (ret != BC_STS_SUCCESS) {
464 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: DtsDeviceOpen failed\n");
468 ret = DtsCrystalHDVersion(priv->dev, &version);
469 if (ret != BC_STS_SUCCESS) {
470 av_log(avctx, AV_LOG_VERBOSE,
471 "CrystalHD: DtsCrystalHDVersion failed\n");
474 priv->is_70012 = version.device == 0;
476 if (priv->is_70012 &&
477 (subtype == BC_MSUBTYPE_DIVX || subtype == BC_MSUBTYPE_DIVX311)) {
478 av_log(avctx, AV_LOG_VERBOSE,
479 "CrystalHD: BCM70012 doesn't support MPEG4-ASP/DivX/Xvid\n");
483 ret = DtsSetInputFormat(priv->dev, &format);
484 if (ret != BC_STS_SUCCESS) {
485 av_log(avctx, AV_LOG_ERROR, "CrystalHD: SetInputFormat failed\n");
489 ret = DtsOpenDecoder(priv->dev, BC_STREAM_TYPE_ES);
490 if (ret != BC_STS_SUCCESS) {
491 av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsOpenDecoder failed\n");
495 ret = DtsSetColorSpace(priv->dev, OUTPUT_MODE422_YUY2);
496 if (ret != BC_STS_SUCCESS) {
497 av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsSetColorSpace failed\n");
500 ret = DtsStartDecoder(priv->dev);
501 if (ret != BC_STS_SUCCESS) {
502 av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartDecoder failed\n");
505 ret = DtsStartCapture(priv->dev);
506 if (ret != BC_STS_SUCCESS) {
507 av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartCapture failed\n");
511 if (avctx->codec->id == CODEC_ID_H264) {
512 priv->parser = av_parser_init(avctx->codec->id);
514 av_log(avctx, AV_LOG_WARNING,
515 "Cannot open the h.264 parser! Interlaced h.264 content "
516 "will not be detected reliably.\n");
517 priv->parser->flags = PARSER_FLAG_COMPLETE_FRAMES;
519 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Init complete.\n");
529 static inline CopyRet copy_frame(AVCodecContext *avctx,
530 BC_DTS_PROC_OUT *output,
531 void *data, int *data_size)
534 BC_DTS_STATUS decoder_status;
535 uint8_t trust_interlaced;
538 CHDContext *priv = avctx->priv_data;
539 int64_t pkt_pts = AV_NOPTS_VALUE;
540 uint8_t pic_type = 0;
542 uint8_t bottom_field = (output->PicInfo.flags & VDEC_FLAG_BOTTOMFIELD) ==
543 VDEC_FLAG_BOTTOMFIELD;
544 uint8_t bottom_first = !!(output->PicInfo.flags & VDEC_FLAG_BOTTOM_FIRST);
546 int width = output->PicInfo.width;
547 int height = output->PicInfo.height;
549 uint8_t *src = output->Ybuff;
554 if (output->PicInfo.timeStamp != 0) {
555 OpaqueList *node = opaque_list_pop(priv, output->PicInfo.timeStamp);
557 pkt_pts = node->reordered_opaque;
558 pic_type = node->pic_type;
562 * We will encounter a situation where a timestamp cannot be
563 * popped if a second field is being returned. In this case,
564 * each field has the same timestamp and the first one will
565 * cause it to be popped. To keep subsequent calculations
566 * simple, pic_type should be set a FIELD value - doesn't
567 * matter which, but I chose BOTTOM.
569 pic_type = PICT_BOTTOM_FIELD;
571 av_log(avctx, AV_LOG_VERBOSE, "output \"pts\": %"PRIu64"\n",
572 output->PicInfo.timeStamp);
573 av_log(avctx, AV_LOG_VERBOSE, "output picture type %d\n",
577 ret = DtsGetDriverStatus(priv->dev, &decoder_status);
578 if (ret != BC_STS_SUCCESS) {
579 av_log(avctx, AV_LOG_ERROR,
580 "CrystalHD: GetDriverStatus failed: %u\n", ret);
585 * For most content, we can trust the interlaced flag returned
586 * by the hardware, but sometimes we can't. These are the
587 * conditions under which we can trust the flag:
589 * 1) It's not h.264 content
590 * 2) The UNKNOWN_SRC flag is not set
591 * 3) We know we're expecting a second field
592 * 4) The hardware reports this picture and the next picture
593 * have the same picture number.
595 * Note that there can still be interlaced content that will
596 * fail this check, if the hardware hasn't decoded the next
597 * picture or if there is a corruption in the stream. (In either
598 * case a 0 will be returned for the next picture number)
600 trust_interlaced = avctx->codec->id != CODEC_ID_H264 ||
601 !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ||
602 priv->need_second_field ||
603 (decoder_status.picNumFlags & ~0x40000000) ==
604 output->PicInfo.picture_number;
607 * If we got a false negative for trust_interlaced on the first field,
608 * we will realise our mistake here when we see that the picture number is that
609 * of the previous picture. We cannot recover the frame and should discard the
610 * second field to keep the correct number of output frames.
612 if (output->PicInfo.picture_number == priv->last_picture && !priv->need_second_field) {
613 av_log(avctx, AV_LOG_WARNING,
614 "Incorrectly guessed progressive frame. Discarding second field\n");
615 /* Returning without providing a picture. */
619 interlaced = (output->PicInfo.flags & VDEC_FLAG_INTERLACED_SRC) &&
622 if (!trust_interlaced && (decoder_status.picNumFlags & ~0x40000000) == 0) {
623 av_log(avctx, AV_LOG_VERBOSE,
624 "Next picture number unknown. Assuming progressive frame.\n");
627 av_log(avctx, AV_LOG_VERBOSE, "Interlaced state: %d | trust_interlaced %d\n",
628 interlaced, trust_interlaced);
630 if (priv->pic.data[0] && !priv->need_second_field)
631 avctx->release_buffer(avctx, &priv->pic);
633 priv->need_second_field = interlaced && !priv->need_second_field;
635 priv->pic.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE |
636 FF_BUFFER_HINTS_REUSABLE;
637 if (!priv->pic.data[0]) {
638 if (avctx->get_buffer(avctx, &priv->pic) < 0) {
639 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
644 bwidth = av_image_get_linesize(avctx->pix_fmt, width, 0);
645 if (priv->is_70012) {
650 else if (width <= 1280)
652 else if (width <= 1080)
654 sStride = av_image_get_linesize(avctx->pix_fmt, pStride, 0);
659 dStride = priv->pic.linesize[0];
660 dst = priv->pic.data[0];
662 av_log(priv->avctx, AV_LOG_VERBOSE, "CrystalHD: Copying out frame\n");
670 av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: bottom field\n");
673 av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: top field\n");
677 for (sY = 0; sY < height; dY++, sY++) {
678 memcpy(&(dst[dY * dStride]), &(src[sY * sStride]), bwidth);
682 av_image_copy_plane(dst, dStride, src, sStride, bwidth, height);
685 priv->pic.interlaced_frame = interlaced;
687 priv->pic.top_field_first = !bottom_first;
689 priv->pic.pkt_pts = pkt_pts;
691 if (!priv->need_second_field) {
692 *data_size = sizeof(AVFrame);
693 *(AVFrame *)data = priv->pic;
697 * Two types of PAFF content have been observed. One form causes the
698 * hardware to return a field pair and the other individual fields,
699 * even though the input is always individual fields. We must skip
700 * copying on the next decode() call to maintain pipeline length in
703 if (!interlaced && (output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) &&
704 (pic_type == PICT_TOP_FIELD || pic_type == PICT_BOTTOM_FIELD)) {
705 av_log(priv->avctx, AV_LOG_VERBOSE, "Fieldpair from two packets.\n");
706 return RET_SKIP_NEXT_COPY;
710 * Testing has shown that in all cases where we don't want to return the
711 * full frame immediately, VDEC_FLAG_UNKNOWN_SRC is set.
713 return priv->need_second_field &&
714 !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ?
715 RET_COPY_NEXT_FIELD : RET_OK;
719 static inline CopyRet receive_frame(AVCodecContext *avctx,
720 void *data, int *data_size)
723 BC_DTS_PROC_OUT output = {
724 .PicInfo.width = avctx->width,
725 .PicInfo.height = avctx->height,
727 CHDContext *priv = avctx->priv_data;
728 HANDLE dev = priv->dev;
732 // Request decoded data from the driver
733 ret = DtsProcOutputNoCopy(dev, OUTPUT_PROC_TIMEOUT, &output);
734 if (ret == BC_STS_FMT_CHANGE) {
735 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Initial format change\n");
736 avctx->width = output.PicInfo.width;
737 avctx->height = output.PicInfo.height;
738 return RET_COPY_AGAIN;
739 } else if (ret == BC_STS_SUCCESS) {
741 if (output.PoutFlags & BC_POUT_FLAGS_PIB_VALID) {
742 if (priv->last_picture == -1) {
744 * Init to one less, so that the incrementing code doesn't
745 * need to be special-cased.
747 priv->last_picture = output.PicInfo.picture_number - 1;
750 if (avctx->codec->id == CODEC_ID_MPEG4 &&
751 output.PicInfo.timeStamp == 0 && priv->bframe_bug) {
752 av_log(avctx, AV_LOG_VERBOSE,
753 "CrystalHD: Not returning packed frame twice.\n");
754 priv->last_picture++;
755 DtsReleaseOutputBuffs(dev, NULL, FALSE);
756 return RET_COPY_AGAIN;
759 print_frame_info(priv, &output);
761 if (priv->last_picture + 1 < output.PicInfo.picture_number) {
762 av_log(avctx, AV_LOG_WARNING,
763 "CrystalHD: Picture Number discontinuity\n");
765 * Have we lost frames? If so, we need to shrink the
766 * pipeline length appropriately.
768 * XXX: I have no idea what the semantics of this situation
769 * are so I don't even know if we've lost frames or which
772 * In any case, only warn the first time.
774 priv->last_picture = output.PicInfo.picture_number - 1;
777 copy_ret = copy_frame(avctx, &output, data, data_size);
778 if (*data_size > 0) {
779 avctx->has_b_frames--;
780 priv->last_picture++;
781 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Pipeline length: %u\n",
782 avctx->has_b_frames);
786 * An invalid frame has been consumed.
788 av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput succeeded with "
790 avctx->has_b_frames--;
793 DtsReleaseOutputBuffs(dev, NULL, FALSE);
796 } else if (ret == BC_STS_BUSY) {
797 return RET_COPY_AGAIN;
799 av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput failed %d\n", ret);
805 static int decode(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
808 BC_DTS_STATUS decoder_status;
810 CHDContext *priv = avctx->priv_data;
811 HANDLE dev = priv->dev;
812 int len = avpkt->size;
813 uint8_t pic_type = 0;
815 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: decode_frame\n");
817 if (avpkt->size == 7 && !priv->bframe_bug) {
819 * The use of a drop frame triggers the bug
821 av_log(avctx, AV_LOG_INFO,
822 "CrystalHD: Enabling work-around for packed b-frame bug\n");
823 priv->bframe_bug = 1;
824 } else if (avpkt->size == 8 && priv->bframe_bug) {
826 * Delay frames don't trigger the bug
828 av_log(avctx, AV_LOG_INFO,
829 "CrystalHD: Disabling work-around for packed b-frame bug\n");
830 priv->bframe_bug = 0;
834 int32_t tx_free = (int32_t)DtsTxFreeSize(dev);
837 uint8_t *in_data = avpkt->data;
842 ret = av_bitstream_filter_filter(priv->bsfc, avctx, NULL,
844 avpkt->data, len, 0);
851 H264Context *h = priv->parser->priv_data;
853 index = av_parser_parse2(priv->parser, avctx, &pout, &psize,
854 in_data, in_len, avctx->pkt->pts,
857 av_log(avctx, AV_LOG_WARNING,
858 "CrystalHD: Failed to parse h.264 packet to "
859 "detect interlacing.\n");
860 } else if (index != in_len) {
861 av_log(avctx, AV_LOG_WARNING,
862 "CrystalHD: Failed to parse h.264 packet "
863 "completely. Interlaced frames may be "
864 "incorrectly detected\n.");
866 av_log(avctx, AV_LOG_VERBOSE,
867 "CrystalHD: parser picture type %d\n",
868 h->s.picture_structure);
869 pic_type = h->s.picture_structure;
872 av_log(avctx, AV_LOG_WARNING,
873 "CrystalHD: mp4toannexb filter failed to filter "
874 "packet. Interlaced frames may be incorrectly "
882 if (len < tx_free - 1024) {
884 * Despite being notionally opaque, either libcrystalhd or
885 * the hardware itself will mangle pts values that are too
886 * small or too large. The docs claim it should be in units
887 * of 100ns. Given that we're nominally dealing with a black
888 * box on both sides, any transform we do has no guarantee of
889 * avoiding mangling so we need to build a mapping to values
890 * we know will not be mangled.
892 uint64_t pts = opaque_list_push(priv, avctx->pkt->pts, pic_type);
894 return AVERROR(ENOMEM);
896 av_log(priv->avctx, AV_LOG_VERBOSE,
897 "input \"pts\": %"PRIu64"\n", pts);
898 ret = DtsProcInput(dev, avpkt->data, len, pts, 0);
899 if (ret == BC_STS_BUSY) {
900 av_log(avctx, AV_LOG_WARNING,
901 "CrystalHD: ProcInput returned busy\n");
903 return AVERROR(EBUSY);
904 } else if (ret != BC_STS_SUCCESS) {
905 av_log(avctx, AV_LOG_ERROR,
906 "CrystalHD: ProcInput failed: %u\n", ret);
909 avctx->has_b_frames++;
911 av_log(avctx, AV_LOG_WARNING, "CrystalHD: Input buffer full\n");
912 len = 0; // We didn't consume any bytes.
915 av_log(avctx, AV_LOG_INFO, "CrystalHD: No more input data\n");
918 if (priv->skip_next_output) {
919 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Skipping next output.\n");
920 priv->skip_next_output = 0;
921 avctx->has_b_frames--;
925 ret = DtsGetDriverStatus(dev, &decoder_status);
926 if (ret != BC_STS_SUCCESS) {
927 av_log(avctx, AV_LOG_ERROR, "CrystalHD: GetDriverStatus failed\n");
932 * No frames ready. Don't try to extract.
934 * Empirical testing shows that ReadyListCount can be a damn lie,
935 * and ProcOut still fails when count > 0. The same testing showed
936 * that two more iterations were needed before ProcOutput would
939 if (priv->output_ready < 2) {
940 if (decoder_status.ReadyListCount != 0)
941 priv->output_ready++;
943 av_log(avctx, AV_LOG_INFO, "CrystalHD: Filling pipeline.\n");
945 } else if (decoder_status.ReadyListCount == 0) {
947 * After the pipeline is established, if we encounter a lack of frames
948 * that probably means we're not giving the hardware enough time to
949 * decode them, so start increasing the wait time at the end of a
953 priv->decode_wait += WAIT_UNIT;
954 av_log(avctx, AV_LOG_INFO, "CrystalHD: No frames ready. Returning\n");
959 rec_ret = receive_frame(avctx, data, data_size);
960 if (rec_ret == RET_OK && *data_size == 0) {
962 * This case is for when the encoded fields are stored
963 * separately and we get a separate avpkt for each one. To keep
964 * the pipeline stable, we should return nothing and wait for
965 * the next time round to grab the second field.
966 * H.264 PAFF is an example of this.
968 av_log(avctx, AV_LOG_VERBOSE, "Returning after first field.\n");
969 avctx->has_b_frames--;
970 } else if (rec_ret == RET_COPY_NEXT_FIELD) {
972 * This case is for when the encoded fields are stored in a
973 * single avpkt but the hardware returns then separately. Unless
974 * we grab the second field before returning, we'll slip another
975 * frame in the pipeline and if that happens a lot, we're sunk.
976 * So we have to get that second field now.
977 * Interlaced mpeg2 and vc1 are examples of this.
979 av_log(avctx, AV_LOG_VERBOSE, "Trying to get second field.\n");
981 usleep(priv->decode_wait);
982 ret = DtsGetDriverStatus(dev, &decoder_status);
983 if (ret == BC_STS_SUCCESS &&
984 decoder_status.ReadyListCount > 0) {
985 rec_ret = receive_frame(avctx, data, data_size);
986 if ((rec_ret == RET_OK && *data_size > 0) ||
987 rec_ret == RET_ERROR)
991 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Got second field.\n");
992 } else if (rec_ret == RET_SKIP_NEXT_COPY) {
994 * Two input packets got turned into a field pair. Gawd.
996 av_log(avctx, AV_LOG_VERBOSE,
997 "Don't output on next decode call.\n");
998 priv->skip_next_output = 1;
1001 * If rec_ret == RET_COPY_AGAIN, that means that either we just handled
1002 * a FMT_CHANGE event and need to go around again for the actual frame,
1003 * we got a busy status and need to try again, or we're dealing with
1004 * packed b-frames, where the hardware strangely returns the packed
1005 * p-frame twice. We choose to keep the second copy as it carries the
1008 } while (rec_ret == RET_COPY_AGAIN);
1009 usleep(priv->decode_wait);
1014 #if CONFIG_H264_CRYSTALHD_DECODER
1015 static AVClass h264_class = {
1017 av_default_item_name,
1019 LIBAVUTIL_VERSION_INT,
1022 AVCodec ff_h264_crystalhd_decoder = {
1023 .name = "h264_crystalhd",
1024 .type = AVMEDIA_TYPE_VIDEO,
1025 .id = CODEC_ID_H264,
1026 .priv_data_size = sizeof(CHDContext),
1030 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1032 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (CrystalHD acceleration)"),
1033 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1034 .priv_class = &h264_class,
1038 #if CONFIG_MPEG2_CRYSTALHD_DECODER
1039 static AVClass mpeg2_class = {
1041 av_default_item_name,
1043 LIBAVUTIL_VERSION_INT,
1046 AVCodec ff_mpeg2_crystalhd_decoder = {
1047 .name = "mpeg2_crystalhd",
1048 .type = AVMEDIA_TYPE_VIDEO,
1049 .id = CODEC_ID_MPEG2VIDEO,
1050 .priv_data_size = sizeof(CHDContext),
1054 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1056 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 Video (CrystalHD acceleration)"),
1057 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1058 .priv_class = &mpeg2_class,
1062 #if CONFIG_MPEG4_CRYSTALHD_DECODER
1063 static AVClass mpeg4_class = {
1065 av_default_item_name,
1067 LIBAVUTIL_VERSION_INT,
1070 AVCodec ff_mpeg4_crystalhd_decoder = {
1071 .name = "mpeg4_crystalhd",
1072 .type = AVMEDIA_TYPE_VIDEO,
1073 .id = CODEC_ID_MPEG4,
1074 .priv_data_size = sizeof(CHDContext),
1078 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1080 .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 (CrystalHD acceleration)"),
1081 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1082 .priv_class = &mpeg4_class,
1086 #if CONFIG_MSMPEG4_CRYSTALHD_DECODER
1087 static AVClass msmpeg4_class = {
1088 "msmpeg4_crystalhd",
1089 av_default_item_name,
1091 LIBAVUTIL_VERSION_INT,
1094 AVCodec ff_msmpeg4_crystalhd_decoder = {
1095 .name = "msmpeg4_crystalhd",
1096 .type = AVMEDIA_TYPE_VIDEO,
1097 .id = CODEC_ID_MSMPEG4V3,
1098 .priv_data_size = sizeof(CHDContext),
1102 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1104 .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 Microsoft variant version 3 (CrystalHD acceleration)"),
1105 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1106 .priv_class = &msmpeg4_class,
1110 #if CONFIG_VC1_CRYSTALHD_DECODER
1111 static AVClass vc1_class = {
1113 av_default_item_name,
1115 LIBAVUTIL_VERSION_INT,
1118 AVCodec ff_vc1_crystalhd_decoder = {
1119 .name = "vc1_crystalhd",
1120 .type = AVMEDIA_TYPE_VIDEO,
1122 .priv_data_size = sizeof(CHDContext),
1126 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1128 .long_name = NULL_IF_CONFIG_SMALL("SMPTE VC-1 (CrystalHD acceleration)"),
1129 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1130 .priv_class = &vc1_class,
1134 #if CONFIG_WMV3_CRYSTALHD_DECODER
1135 static AVClass wmv3_class = {
1137 av_default_item_name,
1139 LIBAVUTIL_VERSION_INT,
1142 AVCodec ff_wmv3_crystalhd_decoder = {
1143 .name = "wmv3_crystalhd",
1144 .type = AVMEDIA_TYPE_VIDEO,
1145 .id = CODEC_ID_WMV3,
1146 .priv_data_size = sizeof(CHDContext),
1150 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1152 .long_name = NULL_IF_CONFIG_SMALL("Windows Media Video 9 (CrystalHD acceleration)"),
1153 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1154 .priv_class = &wmv3_class,