crystalhd.c 25.4 KB
Newer Older
1 2 3
/*
 * - CrystalHD decoder module -
 *
4
 * Copyright(C) 2010,2011 Philip Langdale <ffmpeg.philipl@overt.org>
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/*
 * - Principles of Operation -
 *
 * The CrystalHD decoder operates at the bitstream level - which is an even
 * higher level than the decoding hardware you typically see in modern GPUs.
 * This means it has a very simple interface, in principle. You feed demuxed
 * packets in one end and get decoded picture (fields/frames) out the other.
 *
 * Of course, nothing is ever that simple. Due, at the very least, to b-frame
 * dependencies in the supported formats, the hardware has a delay between
 * when a packet goes in, and when a picture comes out. Furthermore, this delay
 * is not just a function of time, but also one of the dependency on additional
 * frames being fed into the decoder to satisfy the b-frame dependencies.
 *
37 38 39 40 41
 * As such, the hardware can only be used effectively with a decode API that
 * doesn't assume a 1:1 relationship between input packets and output frames.
 * The new avcodec decode API is such an API (an m:n API) while the old one is
 * 1:1. Consequently, we no longer support the old API, which allows us to avoid
 * the vicious hacks that are required to approximate 1:1 operation.
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
 */

/*****************************************************************************
 * Includes
 ****************************************************************************/

#define _XOPEN_SOURCE 600
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>

#include <libcrystalhd/bc_dts_types.h>
#include <libcrystalhd/bc_dts_defs.h>
#include <libcrystalhd/libcrystalhd_if.h>

#include "avcodec.h"
58
#include "decode.h"
59
#include "internal.h"
60 61
#include "libavutil/imgutils.h"
#include "libavutil/intreadwrite.h"
62
#include "libavutil/opt.h"
63

64 65 66 67
#if HAVE_UNISTD_H
#include <unistd.h>
#endif

68
/** Timeout parameter passed to DtsProcOutput() in us */
69
#define OUTPUT_PROC_TIMEOUT 50
70
/** Step between fake timestamps passed to hardware in units of 100ns */
71 72 73 74 75 76 77 78
#define TIMESTAMP_UNIT 100000


/*****************************************************************************
 * Module private data
 ****************************************************************************/

typedef enum {
79 80
    RET_ERROR           = -1,
    RET_OK              = 0,
81
    RET_COPY_AGAIN      = 1,
82 83 84 85 86 87 88 89 90
} CopyRet;

typedef struct OpaqueList {
    struct OpaqueList *next;
    uint64_t fake_timestamp;
    uint64_t reordered_opaque;
} OpaqueList;

typedef struct {
91
    AVClass *av_class;
92 93 94 95 96
    AVCodecContext *avctx;
    HANDLE dev;

    uint8_t is_70012;
    uint8_t need_second_field;
97
    uint8_t draining;
98 99 100

    OpaqueList *head;
    OpaqueList *tail;
101 102 103

    /* Options */
    uint32_t sWidth;
104 105
} CHDContext;

106 107 108 109
static const AVOption options[] = {
    { "crystalhd_downscale_width",
      "Turn on downscaling to the specified width",
      offsetof(CHDContext, sWidth),
110
      AV_OPT_TYPE_INT, {.i64 = 0}, 0, UINT32_MAX,
111 112 113 114
      AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM, },
    { NULL, },
};

115 116 117 118 119

/*****************************************************************************
 * Helper functions
 ****************************************************************************/

120
static inline BC_MEDIA_SUBTYPE id2subtype(CHDContext *priv, enum AVCodecID id)
121 122
{
    switch (id) {
123
    case AV_CODEC_ID_MPEG4:
124
        return BC_MSUBTYPE_DIVX;
125
    case AV_CODEC_ID_MSMPEG4V3:
126
        return BC_MSUBTYPE_DIVX311;
127
    case AV_CODEC_ID_MPEG2VIDEO:
128
        return BC_MSUBTYPE_MPEG2VIDEO;
129
    case AV_CODEC_ID_VC1:
130
        return BC_MSUBTYPE_VC1;
131
    case AV_CODEC_ID_WMV3:
132
        return BC_MSUBTYPE_WMV3;
133
    case AV_CODEC_ID_H264:
134
        return BC_MSUBTYPE_H264;
135 136 137 138 139 140 141
    default:
        return BC_MSUBTYPE_INVALID;
    }
}

