Statistics
| Branch: | Revision:

ffmpeg / libavcodec / crystalhd.c @ 4ab57cff

History | View | Annotate | Download (36.9 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
static inline CopyRet copy_frame(AVCodecContext *avctx,
510
                                 BC_DTS_PROC_OUT *output,
511
                                 void *data, int *data_size)
512
{
513
    BC_STATUS ret;
514
    BC_DTS_STATUS decoder_status;
515
    uint8_t confirmed_interlaced;
516
    uint8_t ignore_interlaced;
517
    uint8_t interlaced;
518

    
519
    CHDContext *priv = avctx->priv_data;
520
    int64_t pkt_pts  = AV_NOPTS_VALUE;
521
    uint8_t pic_type = 0;
522

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

    
527
    int width    = output->PicInfo.width;
528
    int height   = output->PicInfo.height;
529
    int bwidth;
530
    uint8_t *src = output->Ybuff;
531
    int sStride;
532
    uint8_t *dst;
533
    int dStride;
534

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

    
556
    ret = DtsGetDriverStatus(priv->dev, &decoder_status);
557
    if (ret != BC_STS_SUCCESS) {
558
        av_log(avctx, AV_LOG_ERROR,
559
               "CrystalHD: GetDriverStatus failed: %u\n", ret);
560
       return RET_ERROR;
561
    }
562

    
563
    /*
564
     * If we're expecting a second field, or we know that the next
565
     * picture has the same number as the current picture, then we're
566
     * definitely interlaced.
567
     *
568
     * Note that this test can return false negatives if the hardware
569
     * hasn't decoded the next picture or if there is a corruption in
570
     * the stream. (In either case a 0 will be returned for the next
571
     * picture number)
572
     */
573
    confirmed_interlaced = ((decoder_status.picNumFlags & ~0x40000000) ==
574
                            output->PicInfo.picture_number) ||
575
                            priv->need_second_field;
576

    
577
    /*
578
     * If we got a false negative for confirmed_interlaced on the first field,
579
     * we will realise our mistake here when we see that the picture number is that
580
     * of the previous picture. We cannot recover the frame and should discard the
581
     * second field to keep the correct number of output frames.
582
     */
583
    if (output->PicInfo.picture_number == priv->last_picture && !priv->need_second_field) {
584
        av_log(avctx, AV_LOG_WARNING,
585
               "Incorrectly guessed progressie frame. Discarding second field\n");
586
        /* Returning without providing a picture. */
587
        return RET_OK;
588
    }
589

    
590
    /*
591
     * Testing has, so far, shown that we can't trust the interlaced flag for
592
     * H.264 content when VDEC_FLAG_UNKNOWN_SRC is set.
593
     */
594
    ignore_interlaced = avctx->codec->id == CODEC_ID_H264 &&
595
                        (output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) &&
596
                        (pic_type == 0 || pic_type == PICT_FRAME ||
597
                         !confirmed_interlaced);
598
    interlaced        = (output->PicInfo.flags & VDEC_FLAG_INTERLACED_SRC) &&
599
                        (!ignore_interlaced || confirmed_interlaced);
600

    
601
    if (ignore_interlaced && (decoder_status.picNumFlags & ~0x40000000) == 0) {
602
        av_log(avctx, AV_LOG_WARNING,
603
               "Next picture number unknown. Assuming progressive frame.\n");
604
    }
605

    
606
    av_log(avctx, AV_LOG_VERBOSE, "Interlaced state: %d | ignore_interlaced %d\n",
607
           interlaced, ignore_interlaced);
608

    
609
    if (priv->pic.data[0] && !priv->need_second_field)
610
        avctx->release_buffer(avctx, &priv->pic);
611

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

    
614
    priv->pic.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE |
615
                             FF_BUFFER_HINTS_REUSABLE;
616
    if (!priv->pic.data[0]) {
617
        if (avctx->get_buffer(avctx, &priv->pic) < 0) {
618
            av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
619
            return RET_ERROR;
620
        }
621
    }
622

    
623
    bwidth = av_image_get_linesize(avctx->pix_fmt, width, 0);
624
    if (priv->is_70012) {
625
        int pStride;
626

    
627
        if (width <= 720)
628
            pStride = 720;
629
        else if (width <= 1280)
630
            pStride = 1280;
631
        else if (width <= 1080)
632
            pStride = 1080;
633
        sStride = av_image_get_linesize(avctx->pix_fmt, pStride, 0);
634
    } else {
635
        sStride = bwidth;
636
    }
637

    
638
    dStride = priv->pic.linesize[0];
639
    dst     = priv->pic.data[0];
640

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

    
643
    if (interlaced) {
644
        int dY = 0;
645
        int sY = 0;
646

    
647
        height /= 2;
648
        if (bottom_field) {
649
            av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: bottom field\n");
650
            dY = 1;
651
        } else {
652
            av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: top field\n");
653
            dY = 0;
654
        }
655

    
656
        for (sY = 0; sY < height; dY++, sY++) {
657
            memcpy(&(dst[dY * dStride]), &(src[sY * sStride]), bwidth);
658
            dY++;
659
        }
660
    } else {
661
        av_image_copy_plane(dst, dStride, src, sStride, bwidth, height);
662
    }
663

    
664
    priv->pic.interlaced_frame = interlaced;
665
    if (interlaced)
666
        priv->pic.top_field_first = !bottom_first;
667

    
668
    priv->pic.pkt_pts = pkt_pts;
669

    
670
    if (!priv->need_second_field) {
671
        *data_size       = sizeof(AVFrame);
672
        *(AVFrame *)data = priv->pic;
673
    }
674

    
675
    /*
676
     * Two types of PAFF content have been observed. One form causes the
677
     * hardware to return a field pair and the other individual fields,
678
     * even though the input is always individual fields. We must skip
679
     * copying on the next decode() call to maintain pipeline length in
680
     * the first case.
681
     */
682
    if (!interlaced && (output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) &&
683
        (pic_type == PICT_TOP_FIELD || pic_type == PICT_BOTTOM_FIELD)) {
684
        av_log(priv->avctx, AV_LOG_VERBOSE, "Fieldpair from two packets.\n");
685
        return RET_SKIP_NEXT_COPY;
686
    }
687

    
688
    /*
689
     * Testing has shown that in all cases where we don't want to return the
690
     * full frame immediately, VDEC_FLAG_UNKNOWN_SRC is set.
691
     */
692
    return priv->need_second_field &&
693
           !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ?
694
           RET_COPY_NEXT_FIELD : RET_OK;
695
}
696

    
697

    
698
static inline CopyRet receive_frame(AVCodecContext *avctx,
699
                                    void *data, int *data_size)
700
{
701
    BC_STATUS ret;
702
    BC_DTS_PROC_OUT output = {
703
        .PicInfo.width  = avctx->width,
704
        .PicInfo.height = avctx->height,
705
    };
706
    CHDContext *priv = avctx->priv_data;
707
    HANDLE dev       = priv->dev;
708

    
709
    *data_size = 0;
710

    
711
    // Request decoded data from the driver
712
    ret = DtsProcOutputNoCopy(dev, OUTPUT_PROC_TIMEOUT, &output);
713
    if (ret == BC_STS_FMT_CHANGE) {
714
        av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Initial format change\n");
715
        avctx->width  = output.PicInfo.width;
716
        avctx->height = output.PicInfo.height;
717
        return RET_COPY_AGAIN;
718
    } else if (ret == BC_STS_SUCCESS) {
719
        int copy_ret = -1;
720
        if (output.PoutFlags & BC_POUT_FLAGS_PIB_VALID) {
721
            if (priv->last_picture == -1) {
722
                /*
723
                 * Init to one less, so that the incrementing code doesn't
724
                 * need to be special-cased.
725
                 */
726
                priv->last_picture = output.PicInfo.picture_number - 1;
727
            }
728

    
729
            if (avctx->codec->id == CODEC_ID_MPEG4 &&
730
                output.PicInfo.timeStamp == 0) {
731
                av_log(avctx, AV_LOG_VERBOSE,
732
                       "CrystalHD: Not returning packed frame twice.\n");
733
                priv->last_picture++;
734
                DtsReleaseOutputBuffs(dev, NULL, FALSE);
735
                return RET_COPY_AGAIN;
736
            }
737

    
738
            print_frame_info(priv, &output);
739

    
740
            if (priv->last_picture + 1 < output.PicInfo.picture_number) {
741
                av_log(avctx, AV_LOG_WARNING,
742
                       "CrystalHD: Picture Number discontinuity\n");
743
                /*
744
                 * Have we lost frames? If so, we need to shrink the
745
                 * pipeline length appropriately.
746
                 *
747
                 * XXX: I have no idea what the semantics of this situation
748
                 * are so I don't even know if we've lost frames or which
749
                 * ones.
750
                 *
751
                 * In any case, only warn the first time.
752
                 */
753
               priv->last_picture = output.PicInfo.picture_number - 1;
754
            }
755

    
756
            copy_ret = copy_frame(avctx, &output, data, data_size);
757
            if (*data_size > 0) {
758
                avctx->has_b_frames--;
759
                priv->last_picture++;
760
                av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Pipeline length: %u\n",
761
                       avctx->has_b_frames);
762
            }
763
        } else {
764
            /*
765
             * An invalid frame has been consumed.
766
             */
767
            av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput succeeded with "
768
                                        "invalid PIB\n");
769
            avctx->has_b_frames--;
770
            copy_ret = RET_OK;
771
        }
772
        DtsReleaseOutputBuffs(dev, NULL, FALSE);
773

    
774
        return copy_ret;
775
    } else if (ret == BC_STS_BUSY) {
776
        return RET_COPY_AGAIN;
777
    } else {
778
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput failed %d\n", ret);
779
        return RET_ERROR;
780
    }
