Statistics
| Branch: | Revision:

ffmpeg / libavcodec / crystalhd.c @ f6421e0b

History | View | Annotate | Download (34.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
} OpaqueList;
118

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

    
124
    AVCodecParserContext *parser;
125

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

    
135
    uint64_t last_picture;
136

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

    
141

    
142
/*****************************************************************************
143
 * Helper functions
144
 ****************************************************************************/
145

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

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

    
207

    
208
/*****************************************************************************
209
 * OpaqueList functions
210
 ****************************************************************************/
211

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

    
230
    return newNode->fake_timestamp;
231
}
232

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

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

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

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

    
260
        node->next = NULL;
261
        return node;
262
    }
263

    
264
    /*
265
     * The list is processed at arm's length so that we have the
266
     * previous element available to rewrite its next pointer.
267
     */
268
    while (node->next) {
269
        OpaqueList *current = node->next;
270
        if (current->fake_timestamp == fake_timestamp) {
271
            node->next = current->next;
272

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

    
276
            current->next = NULL;
277
            return current;
278
        } else {
279
            node = current;
280
        }
281
    }
282

    
283
    av_log(priv->avctx, AV_LOG_VERBOSE,
284
           "CrystalHD: Couldn't match fake_timestamp.\n");
285
    return NULL;
286
}
287

    
288

    
289
/*****************************************************************************
290
 * Video decoder API function definitions
291
 ****************************************************************************/
292

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

    
297
    avctx->has_b_frames     = 0;
298
    priv->last_picture      = -1;
299
    priv->output_ready      = 0;
300
    priv->need_second_field = 0;
301
    priv->skip_next_output  = 0;
302
    priv->decode_wait       = BASE_WAIT;
303

    
304
    if (priv->pic.data[0])
305
        avctx->release_buffer(avctx, &priv->pic);