static inline void print_frame_info(CHDContext *priv, BC_DTS_PROC_OUT *output)
{
142 143
    av_log(priv->avctx, AV_LOG_TRACE, "\tYBuffSz: %u\n", output->YbuffSz);
    av_log(priv->avctx, AV_LOG_TRACE, "\tYBuffDoneSz: %u\n",
144
           output->YBuffDoneSz);
145
    av_log(priv->avctx, AV_LOG_TRACE, "\tUVBuffDoneSz: %u\n",
146
           output->UVBuffDoneSz);
147
    av_log(priv->avctx, AV_LOG_TRACE, "\tTimestamp: %"PRIu64"\n",
148
           output->PicInfo.timeStamp);
149
    av_log(priv->avctx, AV_LOG_TRACE, "\tPicture Number: %u\n",
150
           output->PicInfo.picture_number);
151
    av_log(priv->avctx, AV_LOG_TRACE, "\tWidth: %u\n",
152
           output->PicInfo.width);
153
    av_log(priv->avctx, AV_LOG_TRACE, "\tHeight: %u\n",
154
           output->PicInfo.height);
155
    av_log(priv->avctx, AV_LOG_TRACE, "\tChroma: 0x%03x\n",
156
           output->PicInfo.chroma_format);
157
    av_log(priv->avctx, AV_LOG_TRACE, "\tPulldown: %u\n",
158
           output->PicInfo.pulldown);
159
    av_log(priv->avctx, AV_LOG_TRACE, "\tFlags: 0x%08x\n",
160
           output->PicInfo.flags);
161
    av_log(priv->avctx, AV_LOG_TRACE, "\tFrame Rate/Res: %u\n",
162
           output->PicInfo.frame_rate);
163
    av_log(priv->avctx, AV_LOG_TRACE, "\tAspect Ratio: %u\n",
164
           output->PicInfo.aspect_ratio);
165
    av_log(priv->avctx, AV_LOG_TRACE, "\tColor Primaries: %u\n",
166
           output->PicInfo.colour_primaries);
167
    av_log(priv->avctx, AV_LOG_TRACE, "\tMetaData: %u\n",
168
           output->PicInfo.picture_meta_payload);
169
    av_log(priv->avctx, AV_LOG_TRACE, "\tSession Number: %u\n",
170
           output->PicInfo.sess_num);
171
    av_log(priv->avctx, AV_LOG_TRACE, "\tycom: %u\n",
172
           output->PicInfo.ycom);
173
    av_log(priv->avctx, AV_LOG_TRACE, "\tCustom Aspect: %u\n",
174
           output->PicInfo.custom_aspect_ratio_width_height);
175
    av_log(priv->avctx, AV_LOG_TRACE, "\tFrames to Drop: %u\n",
176
           output->PicInfo.n_drop);
177
    av_log(priv->avctx, AV_LOG_TRACE, "\tH264 Valid Fields: 0x%08x\n",
178 179 180 181 182 183 184 185
           output->PicInfo.other.h264.valid);
}


/*****************************************************************************
 * OpaqueList functions
 ****************************************************************************/

186
static uint64_t opaque_list_push(CHDContext *priv, uint64_t reordered_opaque)
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
{
    OpaqueList *newNode = av_mallocz(sizeof (OpaqueList));
    if (!newNode) {
        av_log(priv->avctx, AV_LOG_ERROR,
               "Unable to allocate new node in OpaqueList.\n");
        return 0;
    }
    if (!priv->head) {
        newNode->fake_timestamp = TIMESTAMP_UNIT;
        priv->head              = newNode;
    } else {
        newNode->fake_timestamp = priv->tail->fake_timestamp + TIMESTAMP_UNIT;
        priv->tail->next        = newNode;
    }
    priv->tail = newNode;
    newNode->reordered_opaque = reordered_opaque;

    return newNode->fake_timestamp;
}

/*
 * The OpaqueList is built in decode order, while elements will be removed
 * in presentation order. If frames are reordered, this means we must be
 * able to remove elements that are not the first element.
211 212
 *
 * Returned node must be freed by caller.
213
 */