781
}
782

    
783

    
784
static int decode(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
785
{
786
    BC_STATUS ret;
787
    BC_DTS_STATUS decoder_status;
788
    CopyRet rec_ret;
789
    CHDContext *priv   = avctx->priv_data;
790
    HANDLE dev         = priv->dev;
791
    int len            = avpkt->size;
792
    uint8_t pic_type   = 0;
793

    
794
    av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: decode_frame\n");
795

    
796
    if (len) {
797
        int32_t tx_free = (int32_t)DtsTxFreeSize(dev);
798

    
799
        if (priv->parser) {
800
            uint8_t *pout = NULL;
801
            int psize = len;
802
            H264Context *h = priv->parser->priv_data;
803

    
804
            while (psize) {
805
                ret = av_parser_parse2(priv->parser, avctx, &pout, &psize,
806
                                       avpkt->data, len, avctx->pkt->pts,
807
                                       avctx->pkt->dts, len - psize);
808
            }
809
            av_log(avctx, AV_LOG_VERBOSE,
810
                   "CrystalHD: parser picture type %d\n",
811
                   h->s.picture_structure);
812
            pic_type = h->s.picture_structure;
813
        }
814

    
815
        if (len < tx_free - 1024) {
816
            /*
817
             * Despite being notionally opaque, either libcrystalhd or
818
             * the hardware itself will mangle pts values that are too
819
             * small or too large. The docs claim it should be in units
820
             * of 100ns. Given that we're nominally dealing with a black
821
             * box on both sides, any transform we do has no guarantee of
822
             * avoiding mangling so we need to build a mapping to values
823
             * we know will not be mangled.
824
             */
825
            uint64_t pts = opaque_list_push(priv, avctx->pkt->pts, pic_type);
826
            if (!pts) {
827
                return AVERROR(ENOMEM);
828
            }
829
            av_log(priv->avctx, AV_LOG_VERBOSE,
830
                   "input \"pts\": %"PRIu64"\n", pts);
831
            ret = DtsProcInput(dev, avpkt->data, len, pts, 0);
832
            if (ret == BC_STS_BUSY) {
833
                av_log(avctx, AV_LOG_WARNING,
834
                       "CrystalHD: ProcInput returned busy\n");
835
                usleep(BASE_WAIT);
836
                return AVERROR(EBUSY);
837
            } else if (ret != BC_STS_SUCCESS) {
838
                av_log(avctx, AV_LOG_ERROR,
839
                       "CrystalHD: ProcInput failed: %u\n", ret);
840
                return -1;
841
            }
842
            avctx->has_b_frames++;
843
        } else {
844
            av_log(avctx, AV_LOG_WARNING, "CrystalHD: Input buffer full\n");
845
            len = 0; // We didn't consume any bytes.
846
        }
847
    } else {
848
        av_log(avctx, AV_LOG_INFO, "CrystalHD: No more input data\n");
849
    }
850

    
851
    if (priv->skip_next_output) {
852
        av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Skipping next output.\n");
853
        priv->skip_next_output = 0;
854
        avctx->has_b_frames--;
855
        return len;
856
    }
857

    
858
    ret = DtsGetDriverStatus(dev, &decoder_status);
859
    if (ret != BC_STS_SUCCESS) {
860
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: GetDriverStatus failed\n");
861
        return -1;
862
    }
863

    
864
    /*
865
     * No frames ready. Don't try to extract.
866
     *
867
     * Empirical testing shows that ReadyListCount can be a damn lie,
868
     * and ProcOut still fails when count > 0. The same testing showed
869
     * that two more iterations were needed before ProcOutput would
870
     * succeed.
871
     */
872
    if (priv->output_ready < 2) {
873
        if (decoder_status.ReadyListCount != 0)
874
            priv->output_ready++;
875
        usleep(BASE_WAIT);
876
        av_log(avctx, AV_LOG_INFO, "CrystalHD: Filling pipeline.\n");
877
        return len;
878
    } else if (decoder_status.ReadyListCount == 0) {
879
        /*
880
         * After the pipeline is established, if we encounter a lack of frames
881
         * that probably means we're not giving the hardware enough time to
882
         * decode them, so start increasing the wait time at the end of a
883
         * decode call.
884
         */
885
        usleep(BASE_WAIT);
886
        priv->decode_wait += WAIT_UNIT;
887
        av_log(avctx, AV_LOG_INFO, "CrystalHD: No frames ready. Returning\n");
888
        return len;
889
    }
890

    
891
    do {
892
        rec_ret = receive_frame(avctx, data, data_size);
893
        if (rec_ret == RET_OK && *data_size == 0) {
894
            /*
895
             * This case is for when the encoded fields are stored
896
             * separately and we get a separate avpkt for each one. To keep
897
             * the pipeline stable, we should return nothing and wait for
898
             * the next time round to grab the second field.
899
             * H.264 PAFF is an example of this.
900
             */
901
            av_log(avctx, AV_LOG_VERBOSE, "Returning after first field.\n");
902
            avctx->has_b_frames--;
903
        } else if (rec_ret == RET_COPY_NEXT_FIELD) {
904
            /*
905
             * This case is for when the encoded fields are stored in a
906
             * single avpkt but the hardware returns then separately. Unless
907
             * we grab the second field before returning, we'll slip another
908
             * frame in the pipeline and if that happens a lot, we're sunk.
909
             * So we have to get that second field now.
910
             * Interlaced mpeg2 and vc1 are examples of this.
911
             */
912
            av_log(avctx, AV_LOG_VERBOSE, "Trying to get second field.\n");
913
            while (1) {
914
                usleep(priv->decode_wait);
915
                ret = DtsGetDriverStatus(dev, &decoder_status);
916
                if (ret == BC_STS_SUCCESS &&
917
                    decoder_status.ReadyListCount > 0) {
918
                    rec_ret = receive_frame(avctx, data, data_size);
919
                    if ((rec_ret == RET_OK && *data_size > 0) ||
920
                        rec_ret == RET_ERROR)
921
                        break;
922
                }
923
            }
924
            av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Got second field.\n");
925
        } else if (rec_ret == RET_SKIP_NEXT_COPY) {
926
            /*
927
             * Two input packets got turned into a field pair. Gawd.
928
             */
929
            av_log(avctx, AV_LOG_VERBOSE,
930
                   "Don't output on next decode call.\n");
931
            priv->skip_next_output = 1;
932
        }
933
        /*
934
         * If rec_ret == RET_COPY_AGAIN, that means that either we just handled
935
         * a FMT_CHANGE event and need to go around again for the actual frame,
936
         * we got a busy status and need to try again, or we're dealing with
937
         * packed b-frames, where the hardware strangely returns the packed
938
         * p-frame twice. We choose to keep the second copy as it carries the
939
         * valid pts.
940
         */
941
    } while (rec_ret == RET_COPY_AGAIN);
942
    usleep(priv->decode_wait);
943
    return len;
944
}
945

    
946

    
947
#if CONFIG_H264_CRYSTALHD_DECODER
948
AVCodec ff_h264_crystalhd_decoder = {
949
    .name           = "h264_crystalhd",
950
    .type           = AVMEDIA_TYPE_VIDEO,
951
    .id             = CODEC_ID_H264,
952
    .priv_data_size = sizeof(CHDContext),
953
    .init           = init,
954
    .close          = uninit,
955
    .decode         = decode,
956
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
957
    .flush          = flush,
958
    .long_name      = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (CrystalHD acceleration)"),
959
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
960
};
961
#endif
962

    
963
#if CONFIG_MPEG2_CRYSTALHD_DECODER
964
AVCodec ff_mpeg2_crystalhd_decoder = {
965
    .name           = "mpeg2_crystalhd",
966
    .type           = AVMEDIA_TYPE_VIDEO,
967
    .id             = CODEC_ID_MPEG2VIDEO,
968
    .priv_data_size = sizeof(CHDContext),
969
    .init           = init,
970
    .close          = uninit,
971
    .decode         = decode,
972
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
973
    .flush          = flush,
974
    .long_name      = NULL_IF_CONFIG_SMALL("MPEG-2 Video (CrystalHD acceleration)"),
975
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
976
};
977
#endif
978

    
979
#if CONFIG_MPEG4_CRYSTALHD_DECODER
980
AVCodec ff_mpeg4_crystalhd_decoder = {
981
    .name           = "mpeg4_crystalhd",
982
    .type           = AVMEDIA_TYPE_VIDEO,
983
    .id             = CODEC_ID_MPEG4,
984
    .priv_data_size = sizeof(CHDContext),
985
    .init           = init,
986
    .close          = uninit,
987
    .decode         = decode,
988
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
989
    .flush          = flush,
990
    .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 (CrystalHD acceleration)"),
991
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
992
};
993
#endif
994

    
995
#if CONFIG_MSMPEG4_CRYSTALHD_DECODER
996
AVCodec ff_msmpeg4_crystalhd_decoder = {
997
    .name           = "msmpeg4_crystalhd",
998
    .type           = AVMEDIA_TYPE_VIDEO,
999
    .id             = CODEC_ID_MSMPEG4V3,
1000
    .priv_data_size = sizeof(CHDContext),
1001
    .init           = init,
1002
    .close          = uninit,
1003
    .decode         = decode,
1004
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1005
    .flush          = flush,
1006
    .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 Microsoft variant version 3 (CrystalHD acceleration)"),
1007
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1008
};
1009
#endif
1010

    
1011
#if CONFIG_VC1_CRYSTALHD_DECODER
1012
AVCodec ff_vc1_crystalhd_decoder = {
1013
    .name           = "vc1_crystalhd",
1014
    .type           = AVMEDIA_TYPE_VIDEO,
1015
    .id             = CODEC_ID_VC1,
1016
    .priv_data_size = sizeof(CHDContext),
1017
    .init           = init,
1018
    .close          = uninit,
1019
    .decode         = decode,
1020
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1021
    .flush          = flush,
1022
    .long_name      = NULL_IF_CONFIG_SMALL("SMPTE VC-1 (CrystalHD acceleration)"),
1023
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1024
};
1025
#endif
1026

    
1027
#if CONFIG_WMV3_CRYSTALHD_DECODER
1028
AVCodec ff_wmv3_crystalhd_decoder = {
1029
    .name           = "wmv3_crystalhd",
1030
    .type           = AVMEDIA_TYPE_VIDEO,
1031
    .id             = CODEC_ID_WMV3,
1032
    .priv_data_size = sizeof(CHDContext),
1033
    .init           = init,
1034
    .close          = uninit,
1035
    .decode         = decode,
1036
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1037
    .flush          = flush,
1038
    .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Video 9 (CrystalHD acceleration)"),
1039
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1040
};
1041
#endif