306

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

    
311

    
312
static av_cold int uninit(AVCodecContext *avctx)
313
{
314
    CHDContext *priv = avctx->priv_data;
315
    HANDLE device;
316

    
317
    device = priv->dev;
318
    DtsStopDecoder(device);
319
    DtsCloseDecoder(device);
320
    DtsDeviceClose(device);
321

    
322
    av_parser_close(priv->parser);
323

    
324
    av_free(priv->sps_pps_buf);
325

    
326
    if (priv->pic.data[0])
327
        avctx->release_buffer(avctx, &priv->pic);
328

    
329
    if (priv->head) {
330
       OpaqueList *node = priv->head;
331
       while (node) {
332
          OpaqueList *next = node->next;
333
          av_free(node);
334
          node = next;
335
       }
336
    }
337

    
338
    return 0;
339
}
340

    
341

    
342
static av_cold int init(AVCodecContext *avctx)
343
{
344
    CHDContext* priv;
345
    BC_STATUS ret;
346
    BC_INFO_CRYSTAL version;
347
    BC_INPUT_FORMAT format = {
348
        .FGTEnable   = FALSE,
349
        .Progressive = TRUE,
350
        .OptFlags    = 0x80000000 | vdecFrameRate59_94 | 0x40,
351
        .width       = avctx->width,
352
        .height      = avctx->height,
353
    };
354

    
355
    BC_MEDIA_SUBTYPE subtype;
356

    
357
    uint32_t mode = DTS_PLAYBACK_MODE |
358
                    DTS_LOAD_FILE_PLAY_FW |
359
                    DTS_SKIP_TX_CHK_CPB |
360
                    DTS_PLAYBACK_DROP_RPT_MODE |
361
                    DTS_SINGLE_THREADED_MODE |
362
                    DTS_DFLT_RESOLUTION(vdecRESOLUTION_1080p23_976);
363

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

    
367
    avctx->pix_fmt = PIX_FMT_YUYV422;
368

    
369
    /* Initialize the library */
370
    priv               = avctx->priv_data;
371
    priv->avctx        = avctx;
372
    priv->is_nal       = avctx->extradata_size > 0 && *(avctx->extradata) == 1;
373
    priv->last_picture = -1;
374
    priv->decode_wait  = BASE_WAIT;
375

    
376
    subtype = id2subtype(priv, avctx->codec->id);
377
    switch (subtype) {
378
    case BC_MSUBTYPE_AVC1:
379
        {
380
            uint8_t *dummy_p;
381
            int dummy_int;
382
            AVBitStreamFilterContext *bsfc;
383

    
384
            uint32_t orig_data_size = avctx->extradata_size;
385
            uint8_t *orig_data = av_malloc(orig_data_size);
386
            if (!orig_data) {
387
                av_log(avctx, AV_LOG_ERROR,
388
                       "Failed to allocate copy of extradata\n");
389
                return AVERROR(ENOMEM);
390
            }
391
            memcpy(orig_data, avctx->extradata, orig_data_size);
392

    
393

    
394
            bsfc = av_bitstream_filter_init("h264_mp4toannexb");
395
            if (!bsfc) {
396
                av_log(avctx, AV_LOG_ERROR,
397
                       "Cannot open the h264_mp4toannexb BSF!\n");
398
                av_free(orig_data);
399
                return AVERROR_BSF_NOT_FOUND;
400
            }
401
            av_bitstream_filter_filter(bsfc, avctx, NULL, &dummy_p,
402
                                       &dummy_int, NULL, 0, 0);
403
            av_bitstream_filter_close(bsfc);
404

    
405
            priv->sps_pps_buf     = avctx->extradata;
406
            priv->sps_pps_size    = avctx->extradata_size;
407
            avctx->extradata      = orig_data;
408
            avctx->extradata_size = orig_data_size;
409

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

    
434
    /* Get a decoder instance */
435
    av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: starting up\n");
436
    // Initialize the Link and Decoder devices
437
    ret = DtsDeviceOpen(&priv->dev, mode);
438
    if (ret != BC_STS_SUCCESS) {
439
        av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: DtsDeviceOpen failed\n");
440
        goto fail;
441
    }
442

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

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

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

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

    
470
    ret = DtsSetColorSpace(priv->dev, OUTPUT_MODE422_YUY2);
471
    if (ret != BC_STS_SUCCESS) {
472
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsSetColorSpace failed\n");
473
        goto fail;
474
    }
475
    ret = DtsStartDecoder(priv->dev);
476
    if (ret != BC_STS_SUCCESS) {
477
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartDecoder failed\n");
478
        goto fail;
479
    }
480
    ret = DtsStartCapture(priv->dev);
481
    if (ret != BC_STS_SUCCESS) {
482
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartCapture failed\n");
483
        goto fail;
484
    }
485

    
486
    if (avctx->codec->id == CODEC_ID_H264) {
487
        priv->parser = av_parser_init(avctx->codec->id);
488
        if (!priv->parser)
489
            av_log(avctx, AV_LOG_WARNING,
490
                   "Cannot open the h.264 parser! Interlaced h.264 content "
491
                   "will not be detected reliably.\n");
492
    }
493
    av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Init complete.\n");
494

    
495
    return 0;
496

    
497
 fail:
498
    uninit(avctx);
499
    return -1;
500
}
501

    
502

    
503
/*
504
 * The CrystalHD doesn't report interlaced H.264 content in a way that allows
505
 * us to distinguish between specific cases that require different handling.
506
 * So, for now, we have to hard-code the behaviour we want.
507
 *
508
 * The default behaviour is to assume MBAFF with input and output fieldpairs.
509
 *
510
 * Define ASSUME_PAFF_OVER_MBAFF to treat input as PAFF with separate input
511
 * and output fields.
512
 *
513
 * Define ASSUME_TWO_INPUTS_ONE_OUTPUT to treat input as separate fields but
514
 * output as a single fieldpair.
515
 *
516
 * Define both to mess up your playback.
517
 */
518
#define ASSUME_PAFF_OVER_MBAFF 0
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
                                 uint8_t second_field)
524
{
525
    BC_STATUS ret;
526
    BC_DTS_STATUS decoder_status;
527
    uint8_t is_paff;
528
    uint8_t next_frame_same;
529
    uint8_t interlaced;
530

    
531
    CHDContext *priv = avctx->priv_data;
532
    int64_t pkt_pts  = AV_NOPTS_VALUE;
533

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

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

    
546
    if (output->PicInfo.timeStamp != 0) {
547
        OpaqueList *node = opaque_list_pop(priv, output->PicInfo.timeStamp);
548
        if (node) {
549
            pkt_pts = node->reordered_opaque;
550
            av_free(node);
551
        }
552
        av_log(avctx, AV_LOG_VERBOSE, "output \"pts\": %"PRIu64"\n",
553
               output->PicInfo.timeStamp);
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
    is_paff           = ASSUME_PAFF_OVER_MBAFF ||
564
                        !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC);
565
    next_frame_same   = output->PicInfo.picture_number ==
566
                        (decoder_status.picNumFlags & ~0x40000000);
567
    interlaced        = ((output->PicInfo.flags &
568
                          VDEC_FLAG_INTERLACED_SRC) && is_paff) ||
569
                         next_frame_same || bottom_field || second_field;
570

    
571
    av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: next_frame_same: %u | %u | %u\n",
572
           next_frame_same, output->PicInfo.picture_number,
573
           decoder_status.picNumFlags & ~0x40000000);
574

    
575
    if (priv->pic.data[0] && !priv->need_second_field)
576
        avctx->release_buffer(avctx, &priv->pic);
577

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

    
580
    priv->pic.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE |
581
                             FF_BUFFER_HINTS_REUSABLE;
582
    if (!priv->pic.data[0]) {
583
        if (avctx->get_buffer(avctx, &priv->pic) < 0) {
584
            av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
585
            return RET_ERROR;
586
        }
587
    }
588

    
589
    bwidth = av_image_get_linesize(avctx->pix_fmt, width, 0);
590
    if (priv->is_70012) {
591
        int pStride;
592

    
593
        if (width <= 720)
594
            pStride = 720;
595
        else if (width <= 1280)
596
            pStride = 1280;
597
        else if (width <= 1080)
598
            pStride = 1080;
599
        sStride = av_image_get_linesize(avctx->pix_fmt, pStride, 0);
600
    } else {
601
        sStride = bwidth;
602
    }
603

    
604
    dStride = priv->pic.linesize[0];
605
    dst     = priv->pic.data[0];
606

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

    
609
    if (interlaced) {
610
        int dY = 0;
611
        int sY = 0;
612

    
613
        height /= 2;
614
        if (bottom_field) {
615
            av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: bottom field\n");
616
            dY = 1;
617
        } else {
618
            av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: top field\n");
619
            dY = 0;
620
        }
621

    
622
        for (sY = 0; sY < height; dY++, sY++) {
623
            memcpy(&(dst[dY * dStride]), &(src[sY * sStride]), bwidth);
624
            dY++;
625
        }
626
    } else {
627
        av_image_copy_plane(dst, dStride, src, sStride, bwidth, height);
628
    }
629

    
630
    priv->pic.interlaced_frame = interlaced;
631
    if (interlaced)
632
        priv->pic.top_field_first = !bottom_first;
633

    
634
    priv->pic.pkt_pts = pkt_pts;
635

    
636
    if (!priv->need_second_field) {
637
        *data_size       = sizeof(AVFrame);
638
        *(AVFrame *)data = priv->pic;
639
    }
640

    
641
    if (ASSUME_TWO_INPUTS_ONE_OUTPUT &&
642
        output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) {
643
        av_log(priv->avctx, AV_LOG_VERBOSE, "Fieldpair from two packets.\n");
644
        return RET_SKIP_NEXT_COPY;
645
    }
646

    
647
    /*
648
     * Testing has shown that in all cases where we don't want to return the
649
     * full frame immediately, VDEC_FLAG_UNKNOWN_SRC is set.
650
     */
651
    return priv->need_second_field &&
652
           !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ?
653
           RET_COPY_NEXT_FIELD : RET_OK;
654
}
655

    
656

    
657
static inline CopyRet receive_frame(AVCodecContext *avctx,
658
                                    void *data, int *data_size,
659
                                    uint8_t second_field)