214
static OpaqueList *opaque_list_pop(CHDContext *priv, uint64_t fake_timestamp)
215 216 217 218 219 220
{
    OpaqueList *node = priv->head;

    if (!priv->head) {
        av_log(priv->avctx, AV_LOG_ERROR,
               "CrystalHD: Attempted to query non-existent timestamps.\n");
221
        return NULL;
222 223 224 225 226 227 228 229 230 231 232 233
    }

    /*
     * The first element is special-cased because we have to manipulate
     * the head pointer rather than the previous element in the list.
     */
    if (priv->head->fake_timestamp == fake_timestamp) {
        priv->head = node->next;

        if (!priv->head->next)
            priv->tail = priv->head;

234 235
        node->next = NULL;
        return node;
236 237 238 239 240 241 242
    }

    /*
     * The list is processed at arm's length so that we have the
     * previous element available to rewrite its next pointer.
     */
    while (node->next) {
243 244 245
        OpaqueList *current = node->next;
        if (current->fake_timestamp == fake_timestamp) {
            node->next = current->next;
246 247 248 249

            if (!node->next)
               priv->tail = node;

250 251
            current->next = NULL;
            return current;
252
        } else {
253
            node = current;
254 255 256 257 258
        }
    }

    av_log(priv->avctx, AV_LOG_VERBOSE,
           "CrystalHD: Couldn't match fake_timestamp.\n");
259
    return NULL;
260 261 262 263 264 265 266 267 268 269 270 271
}


/*****************************************************************************
 * Video decoder API function definitions
 ****************************************************************************/

static void flush(AVCodecContext *avctx)
{
    CHDContext *priv = avctx->priv_data;

    priv->need_second_field = 0;
272
    priv->draining          = 0;
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325

    /* Flush mode 4 flushes all software and hardware buffers. */
    DtsFlushInput(priv->dev, 4);
}


static av_cold int uninit(AVCodecContext *avctx)
{
    CHDContext *priv = avctx->priv_data;
    HANDLE device;

    device = priv->dev;
    DtsStopDecoder(device);
    DtsCloseDecoder(device);
    DtsDeviceClose(device);

    if (priv->head) {
       OpaqueList *node = priv->head;
       while (node) {
          OpaqueList *next = node->next;
          av_free(node);
          node = next;
       }
    }

    return 0;
}

static av_cold int init(AVCodecContext *avctx)
{
    CHDContext* priv;
    BC_STATUS ret;
    BC_INFO_CRYSTAL version;
    BC_INPUT_FORMAT format = {
        .FGTEnable   = FALSE,
        .Progressive = TRUE,
        .OptFlags    = 0x80000000 | vdecFrameRate59_94 | 0x40,
        .width       = avctx->width,
        .height      = avctx->height,
    };

    BC_MEDIA_SUBTYPE subtype;

    uint32_t mode = DTS_PLAYBACK_MODE |
                    DTS_LOAD_FILE_PLAY_FW |
                    DTS_SKIP_TX_CHK_CPB |
                    DTS_PLAYBACK_DROP_RPT_MODE |
                    DTS_SINGLE_THREADED_MODE |
                    DTS_DFLT_RESOLUTION(vdecRESOLUTION_1080p23_976);

    av_log(avctx, AV_LOG_VERBOSE, "CrystalHD Init for %s\n",
           avctx->codec->name);

326
    avctx->pix_fmt = AV_PIX_FMT_YUYV422;
327 328 329 330

    /* Initialize the library */
    priv               = avctx->priv_data;
    priv->avctx        = avctx;
331
    priv->draining     = 0;
332 333 334 335 336 337 338 339 340 341 342

    subtype = id2subtype(priv, avctx->codec->id);
    switch (subtype) {
    case BC_MSUBTYPE_H264:
        format.startCodeSz = 4;
        // Fall-through
    case BC_MSUBTYPE_VC1:
    case BC_MSUBTYPE_WVC1:
    case BC_MSUBTYPE_WMV3:
    case BC_MSUBTYPE_WMVA:
    case BC_MSUBTYPE_MPEG2VIDEO:
343
    case BC_MSUBTYPE_DIVX:
344 345 346 347 348 349 350 351 352 353
    case BC_MSUBTYPE_DIVX311:
        format.pMetaData  = avctx->extradata;
        format.metaDataSz = avctx->extradata_size;
        break;
    default:
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: Unknown codec name\n");
        return AVERROR(EINVAL);
    }
    format.mSubtype = subtype;

354 355 356 357 358
    if (priv->sWidth) {
        format.bEnableScaling = 1;
        format.ScalingParams.sWidth = priv->sWidth;
    }

359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
    /* Get a decoder instance */
    av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: starting up\n");
    // Initialize the Link and Decoder devices
    ret = DtsDeviceOpen(&priv->dev, mode);
    if (ret != BC_STS_SUCCESS) {
        av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: DtsDeviceOpen failed\n");
        goto fail;
    }

    ret = DtsCrystalHDVersion(priv->dev, &version);
    if (ret != BC_STS_SUCCESS) {
        av_log(avctx, AV_LOG_VERBOSE,
               "CrystalHD: DtsCrystalHDVersion failed\n");
        goto fail;
    }
    priv->is_70012 = version.device == 0;

    if (priv->is_70012 &&
        (subtype == BC_MSUBTYPE_DIVX || subtype == BC_MSUBTYPE_DIVX311)) {
        av_log(avctx, AV_LOG_VERBOSE,
               "CrystalHD: BCM70012 doesn't support MPEG4-ASP/DivX/Xvid\n");
        goto fail;
    }

    ret = DtsSetInputFormat(priv->dev, &format);
    if (ret != BC_STS_SUCCESS) {
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: SetInputFormat failed\n");
        goto fail;
    }

    ret = DtsOpenDecoder(priv->dev, BC_STREAM_TYPE_ES);
    if (ret != BC_STS_SUCCESS) {
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsOpenDecoder failed\n");
        goto fail;
    }

    ret = DtsSetColorSpace(priv->dev, OUTPUT_MODE422_YUY2);
    if (ret != BC_STS_SUCCESS) {
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsSetColorSpace failed\n");
        goto fail;
    }
    ret = DtsStartDecoder(priv->dev);
    if (ret != BC_STS_SUCCESS) {
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartDecoder failed\n");
        goto fail;
    }
    ret = DtsStartCapture(priv->dev);
    if (ret != BC_STS_SUCCESS) {
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartCapture failed\n");
        goto fail;
    }

    av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Init complete.\n");

    return 0;

 fail:
    uninit(avctx);
    return -1;
}


