Statistics
| Branch: | Revision:

ffmpeg / libavcodec / crystalhd.c @ 85b01098

History | View | Annotate | Download (35.6 KB)

1
/*
2
 * - CrystalHD decoder module -
3
 *
4
 * Copyright(C) 2010,2011 Philip Langdale <ffmpeg.philipl@overt.org>
5
 *
6
 * This file is part of FFmpeg.
7
 *
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.
12
 *
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.
17
 *
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
21
 */
22

    
23
/*
24
 * - Principles of Operation -
25
 *
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.
30
 *
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.
36
 *
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.
40
 *
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.
45
 *
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.
53
 *
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.
62
 *
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).
70
 */
71

    
72
/*****************************************************************************
73
 * Includes
74
 ****************************************************************************/
75

    
76
#define _XOPEN_SOURCE 600
77
#include <inttypes.h>
78
#include <stdio.h>
79
#include <stdlib.h>
80
#include <unistd.h>
81

    
82
#include <libcrystalhd/bc_dts_types.h>
83
#include <libcrystalhd/bc_dts_defs.h>
84
#include <libcrystalhd/libcrystalhd_if.h>
85

    
86
#include "avcodec.h"
87
#include "h264.h"
88
#include "libavutil/imgutils.h"
89
#include "libavutil/intreadwrite.h"
90

    
91
/** Timeout parameter passed to DtsProcOutput() in us */
92
#define OUTPUT_PROC_TIMEOUT 50
93
/** Step between fake timestamps passed to hardware in units of 100ns */
94
#define TIMESTAMP_UNIT 100000
95
/** Initial value in us of the wait in decode() */
96
#define BASE_WAIT 10000
97
/** Increment in us to adjust wait in decode() */
98
#define WAIT_UNIT 1000
99

    
100

    
101
/*****************************************************************************
102
 * Module private data
103
 ****************************************************************************/
104

    
105
typedef enum {
106
    RET_ERROR           = -1,
107
    RET_OK              = 0,
108
    RET_COPY_AGAIN      = 1,
109
    RET_SKIP_NEXT_COPY  = 2,
110
    RET_COPY_NEXT_FIELD = 3,
111
} CopyRet;
112

    
113
typedef struct OpaqueList {
114
    struct OpaqueList *next;
115
    uint64_t fake_timestamp;
116
    uint64_t reordered_opaque;
117
    uint8_t pic_type;
118
} OpaqueList;
119

    
120
typedef struct {
121
    AVCodecContext *avctx;
122
    AVFrame pic;
123
    HANDLE dev;
124

    
125
    AVCodecParserContext *parser;
126

    
127
    uint8_t is_70012;
128
    uint8_t *sps_pps_buf;
129
    uint32_t sps_pps_size;
130
    uint8_t is_nal;
131
    uint8_t output_ready;
132
    uint8_t need_second_field;
133
    uint8_t skip_next_output;
134
    uint64_t decode_wait;
135

    
136
    uint64_t last_picture;
137

    
138
    OpaqueList *head;
139
    OpaqueList *tail;
140
} CHDContext;
141

    
142

    
143
/*****************************************************************************
144
 * Helper functions
145
 ****************************************************************************/
146

    
147
static inline BC_MEDIA_SUBTYPE id2subtype(CHDContext *priv, enum CodecID id)
148
{
149
    switch (id) {
150
    case CODEC_ID_MPEG4:
151
        return BC_MSUBTYPE_DIVX;
152
    case CODEC_ID_MSMPEG4V3:
153
        return BC_MSUBTYPE_DIVX311;
154
    case CODEC_ID_MPEG2VIDEO:
155
        return BC_MSUBTYPE_MPEG2VIDEO;
156
    case CODEC_ID_VC1:
157
        return BC_MSUBTYPE_VC1;
158
    case CODEC_ID_WMV3:
159
        return BC_MSUBTYPE_WMV3;
160
    case CODEC_ID_H264:
161
        return priv->is_nal ? BC_MSUBTYPE_AVC1 : BC_MSUBTYPE_H264;
162
    default:
163
        return BC_MSUBTYPE_INVALID;
164
    }
165
}
166

    
167
static inline void print_frame_info(CHDContext *priv, BC_DTS_PROC_OUT *output)
168
{
169
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tYBuffSz: %u\n", output->YbuffSz);
170
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tYBuffDoneSz: %u\n",
171
           output->YBuffDoneSz);
172
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tUVBuffDoneSz: %u\n",
173
           output->UVBuffDoneSz);