660
{
661
    BC_STATUS ret;
662
    BC_DTS_PROC_OUT output = {
663
        .PicInfo.width  = avctx->width,
664
        .PicInfo.height = avctx->height,
665
    };
666
    CHDContext *priv = avctx->priv_data;
667
    HANDLE dev       = priv->dev;
668

    
669
    *data_size = 0;
670

    
671
    // Request decoded data from the driver
672
    ret = DtsProcOutputNoCopy(dev, OUTPUT_PROC_TIMEOUT, &output);
673
    if (ret == BC_STS_FMT_CHANGE) {
674
        av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Initial format change\n");
675
        avctx->width  = output.PicInfo.width;
676
        avctx->height = output.PicInfo.height;
677
        return RET_COPY_AGAIN;
678
    } else if (ret == BC_STS_SUCCESS) {
679
        int copy_ret = -1;
680
        if (output.PoutFlags & BC_POUT_FLAGS_PIB_VALID) {
681
            if (priv->last_picture == -1) {
682
                /*
683
                 * Init to one less, so that the incrementing code doesn't
684
                 * need to be special-cased.
685
                 */
686
                priv->last_picture = output.PicInfo.picture_number - 1;
687
            }
688

    
689
            if (avctx->codec->id == CODEC_ID_MPEG4 &&
690
                output.PicInfo.timeStamp == 0) {
691
                av_log(avctx, AV_LOG_VERBOSE,
692
                       "CrystalHD: Not returning packed frame twice.\n");
693
                priv->last_picture++;
694
                DtsReleaseOutputBuffs(dev, NULL, FALSE);
695
                return RET_COPY_AGAIN;
696
            }
697

    
698
            print_frame_info(priv, &output);
699

    
700
            if (priv->last_picture + 1 < output.PicInfo.picture_number) {
701
                av_log(avctx, AV_LOG_WARNING,
702
                       "CrystalHD: Picture Number discontinuity\n");
703
                /*
704
                 * Have we lost frames? If so, we need to shrink the
705
                 * pipeline length appropriately.
706
                 *
707
                 * XXX: I have no idea what the semantics of this situation
708
                 * are so I don't even know if we've lost frames or which
709
                 * ones.
710
                 *
711
                 * In any case, only warn the first time.
712
                 */
713
               priv->last_picture = output.PicInfo.picture_number - 1;
714
            }
715

    
716
            copy_ret = copy_frame(avctx, &output, data, data_size, second_field);
717
            if (*data_size > 0) {
718
                avctx->has_b_frames--;
719
                priv->last_picture++;
720
                av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Pipeline length: %u\n",
721
                       avctx->has_b_frames);
722
            }
723
        } else {
724
            /*
725
             * An invalid frame has been consumed.
726
             */
727
            av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput succeeded with "
728
                                        "invalid PIB\n");
729
            avctx->has_b_frames--;
730
            copy_ret = RET_OK;
731
        }