static inline CopyRet copy_frame(AVCodecContext *avctx,
                                 BC_DTS_PROC_OUT *output,
423
                                 AVFrame *frame, int *got_frame)
424 425
{
    BC_STATUS ret;
426
    BC_DTS_STATUS decoder_status = { 0, };
427 428 429
    uint8_t interlaced;

    CHDContext *priv = avctx->priv_data;
430
    int64_t pkt_pts  = AV_NOPTS_VALUE;
431 432 433 434 435 436 437 438 439 440 441 442 443

    uint8_t bottom_field = (output->PicInfo.flags & VDEC_FLAG_BOTTOMFIELD) ==
                           VDEC_FLAG_BOTTOMFIELD;
    uint8_t bottom_first = !!(output->PicInfo.flags & VDEC_FLAG_BOTTOM_FIRST);

    int width    = output->PicInfo.width;
    int height   = output->PicInfo.height;
    int bwidth;
    uint8_t *src = output->Ybuff;
    int sStride;
    uint8_t *dst;
    int dStride;

444 445 446 447 448
    if (output->PicInfo.timeStamp != 0) {
        OpaqueList *node = opaque_list_pop(priv, output->PicInfo.timeStamp);
        if (node) {
            pkt_pts = node->reordered_opaque;
            av_free(node);
449 450 451 452 453
        } else {
            /*
             * We will encounter a situation where a timestamp cannot be
             * popped if a second field is being returned. In this case,
             * each field has the same timestamp and the first one will
454 455
             * cause it to be popped. We'll avoid overwriting the valid
             * timestamp below.
456
             */
457 458 459 460 461
        }
        av_log(avctx, AV_LOG_VERBOSE, "output \"pts\": %"PRIu64"\n",
               output->PicInfo.timeStamp);
    }

462 463 464 465 466 467 468
    ret = DtsGetDriverStatus(priv->dev, &decoder_status);
    if (ret != BC_STS_SUCCESS) {
        av_log(avctx, AV_LOG_ERROR,
               "CrystalHD: GetDriverStatus failed: %u\n", ret);
       return RET_ERROR;
    }

469
    interlaced = output->PicInfo.flags & VDEC_FLAG_INTERLACED_SRC;
470

471 472
    av_log(avctx, AV_LOG_VERBOSE, "Interlaced state: %d\n",
           interlaced);
473 474 475

    priv->need_second_field = interlaced && !priv->need_second_field;

476 477
    if (!frame->data[0]) {
        if (ff_get_buffer(avctx, frame, 0) < 0)
478 479 480 481
            return RET_ERROR;
    }

    bwidth = av_image_get_linesize(avctx->pix_fmt, width, 0);
482 483 484
    if (bwidth < 0)
       return RET_ERROR;

485 486 487 488 489 490 491
    if (priv->is_70012) {
        int pStride;

        if (width <= 720)
            pStride = 720;
        else if (width <= 1280)
            pStride = 1280;
sebist's avatar
sebist committed
492
        else pStride = 1920;
493
        sStride = av_image_get_linesize(avctx->pix_fmt, pStride, 0);
494 495
        if (sStride < 0)
            return RET_ERROR;
496 497 498 499
    } else {
        sStride = bwidth;
    }

500 501
    dStride = frame->linesize[0];
    dst     = frame->data[0];
502 503 504

    av_log(priv->avctx, AV_LOG_VERBOSE, "CrystalHD: Copying out frame\n");

505 506 507 508 509 510 511 512 513
    /*
     * The hardware doesn't return the first sample of a picture.
     * Ignoring why it behaves this way, it's better to copy the sample from
     * the second line, rather than the next sample across because the chroma
     * values should be correct (assuming the decoded video was 4:2:0, which
     * it was).
     */
    *((uint32_t *)src) = *((uint32_t *)(src + sStride));

514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
    if (interlaced) {
        int dY = 0;
        int sY = 0;

        height /= 2;
        if (bottom_field) {
            av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: bottom field\n");
            dY = 1;
        } else {
            av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: top field\n");
            dY = 0;
        }

        for (sY = 0; sY < height; dY++, sY++) {
            memcpy(&(dst[dY * dStride]), &(src[sY * sStride]), bwidth);
529
            dY++;
530 531 532 533 534
        }
    } else {
        av_image_copy_plane(dst, dStride, src, sStride, bwidth, height);
    }

535
    frame->interlaced_frame = interlaced;
536
    if (interlaced)
537
        frame->top_field_first = !bottom_first;
538

539
    frame->pts = pkt_pts;
540 541
#if FF_API_PKT_PTS
FF_DISABLE_DEPRECATION_WARNINGS
542
    frame->pkt_pts = pkt_pts;
543 544
FF_ENABLE_DEPRECATION_WARNINGS
#endif
545

546 547 548
    frame->pkt_pos = -1;
    frame->pkt_duration = 0;
    frame->pkt_size = -1;
549 550

    if (!priv->need_second_field) {
551
        *got_frame       = 1;
552 553
    } else {
        return RET_COPY_AGAIN;
554 555
    }

556
    return RET_OK;
557 558 559 560
}