174
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tTimestamp: %"PRIu64"\n",
175
           output->PicInfo.timeStamp);
176
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tPicture Number: %u\n",
177
           output->PicInfo.picture_number);
178
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tWidth: %u\n",
179
           output->PicInfo.width);
180
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tHeight: %u\n",
181
           output->PicInfo.height);
182
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tChroma: 0x%03x\n",
183
           output->PicInfo.chroma_format);
184
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tPulldown: %u\n",
185
           output->PicInfo.pulldown);
186
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tFlags: 0x%08x\n",
187
           output->PicInfo.flags);
188
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tFrame Rate/Res: %u\n",
189
           output->PicInfo.frame_rate);
190
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tAspect Ratio: %u\n",
191
           output->PicInfo.aspect_ratio);
192
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tColor Primaries: %u\n",
193
           output->PicInfo.colour_primaries);
194
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tMetaData: %u\n",
195
           output->PicInfo.picture_meta_payload);
196
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tSession Number: %u\n",
197
           output->PicInfo.sess_num);
198
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tycom: %u\n",
199
           output->PicInfo.ycom);
200
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tCustom Aspect: %u\n",
201
           output->PicInfo.custom_aspect_ratio_width_height);
202
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tFrames to Drop: %u\n",
203
           output->PicInfo.n_drop);
204
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tH264 Valid Fields: 0x%08x\n",
205
           output->PicInfo.other.h264.valid);
206
}
207

    
208

    
209
/*****************************************************************************
210
 * OpaqueList functions
211
 ****************************************************************************/
212

    
213
static uint64_t opaque_list_push(CHDContext *priv, uint64_t reordered_opaque,
214
                                 uint8_t pic_type)
215
{
216
    OpaqueList *newNode = av_mallocz(sizeof (OpaqueList));
217
    if (!newNode) {
218
        av_log(priv->avctx, AV_LOG_ERROR,
219
               "Unable to allocate new node in OpaqueList.\n");
220
        return 0;
221
    }
222
    if (!priv->head) {
223
        newNode->fake_timestamp = TIMESTAMP_UNIT;
224
        priv->head              = newNode;
225
    } else {
226
        newNode->fake_timestamp = priv->tail->fake_timestamp + TIMESTAMP_UNIT;
227
        priv->tail->next        = newNode;
228
    }
229
    priv->tail = newNode;
230
    newNode->reordered_opaque = reordered_opaque;
231
    newNode->pic_type = pic_type;
232

    
233
    return newNode->fake_timestamp;
234
}
235

    
236
/*
237
 * The OpaqueList is built in decode order, while elements will be removed
238
 * in presentation order. If frames are reordered, this means we must be
239
 * able to remove elements that are not the first element.
240
 */
241
static uint8_t opaque_list_pop(CHDContext *priv, uint64_t fake_timestamp,
242
                               uint64_t *reordered_opaque, uint8_t *pic_type)
243
{
244
    OpaqueList *node = priv->head;
245

    
246
    if (!priv->head) {
247
        av_log(priv->avctx, AV_LOG_ERROR,
248
               "CrystalHD: Attempted to query non-existent timestamps.\n");
249
        return FALSE;
250
    }
251

    
252
    /*
253
     * The first element is special-cased because we have to manipulate
254
     * the head pointer rather than the previous element in the list.
255
     */
256
    if (priv->head->fake_timestamp == fake_timestamp) {
257
        *reordered_opaque = node->reordered_opaque;
258
        *pic_type = node->pic_type;
259
        priv->head = node->next;
260
        av_free(node);
261

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

    
265
        return TRUE;
266
    }
267

    
268
    /*
269
     * The list is processed at arm's length so that we have the
270
     * previous element available to rewrite its next pointer.
271
     */
272
    while (node->next) {
273
        OpaqueList *next = node->next;
274
        if (next->fake_timestamp == fake_timestamp) {
275
            *reordered_opaque = node->reordered_opaque;
276
            *pic_type = node->pic_type;
277
            node->next = next->next;
278
            av_free(next);
279

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

    
283
            return TRUE;
284
        } else {
285
            node = next;
286
        }
287
    }
288

    
289
    av_log(priv->avctx, AV_LOG_VERBOSE,
290
           "CrystalHD: Couldn't match fake_timestamp.\n");
291
    return FALSE;
292
}
293

    
294

    
295
/*****************************************************************************
296
 * Video decoder API function definitions
297
 ****************************************************************************/
298

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

    
303
    avctx->has_b_frames     = 0;
304
    priv->last_picture      = -1;