732
        DtsReleaseOutputBuffs(dev, NULL, FALSE);
733

    
734
        return copy_ret;
735
    } else if (ret == BC_STS_BUSY) {
736
        return RET_COPY_AGAIN;
737
    } else {
738
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput failed %d\n", ret);
739
        return RET_ERROR;
740
    }
741
}
742

    
743

    
744
static int decode(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
745
{
746
    BC_STATUS ret;
747
    BC_DTS_STATUS decoder_status;
748
    CopyRet rec_ret;
749
    CHDContext *priv   = avctx->priv_data;
750
    HANDLE dev         = priv->dev;
751
    int len            = avpkt->size;
752
    uint8_t pic_type   = 0;
753

    
754
    av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: decode_frame\n");
755

    
756
    if (len) {
757
        int32_t tx_free = (int32_t)DtsTxFreeSize(dev);
758

    
759
        if (priv->parser) {
760
            uint8_t *pout;
761
            int psize = len;
762
            H264Context *h = priv->parser->priv_data;
763

    
764
            while (psize)
765
                ret = av_parser_parse2(priv->parser, avctx, &pout, &psize,
766
                                       avpkt->data, len, avctx->pkt->pts,
767
                                       avctx->pkt->dts, len - psize);
768
            av_log(avctx, AV_LOG_VERBOSE,
769
                   "CrystalHD: parser picture type %d\n",
770
                   h->s.picture_structure);
771
            pic_type = h->s.picture_structure;
772
        }
773

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

    
810
    if (priv->skip_next_output) {
811
        av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Skipping next output.\n");
812
        priv->skip_next_output = 0;
813
        avctx->has_b_frames--;
814
        return len;
815
    }
816

    
817
    ret = DtsGetDriverStatus(dev, &decoder_status);
818
    if (ret != BC_STS_SUCCESS) {
819
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: GetDriverStatus failed\n");
820
        return -1;
821
    }
822

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

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

    
905

    
906
#if CONFIG_H264_CRYSTALHD_DECODER
907
AVCodec ff_h264_crystalhd_decoder = {
908
    .name           = "h264_crystalhd",
909
    .type           = AVMEDIA_TYPE_VIDEO,
910
    .id             = CODEC_ID_H264,
911
    .priv_data_size = sizeof(CHDContext),
912
    .init           = init,
913
    .close          = uninit,
914
    .decode         = decode,
915
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
916
    .flush          = flush,
917
    .long_name      = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (CrystalHD acceleration)"),
918
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
919
};
920
#endif
921

    
922
#if CONFIG_MPEG2_CRYSTALHD_DECODER
923
AVCodec ff_mpeg2_crystalhd_decoder = {
924
    .name           = "mpeg2_crystalhd",
925
    .type           = AVMEDIA_TYPE_VIDEO,
926
    .id             = CODEC_ID_MPEG2VIDEO,
927
    .priv_data_size = sizeof(CHDContext),
928
    .init           = init,
929
    .close          = uninit,
930
    .decode         = decode,
931
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
932
    .flush          = flush,
933
    .long_name      = NULL_IF_CONFIG_SMALL("MPEG-2 Video (CrystalHD acceleration)"),
934
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
935
};
936
#endif
937

    
938
#if CONFIG_MPEG4_CRYSTALHD_DECODER
939
AVCodec ff_mpeg4_crystalhd_decoder = {
940
    .name           = "mpeg4_crystalhd",
941
    .type           = AVMEDIA_TYPE_VIDEO,
942
    .id             = CODEC_ID_MPEG4,
943
    .priv_data_size = sizeof(CHDContext),
944
    .init           = init,
945
    .close          = uninit,
946
    .decode         = decode,
947
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
948
    .flush          = flush,
949
    .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 (CrystalHD acceleration)"),
950
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
951
};
952
#endif
953

    
954
#if CONFIG_MSMPEG4_CRYSTALHD_DECODER
955
AVCodec ff_msmpeg4_crystalhd_decoder = {
956
    .name           = "msmpeg4_crystalhd",
957
    .type           = AVMEDIA_TYPE_VIDEO,
958
    .id             = CODEC_ID_MSMPEG4V3,
959
    .priv_data_size = sizeof(CHDContext),
960
    .init           = init,
961
    .close          = uninit,
962
    .decode         = decode,
963
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
964
    .flush          = flush,
965
    .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 Microsoft variant version 3 (CrystalHD acceleration)"),
966
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
967
};
968
#endif
969

    
970
#if CONFIG_VC1_CRYSTALHD_DECODER
971
AVCodec ff_vc1_crystalhd_decoder = {
972
    .name           = "vc1_crystalhd",
973
    .type           = AVMEDIA_TYPE_VIDEO,
974
    .id             = CODEC_ID_VC1,
975
    .priv_data_size = sizeof(CHDContext),
976
    .init           = init,
977
    .close          = uninit,
978
    .decode         = decode,
979
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
980
    .flush          = flush,
981
    .long_name      = NULL_IF_CONFIG_SMALL("SMPTE VC-1 (CrystalHD acceleration)"),
982
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
983
};
984
#endif
985

    
986
#if CONFIG_WMV3_CRYSTALHD_DECODER
987
AVCodec ff_wmv3_crystalhd_decoder = {
988
    .name           = "wmv3_crystalhd",
989
    .type           = AVMEDIA_TYPE_VIDEO,
990
    .id             = CODEC_ID_WMV3,
991
    .priv_data_size = sizeof(CHDContext),
992
    .init           = init,
993
    .close          = uninit,
994
    .decode         = decode,
995
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
996
    .flush          = flush,
997
    .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Video 9 (CrystalHD acceleration)"),
998
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
999
};
1000
#endif