static inline CopyRet receive_frame(AVCodecContext *avctx,
561
                                    AVFrame *frame, int *got_frame)
562 563 564 565 566 567 568 569 570
{
    BC_STATUS ret;
    BC_DTS_PROC_OUT output = {
        .PicInfo.width  = avctx->width,
        .PicInfo.height = avctx->height,
    };
    CHDContext *priv = avctx->priv_data;
    HANDLE dev       = priv->dev;

571
    *got_frame = 0;
572 573 574 575 576 577 578

    // Request decoded data from the driver
    ret = DtsProcOutputNoCopy(dev, OUTPUT_PROC_TIMEOUT, &output);
    if (ret == BC_STS_FMT_CHANGE) {
        av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Initial format change\n");
        avctx->width  = output.PicInfo.width;
        avctx->height = output.PicInfo.height;
sebist's avatar
sebist committed
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
        switch ( output.PicInfo.aspect_ratio ) {
        case vdecAspectRatioSquare:
            avctx->sample_aspect_ratio = (AVRational) {  1,  1};
            break;
        case vdecAspectRatio12_11:
            avctx->sample_aspect_ratio = (AVRational) { 12, 11};
            break;
        case vdecAspectRatio10_11:
            avctx->sample_aspect_ratio = (AVRational) { 10, 11};
            break;
        case vdecAspectRatio16_11:
            avctx->sample_aspect_ratio = (AVRational) { 16, 11};
            break;
        case vdecAspectRatio40_33:
            avctx->sample_aspect_ratio = (AVRational) { 40, 33};
            break;
        case vdecAspectRatio24_11:
            avctx->sample_aspect_ratio = (AVRational) { 24, 11};
            break;
        case vdecAspectRatio20_11:
            avctx->sample_aspect_ratio = (AVRational) { 20, 11};
            break;
        case vdecAspectRatio32_11:
            avctx->sample_aspect_ratio = (AVRational) { 32, 11};
            break;
        case vdecAspectRatio80_33:
            avctx->sample_aspect_ratio = (AVRational) { 80, 33};
            break;
        case vdecAspectRatio18_11:
            avctx->sample_aspect_ratio = (AVRational) { 18, 11};
            break;
        case vdecAspectRatio15_11:
            avctx->sample_aspect_ratio = (AVRational) { 15, 11};
            break;
        case vdecAspectRatio64_33:
            avctx->sample_aspect_ratio = (AVRational) { 64, 33};
            break;
        case vdecAspectRatio160_99:
            avctx->sample_aspect_ratio = (AVRational) {160, 99};
            break;
        case vdecAspectRatio4_3:
            avctx->sample_aspect_ratio = (AVRational) {  4,  3};
            break;
        case vdecAspectRatio16_9:
            avctx->sample_aspect_ratio = (AVRational) { 16,  9};
            break;
        case vdecAspectRatio221_1:
            avctx->sample_aspect_ratio = (AVRational) {221,  1};
            break;
        }
629
        return RET_COPY_AGAIN;
630 631 632 633 634
    } else if (ret == BC_STS_SUCCESS) {
        int copy_ret = -1;
        if (output.PoutFlags & BC_POUT_FLAGS_PIB_VALID) {
            print_frame_info(priv, &output);

635
            copy_ret = copy_frame(avctx, &output, frame, got_frame);
636 637 638 639 640 641
        } else {
            /*
             * An invalid frame has been consumed.
             */
            av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput succeeded with "
                                        "invalid PIB\n");
642
            copy_ret = RET_COPY_AGAIN;
643 644 645 646 647
        }
        DtsReleaseOutputBuffs(dev, NULL, FALSE);

        return copy_ret;
    } else if (ret == BC_STS_BUSY) {
648
        return RET_COPY_AGAIN;
649 650 651 652 653 654
    } else {
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput failed %d\n", ret);
        return RET_ERROR;
    }
}