305
    priv->output_ready      = 0;
306
    priv->need_second_field = 0;
307
    priv->skip_next_output  = 0;
308
    priv->decode_wait       = BASE_WAIT;
309

    
310
    if (priv->pic.data[0])
311
        avctx->release_buffer(avctx, &priv->pic);
312

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

    
317

    
318
static av_cold int uninit(AVCodecContext *avctx)
319
{
320
    CHDContext *priv = avctx->priv_data;
321
    HANDLE device;
322

    
323
    device = priv->dev;
324
    DtsStopDecoder(device);
325
    DtsCloseDecoder(device);
326
    DtsDeviceClose(device);
327

    
328
    av_parser_close(priv->parser);
329

    
330
    av_free(priv->sps_pps_buf);
331

    
332
    if (priv->pic.data[0])
333
        avctx->release_buffer(avctx, &priv->pic);
334

    
335
    if (priv->head) {
336
       OpaqueList *node = priv->head;
337
       while (node) {
338
          OpaqueList *next = node->next;
339
          av_free(node);
340
          node = next;
341
       }
342
    }
343

    
344
    return 0;
345
}
346

    
347

    
348
static av_cold int init(AVCodecContext *avctx)
349
{
350
    CHDContext* priv;
351
    BC_STATUS ret;
352
    BC_INFO_CRYSTAL version;
353
    BC_INPUT_FORMAT format = {
354
        .FGTEnable   = FALSE,
355
        .Progressive = TRUE,
356
        .OptFlags    = 0x80000000 | vdecFrameRate59_94 | 0x40,
357
        .width       = avctx->width,
358
        .height      = avctx->height,
359
    };
360

    
361
    BC_MEDIA_SUBTYPE subtype;
362

    
363
    uint32_t mode = DTS_PLAYBACK_MODE |
364
                    DTS_LOAD_FILE_PLAY_FW |
365
                    DTS_SKIP_TX_CHK_CPB |
366
                    DTS_PLAYBACK_DROP_RPT_MODE |
367
                    DTS_SINGLE_THREADED_MODE |
368
                    DTS_DFLT_RESOLUTION(vdecRESOLUTION_1080p23_976);
369

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

    
373
    avctx->pix_fmt = PIX_FMT_YUYV422;
374

    
375
    /* Initialize the library */
376
    priv               = avctx->priv_data;
377
    priv->avctx        = avctx;
378
    priv->is_nal       = avctx->extradata_size > 0 && *(avctx->extradata) == 1;
379
    priv->last_picture = -1;
380
    priv->decode_wait  = BASE_WAIT;
381

    
382
    subtype = id2subtype(priv, avctx->codec->id);
383
    switch (subtype) {
384
    case BC_MSUBTYPE_AVC1:
385
        {
386
            uint8_t *dummy_p;
387
            int dummy_int;
388
            AVBitStreamFilterContext *bsfc;
389

    
390
            uint32_t orig_data_size = avctx->extradata_size;
391
            uint8_t *orig_data = av_malloc(orig_data_size);
392
            if (!orig_data) {
393
                av_log(avctx, AV_LOG_ERROR,
394
                       "Failed to allocate copy of extradata\n");
395
                return AVERROR(ENOMEM);
396
            }
397
            memcpy(orig_data, avctx->extradata, orig_data_size);
398

    
399

    
400
            bsfc = av_bitstream_filter_init("h264_mp4toannexb");
401
            if (!bsfc) {
402
                av_log(avctx, AV_LOG_ERROR,
403
                       "Cannot open the h264_mp4toannexb BSF!\n");
404
                av_free(orig_data);
405
                return AVERROR_BSF_NOT_FOUND;
406
            }
407
            av_bitstream_filter_filter(bsfc, avctx, NULL, &dummy_p,
408
                                       &dummy_int, NULL, 0, 0);
409
            av_bitstream_filter_close(bsfc);
410

    
411
            priv->sps_pps_buf     = avctx->extradata;
412
            priv->sps_pps_size    = avctx->extradata_size;
413
            avctx->extradata      = orig_data;
414
            avctx->extradata_size = orig_data_size;
415

    
416
            format.pMetaData   = priv->sps_pps_buf;
417
            format.metaDataSz  = priv->sps_pps_size;
418
            format.startCodeSz = (avctx->extradata[4] & 0x03) + 1;
419
        }
420
        break;
421
    case BC_MSUBTYPE_H264:
422
        format.startCodeSz = 4;
423
        // Fall-through
424
    case BC_MSUBTYPE_VC1:
425
    case BC_MSUBTYPE_WVC1:
426
    case BC_MSUBTYPE_WMV3:
427
    case BC_MSUBTYPE_WMVA:
428
    case BC_MSUBTYPE_MPEG2VIDEO:
429
    case BC_MSUBTYPE_DIVX:
430
    case BC_MSUBTYPE_DIVX311:
431
        format.pMetaData  = avctx->extradata;
432
        format.metaDataSz = avctx->extradata_size;
433
        break;
434
    default:
435
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: Unknown codec name\n");
436
        return AVERROR(EINVAL);
437
    }
438
    format.mSubtype = subtype;
439

    
440
    /* Get a decoder instance */
441
    av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: starting up\n");
442
    // Initialize the Link and Decoder devices
443
    ret = DtsDeviceOpen(&priv->dev, mode);
444
    if (ret != BC_STS_SUCCESS) {
445
        av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: DtsDeviceOpen failed\n");
446
        goto fail;
447
    }
448

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

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

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

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

    
476
    ret = DtsSetColorSpace(priv->dev, OUTPUT_MODE422_YUY2);
477
    if (ret != BC_STS_SUCCESS) {
478
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsSetColorSpace failed\n");
479
        goto fail;
480
    }
481
    ret = DtsStartDecoder(priv->dev);
482
    if (ret != BC_STS_SUCCESS) {
483
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartDecoder failed\n");
484
        goto fail;
485
    }
486
    ret = DtsStartCapture(priv->dev);
487
    if (ret != BC_STS_SUCCESS) {
488
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartCapture failed\n");
489
        goto fail;
490
    }
491

    
492
    if (avctx->codec->id == CODEC_ID_H264) {
493
        priv->parser = av_parser_init(avctx->codec->id);
494
        if (!priv->parser)
495
            av_log(avctx, AV_LOG_WARNING,
496
                   "Cannot open the h.264 parser! Interlaced h.264 content "
497
                   "will not be detected reliably.\n");
498
    }
499
    av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Init complete.\n");
500

    
501
    return 0;
502

    
503
 fail:
504
    uninit(avctx);
505
    return -1;
506
}
507

    
508

    
509
/*
510
 * The CrystalHD doesn't report interlaced H.264 content in a way that allows
511
 * us to distinguish between specific cases that require different handling.
512
 * So, for now, we have to hard-code the behaviour we want.
513
 *
514
 * Specifically, there are PAFF samples where input is always separate fields
515
 * but the hardware returns separate fields on one occasion and a field-pair
516
 * on another. The code assumes the first case and define
517
 * ASSUME_TWO_INPUTS_ONE_OUTPUT to assume the second case.
518
 */
519
#define ASSUME_TWO_INPUTS_ONE_OUTPUT 0
520
static inline CopyRet copy_frame(AVCodecContext *avctx,
521
                                 BC_DTS_PROC_OUT *output,
522
                                 void *data, int *data_size)
523
{
524
    BC_STATUS ret;
525
    BC_DTS_STATUS decoder_status;
526
    uint8_t ignore_interlaced;
527
    uint8_t interlaced;
528

    
529
    CHDContext *priv = avctx->priv_data;
530
    int64_t pkt_pts  = AV_NOPTS_VALUE;
531
    uint8_t pic_type = 0;
532

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

    
537
    int width    = output->PicInfo.width;
538
    int height   = output->PicInfo.height;
539
    int bwidth;
540
    uint8_t *src = output->Ybuff;
541
    int sStride;
542
    uint8_t *dst;
543
    int dStride;
544

    
545
    if (output->PicInfo.timeStamp != 0) {
546
        uint8_t pop_ret;
547
        pop_ret = opaque_list_pop(priv, output->PicInfo.timeStamp,
548
                                  &pkt_pts, &pic_type);
549
        if (!pop_ret) {
550
           /*
551
            * We will encounter a situation where a timestamp cannot be
552
            * popped if a second field is being returned. In this case,
553
            * each field has the same timestamp and the first one will
554
            * cause it to be popped. To keep subsequent calculations
555
            * simple, pic_type should be set a FIELD value - doesn't
556
            * matter which, but I chose BOTTOM.
557
            */
558
           pic_type = PICT_BOTTOM_FIELD;
559
        }
560
        av_log(avctx, AV_LOG_VERBOSE, "output \"pts\": %"PRIu64"\n",
561
               output->PicInfo.timeStamp);
562
        av_log(avctx, AV_LOG_VERBOSE, "output picture type %d\n",
563
               pic_type);
564
    }
565

    
566
    ret = DtsGetDriverStatus(priv->dev, &decoder_status);
567
    if (ret != BC_STS_SUCCESS) {
568
        av_log(avctx, AV_LOG_ERROR,
569
               "CrystalHD: GetDriverStatus failed: %u\n", ret);
570
       return RET_ERROR;
571
    }
572

    
573
    /*
574
     * Testing has, so far, shown that we can't trust the interlaced flag for
575
     * H.264 content when VDEC_FLAG_UNKNOWN_SRC is set.
576
     */
577
    ignore_interlaced = avctx->codec->id == CODEC_ID_H264 &&
578
                        (output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) &&
579
                        (pic_type == 0 || pic_type == PICT_FRAME ||
580
                         ASSUME_TWO_INPUTS_ONE_OUTPUT);
581
    interlaced        = (output->PicInfo.flags & VDEC_FLAG_INTERLACED_SRC) &&
582
                        !ignore_interlaced;
583

    
584
    av_log(avctx, AV_LOG_VERBOSE, "Interlaced state: %d | ignore_interlaced %d\n",
585
           interlaced, ignore_interlaced);
586

    
587
    if (priv->pic.data[0] && !priv->need_second_field)
588
        avctx->release_buffer(avctx, &priv->pic);
589

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

    
592
    priv->pic.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE |
593
                             FF_BUFFER_HINTS_REUSABLE;
594
    if (!priv->pic.data[0]) {
595
        if (avctx->get_buffer(avctx, &priv->pic) < 0) {
596
            av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
597
            return RET_ERROR;
598
        }
599
    }
600

    
601
    bwidth = av_image_get_linesize(avctx->pix_fmt, width, 0);
602
    if (priv->is_70012) {
603
        int pStride;
604

    
605
        if (width <= 720)
606
            pStride = 720;
607
        else if (width <= 1280)
608
            pStride = 1280;
609
        else if (width <= 1080)
610
            pStride = 1080;
611
        sStride = av_image_get_linesize(avctx->pix_fmt, pStride, 0);
612
    } else {
613
        sStride = bwidth;
614
    }
615

    
616
    dStride = priv->pic.linesize[0];
617
    dst     = priv->pic.data[0];
618

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

    
621
    if (interlaced) {
622
        int dY = 0;
623
        int sY = 0;
624

    
625
        height /= 2;
626
        if (bottom_field) {
627
            av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: bottom field\n");
628
            dY = 1;
629
        } else {
630
            av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: top field\n");
631
            dY = 0;
632
        }
633

    
634
        for (sY = 0; sY < height; dY++, sY++) {
635
            memcpy(&(dst[dY * dStride]), &(src[sY * sStride]), bwidth);
636
            dY++;
637
        }
638
    } else {
639
        av_image_copy_plane(dst, dStride, src, sStride, bwidth, height);
640
    }
641

    
642
    priv->pic.interlaced_frame = interlaced;
643
    if (interlaced)
644
        priv->pic.top_field_first = !bottom_first;
645

    
646
    priv->pic.pkt_pts = pkt_pts;
647

    
648
    if (!priv->need_second_field) {
649
        *data_size       = sizeof(AVFrame);
650
        *(AVFrame *)data = priv->pic;
651
    }
652

    
653
    if (ASSUME_TWO_INPUTS_ONE_OUTPUT &&
654
        output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) {
655
        av_log(priv->avctx, AV_LOG_VERBOSE, "Fieldpair from two packets.\n");
656
        return RET_SKIP_NEXT_COPY;
657
    }
658

    
659
    /*
660
     * Testing has shown that in all cases where we don't want to return the
661
     * full frame immediately, VDEC_FLAG_UNKNOWN_SRC is set.
662
     */
663
    return priv->need_second_field &&
664
           !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ?
665
           RET_COPY_NEXT_FIELD : RET_OK;
666
}
667

    
668

    
669
static inline CopyRet receive_frame(AVCodecContext *avctx,
670
                                    void *data, int *data_size)