655
static int crystalhd_decode_packet(AVCodecContext *avctx, const AVPacket *avpkt)
656
{
657
    BC_STATUS bc_ret;
658 659
    CHDContext *priv   = avctx->priv_data;
    HANDLE dev         = priv->dev;
660 661
    AVPacket filtered_packet = { 0 };
    int ret = 0;
662

663
    av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: decode_packet\n");
664

665
    if (avpkt && avpkt->size) {
666
        uint64_t pts;
667

668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
        /*
         * Despite being notionally opaque, either libcrystalhd or
         * the hardware itself will mangle pts values that are too
         * small or too large. The docs claim it should be in units
         * of 100ns. Given that we're nominally dealing with a black
         * box on both sides, any transform we do has no guarantee of
         * avoiding mangling so we need to build a mapping to values
         * we know will not be mangled.
         */
        pts = opaque_list_push(priv, avpkt->pts);
        if (!pts) {
            ret = AVERROR(ENOMEM);
            goto exit;
        }
        av_log(priv->avctx, AV_LOG_VERBOSE,
               "input \"pts\": %"PRIu64"\n", pts);
        bc_ret = DtsProcInput(dev, avpkt->data, avpkt->size, pts, 0);
        if (bc_ret == BC_STS_BUSY) {
            av_log(avctx, AV_LOG_WARNING,
                   "CrystalHD: ProcInput returned busy\n");
688 689
            ret = AVERROR(EAGAIN);
            goto exit;
690 691 692 693 694
        } else if (bc_ret != BC_STS_SUCCESS) {
            av_log(avctx, AV_LOG_ERROR,
                   "CrystalHD: ProcInput failed: %u\n", ret);
            ret = -1;
            goto exit;
695 696 697
        }
    } else {
        av_log(avctx, AV_LOG_INFO, "CrystalHD: No more input data\n");
698
        priv->draining = 1;
699 700
        ret = AVERROR_EOF;
        goto exit;
701
    }
702 703 704 705
 exit:
    av_packet_unref(&filtered_packet);
    return ret;
}
706