671
{
672
    BC_STATUS ret;
673
    BC_DTS_PROC_OUT output = {
674
        .PicInfo.width  = avctx->width,
675
        .PicInfo.height = avctx->height,
676
    };
677
    CHDContext *priv = avctx->priv_data;
678
    HANDLE dev       = priv->dev;
679

    
680
    *data_size = 0;
681

    
682
    // Request decoded data from the driver
683
    ret = DtsProcOutputNoCopy(dev, OUTPUT_PROC_TIMEOUT, &output);
684
    if (ret == BC_STS_FMT_CHANGE) {
685
        av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Initial format change\n");
686
        avctx->width  = output.PicInfo.width;
687
        avctx->height = output.PicInfo.height;
688
        return RET_COPY_AGAIN;
689
    } else if (ret == BC_STS_SUCCESS) {
690
        int copy_ret = -1;
691
        if (output.PoutFlags & BC_POUT_FLAGS_PIB_VALID) {
692
            if (priv->last_picture == -1) {
693
                /*
694
                 * Init to one less, so that the incrementing code doesn't
695
                 * need to be special-cased.
696
                 */
697
                priv->last_picture = output.PicInfo.picture_number - 1;
698
            }
699

    
700
            if (avctx->codec->id == CODEC_ID_MPEG4 &&
701
                output.PicInfo.timeStamp == 0) {
702
                av_log(avctx, AV_LOG_VERBOSE,
703
                       "CrystalHD: Not returning packed frame twice.\n");
704
                priv->last_picture++;
705
                DtsReleaseOutputBuffs(dev, NULL, FALSE);
706
                return RET_COPY_AGAIN;
707
            }
708

    
709
            print_frame_info(priv, &output);
710

    
711
            if (priv->last_picture + 1 < output.PicInfo.picture_number) {
712
                av_log(avctx, AV_LOG_WARNING,
713
                       "CrystalHD: Picture Number discontinuity\n");
714
                /*
715
                 * Have we lost frames? If so, we need to shrink the
716
                 * pipeline length appropriately.
717
                 *
718
                 * XXX: I have no idea what the semantics of this situation
719
                 * are so I don't even know if we've lost frames or which
720
                 * ones.
721
                 *
722
                 * In any case, only warn the first time.
723
                 */
724
               priv->last_picture = output.PicInfo.picture_number - 1;
725
            }
726

    
727
            copy_ret = copy_frame(avctx, &output, data, data_size);
728
            if (*data_size > 0) {
729
                avctx->has_b_frames--;
730
                priv->last_picture++;
731
                av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Pipeline length: %u\n",
732
                       avctx->has_b_frames);
733
            }
734
        } else {
735
            /*
736
             * An invalid frame has been consumed.
737
             */
738
            av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput succeeded with "
739
                                        "invalid PIB\n");
740
            avctx->has_b_frames--;
741
            copy_ret = RET_OK;
742
        }
743
        DtsReleaseOutputBuffs(dev, NULL, FALSE);
744

    
745
        return copy_ret;
746
    } else if (ret == BC_STS_BUSY) {
747
        return RET_COPY_AGAIN;
748
    } else {
749
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput failed %d\n", ret);
750
        return RET_ERROR;
751
    }
752
}
753

    
754

    
755
static int decode(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
756
{
757
    BC_STATUS ret;
758
    BC_DTS_STATUS decoder_status;
759
    CopyRet rec_ret;
760
    CHDContext *priv   = avctx->priv_data;
761
    HANDLE dev         = priv->dev;
762
    int len            = avpkt->size;
763
    uint8_t pic_type   = 0;
764

    
765
    av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: decode_frame\n");
766

    
767
    if (len) {
768
        int32_t tx_free = (int32_t)DtsTxFreeSize(dev);
769

    
770
        if (priv->parser) {
771
            uint8_t *pout = NULL;
772
            int psize = len;
773
            H264Context *h = priv->parser->priv_data;
774

    
775
            while (psize) {
776
                ret = av_parser_parse2(priv->parser, avctx, &pout, &psize,
777
                                       avpkt->data, len, avctx->pkt->pts,
778
                                       avctx->pkt->dts, len - psize);
779
            }
780
            av_log(avctx, AV_LOG_VERBOSE,
781
                   "CrystalHD: parser picture type %d\n",
782
                   h->s.picture_structure);
783
            pic_type = h->s.picture_structure;
784
        }
785

    
786
        if (len < tx_free - 1024) {
787
            /*
788
             * Despite being notionally opaque, either libcrystalhd or
789
             * the hardware itself will mangle pts values that are too
790
             * small or too large. The docs claim it should be in units
791
             * of 100ns. Given that we're nominally dealing with a black
792
             * box on both sides, any transform we do has no guarantee of
793
             * avoiding mangling so we need to build a mapping to values
794
             * we know will not be mangled.
795
             */
796
            uint64_t pts = opaque_list_push(priv, avctx->pkt->pts, pic_type);
797
            if (!pts) {
798
                return AVERROR(ENOMEM);
799
            }
800
            av_log(priv->avctx, AV_LOG_VERBOSE,
801
                   "input \"pts\": %"PRIu64"\n", pts);
802
            ret = DtsProcInput(dev, avpkt->data, len, pts, 0);
803
            if (ret == BC_STS_BUSY) {
804
                av_log(avctx, AV_LOG_WARNING,
805
                       "CrystalHD: ProcInput returned busy\n");
806
                usleep(BASE_WAIT);
807
                return AVERROR(EBUSY);
808
            } else if (ret != BC_STS_SUCCESS) {
809
                av_log(avctx, AV_LOG_ERROR,
810
                       "CrystalHD: ProcInput failed: %u\n", ret);
811
                return -1;
812
            }
813
            avctx->has_b_frames++;
814
        } else {
815
            av_log(avctx, AV_LOG_WARNING, "CrystalHD: Input buffer full\n");
816
            len = 0; // We didn't consume any bytes.
817
        }
818
    } else {
819
        av_log(avctx, AV_LOG_INFO, "CrystalHD: No more input data\n");
820
    }
821

    
822
    if (priv->skip_next_output) {
823
        av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Skipping next output.\n");
824
        priv->skip_next_output = 0;
825
        avctx->has_b_frames--;
826
        return len;
827
    }
828

    
829
    ret = DtsGetDriverStatus(dev, &decoder_status);
830
    if (ret != BC_STS_SUCCESS) {
831
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: GetDriverStatus failed\n");
832
        return -1;
833
    }
834

    
835
    /*
836
     * No frames ready. Don't try to extract.
837
     *
838
     * Empirical testing shows that ReadyListCount can be a damn lie,
839
     * and ProcOut still fails when count > 0. The same testing showed
840
     * that two more iterations were needed before ProcOutput would
841
     * succeed.
842
     */
843
    if (priv->output_ready < 2) {
844
        if (decoder_status.ReadyListCount != 0)
845
            priv->output_ready++;
846
        usleep(BASE_WAIT);
847
        av_log(avctx, AV_LOG_INFO, "CrystalHD: Filling pipeline.\n");
848
        return len;
849
    } else if (decoder_status.ReadyListCount == 0) {
850
        /*
851
         * After the pipeline is established, if we encounter a lack of frames
852
         * that probably means we're not giving the hardware enough time to
853
         * decode them, so start increasing the wait time at the end of a
854
         * decode call.
855
         */
856
        usleep(BASE_WAIT);
857
        priv->decode_wait += WAIT_UNIT;
858
        av_log(avctx, AV_LOG_INFO, "CrystalHD: No frames ready. Returning\n");
859
        return len;
860
    }
861

    
862
    do {
863
        rec_ret = receive_frame(avctx, data, data_size);
864
        if (rec_ret == RET_OK && *data_size == 0) {
865
            /*
866
             * This case is for when the encoded fields are stored
867
             * separately and we get a separate avpkt for each one. To keep
868
             * the pipeline stable, we should return nothing and wait for
869
             * the next time round to grab the second field.
870
             * H.264 PAFF is an example of this.
871
             */
872
            av_log(avctx, AV_LOG_VERBOSE, "Returning after first field.\n");
873
            avctx->has_b_frames--;
874
        } else if (rec_ret == RET_COPY_NEXT_FIELD) {
875
            /*
876
             * This case is for when the encoded fields are stored in a
877
             * single avpkt but the hardware returns then separately. Unless
878
             * we grab the second field before returning, we'll slip another
879
             * frame in the pipeline and if that happens a lot, we're sunk.
880
             * So we have to get that second field now.
881
             * Interlaced mpeg2 and vc1 are examples of this.
882
             */
883
            av_log(avctx, AV_LOG_VERBOSE, "Trying to get second field.\n");
884
            while (1) {
885
                usleep(priv->decode_wait);
886
                ret = DtsGetDriverStatus(dev, &decoder_status);
887
                if (ret == BC_STS_SUCCESS &&
888
                    decoder_status.ReadyListCount > 0) {
889
                    rec_ret = receive_frame(avctx, data, data_size);
890
                    if ((rec_ret == RET_OK && *data_size > 0) ||
891
                        rec_ret == RET_ERROR)
892
                        break;
893
                }
894
            }
895
            av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Got second field.\n");
896
        } else if (rec_ret == RET_SKIP_NEXT_COPY) {
897
            /*
898
             * Two input packets got turned into a field pair. Gawd.
899
             */
900
            av_log(avctx, AV_LOG_VERBOSE,
901
                   "Don't output on next decode call.\n");
902
            priv->skip_next_output = 1;
903
        }
904
        /*
905
         * If rec_ret == RET_COPY_AGAIN, that means that either we just handled
906
         * a FMT_CHANGE event and need to go around again for the actual frame,
907
         * we got a busy status and need to try again, or we're dealing with
908
         * packed b-frames, where the hardware strangely returns the packed
909
         * p-frame twice. We choose to keep the second copy as it carries the
910
         * valid pts.
911
         */
912
    } while (rec_ret == RET_COPY_AGAIN);
913
    usleep(priv->decode_wait);
914
    return len;
915
}
916

    
917

    
918
#if CONFIG_H264_CRYSTALHD_DECODER
919
AVCodec ff_h264_crystalhd_decoder = {
920
    .name           = "h264_crystalhd",
921
    .type           = AVMEDIA_TYPE_VIDEO,
922
    .id             = CODEC_ID_H264,
923
    .priv_data_size = sizeof(CHDContext),
924
    .init           = init,
925
    .close          = uninit,
926
    .decode         = decode,
927
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
928
    .flush          = flush,
929
    .long_name      = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (CrystalHD acceleration)"),
930
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
931
};
932
#endif
933

    
934
#if CONFIG_MPEG2_CRYSTALHD_DECODER
935
AVCodec ff_mpeg2_crystalhd_decoder = {
936
    .name           = "mpeg2_crystalhd",
937
    .type           = AVMEDIA_TYPE_VIDEO,
938
    .id             = CODEC_ID_MPEG2VIDEO,
939
    .priv_data_size = sizeof(CHDContext),
940
    .init           = init,
941
    .close          = uninit,
942
    .decode         = decode,
943
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
944
    .flush          = flush,
945
    .long_name      = NULL_IF_CONFIG_SMALL("MPEG-2 Video (CrystalHD acceleration)"),
946
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
947
};
948
#endif
949

    
950
#if CONFIG_MPEG4_CRYSTALHD_DECODER
951
AVCodec ff_mpeg4_crystalhd_decoder = {
952
    .name           = "mpeg4_crystalhd",
953
    .type           = AVMEDIA_TYPE_VIDEO,
954
    .id             = CODEC_ID_MPEG4,
955
    .priv_data_size = sizeof(CHDContext),
956
    .init           = init,
957
    .close          = uninit,
958
    .decode         = decode,
959
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
960
    .flush          = flush,
961
    .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 (CrystalHD acceleration)"),
962
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
963
};
964
#endif
965

    
966
#if CONFIG_MSMPEG4_CRYSTALHD_DECODER
967
AVCodec ff_msmpeg4_crystalhd_decoder = {
968
    .name           = "msmpeg4_crystalhd",
969
    .type           = AVMEDIA_TYPE_VIDEO,
970
    .id             = CODEC_ID_MSMPEG4V3,
971
    .priv_data_size = sizeof(CHDContext),
972
    .init           = init,
973
    .close          = uninit,
974
    .decode         = decode,
975
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
976
    .flush          = flush,
977
    .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 Microsoft variant version 3 (CrystalHD acceleration)"),
978
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
979
};
980
#endif
981

    
982
#if CONFIG_VC1_CRYSTALHD_DECODER
983
AVCodec ff_vc1_crystalhd_decoder = {
984
    .name           = "vc1_crystalhd",
985
    .type           = AVMEDIA_TYPE_VIDEO,
986
    .id             = CODEC_ID_VC1,
987
    .priv_data_size = sizeof(CHDContext),
988
    .init           = init,
989
    .close          = uninit,
990
    .decode         = decode,
991
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
992
    .flush          = flush,
993
    .long_name      = NULL_IF_CONFIG_SMALL("SMPTE VC-1 (CrystalHD acceleration)"),
994
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
995
};
996
#endif
997

    
998
#if CONFIG_WMV3_CRYSTALHD_DECODER
999
AVCodec ff_wmv3_crystalhd_decoder = {
1000
    .name           = "wmv3_crystalhd",
1001
    .type           = AVMEDIA_TYPE_VIDEO,
1002
    .id             = CODEC_ID_WMV3,
1003
    .priv_data_size = sizeof(CHDContext),
1004
    .init           = init,
1005
    .close          = uninit,
1006
    .decode         = decode,
1007
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1008
    .flush          = flush,
1009
    .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Video 9 (CrystalHD acceleration)"),
1010
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1011
};
1012
#endif