707 708 709 710 711 712 713 714
static int crystalhd_receive_frame(AVCodecContext *avctx, AVFrame *frame)
{
    BC_STATUS bc_ret;
    BC_DTS_STATUS decoder_status = { 0, };
    CopyRet rec_ret;
    CHDContext *priv   = avctx->priv_data;
    HANDLE dev         = priv->dev;
    int got_frame = 0;
715 716
    int ret = 0;
    AVPacket pkt = {0};
717

718 719
    av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: receive_frame\n");

720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
    ret = ff_decode_get_packet(avctx, &pkt);
    if (ret < 0 && ret != AVERROR_EOF) {
        return ret;
    }

    while (pkt.size > DtsTxFreeSize(dev)) {
        /*
         * Block until there is space in the buffer for the next packet.
         * We assume that the hardware will make forward progress at this
         * point, although in pathological cases that may not happen.
         */
        av_log(avctx, AV_LOG_TRACE, "CrystalHD: Waiting for space in input buffer\n");
    }

    ret = crystalhd_decode_packet(avctx, &pkt);
    av_packet_unref(&pkt);
    // crystalhd_is_buffer_full() should avoid this.
    if (ret == AVERROR(EAGAIN)) {
        ret = AVERROR_EXTERNAL;
    }
    if (ret < 0 && ret != AVERROR_EOF) {
        return ret;
    }

744 745 746 747 748 749
    do {
        bc_ret = DtsGetDriverStatus(dev, &decoder_status);
        if (bc_ret != BC_STS_SUCCESS) {
            av_log(avctx, AV_LOG_ERROR, "CrystalHD: GetDriverStatus failed\n");
            return -1;
        }
750

751
        if (decoder_status.ReadyListCount == 0) {
752
            av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Insufficient frames ready. Returning\n");
753 754 755 756 757 758 759
            got_frame = 0;
            rec_ret = RET_OK;
            break;
        }

        rec_ret = receive_frame(avctx, frame, &got_frame);
    } while (rec_ret == RET_COPY_AGAIN);
760

761 762 763
    if (rec_ret == RET_ERROR) {
        return -1;
    } else if (got_frame == 0) {
764
        return priv->draining ? AVERROR_EOF : AVERROR(EAGAIN);
765 766 767
    } else {
        return 0;
    }
768 769
}

770
#define DEFINE_CRYSTALHD_DECODER(x, X, bsf_name) \
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
    static const AVClass x##_crystalhd_class = { \
        .class_name = #x "_crystalhd", \
        .item_name = av_default_item_name, \
        .option = options, \
        .version = LIBAVUTIL_VERSION_INT, \
    }; \
    AVCodec ff_##x##_crystalhd_decoder = { \
        .name           = #x "_crystalhd", \
        .long_name      = NULL_IF_CONFIG_SMALL("CrystalHD " #X " decoder"), \
        .type           = AVMEDIA_TYPE_VIDEO, \
        .id             = AV_CODEC_ID_##X, \
        .priv_data_size = sizeof(CHDContext), \
        .priv_class     = &x##_crystalhd_class, \
        .init           = init, \
        .close          = uninit, \
        .receive_frame  = crystalhd_receive_frame, \
        .flush          = flush, \
788
        .bsfs           = bsf_name, \
789
        .capabilities   = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AVOID_PROBING, \
790 791
        .pix_fmts       = (const enum AVPixelFormat[]){AV_PIX_FMT_YUYV422, AV_PIX_FMT_NONE}, \
    };
792 793

#if CONFIG_H264_CRYSTALHD_DECODER
794
DEFINE_CRYSTALHD_DECODER(h264, H264, "h264_mp4toannexb")
795 796 797
#endif

#if CONFIG_MPEG2_CRYSTALHD_DECODER
798
DEFINE_CRYSTALHD_DECODER(mpeg2, MPEG2VIDEO, NULL)
799 800 801
#endif

#if CONFIG_MPEG4_CRYSTALHD_DECODER
802
DEFINE_CRYSTALHD_DECODER(mpeg4, MPEG4, "mpeg4_unpack_bframes")
803 804 805
#endif

#if CONFIG_MSMPEG4_CRYSTALHD_DECODER
806
DEFINE_CRYSTALHD_DECODER(msmpeg4, MSMPEG4V3, NULL)
807 808 809
#endif

#if CONFIG_VC1_CRYSTALHD_DECODER
810
DEFINE_CRYSTALHD_DECODER(vc1, VC1, NULL)
811 812 813
#endif

#if CONFIG_WMV3_CRYSTALHD_DECODER
814
DEFINE_CRYSTALHD_DECODER(wmv3, WMV3, NULL)
815
#endif