]> git.sesse.net Git - ffmpeg/blob - libavcodec/crystalhd.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavcodec / crystalhd.c
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 #include "libavutil/opt.h"
91
92 /** Timeout parameter passed to DtsProcOutput() in us */
93 #define OUTPUT_PROC_TIMEOUT 50
94 /** Step between fake timestamps passed to hardware in units of 100ns */
95 #define TIMESTAMP_UNIT 100000
96 /** Initial value in us of the wait in decode() */
97 #define BASE_WAIT 10000
98 /** Increment in us to adjust wait in decode() */
99 #define WAIT_UNIT 1000
100
101
102 /*****************************************************************************
103  * Module private data
104  ****************************************************************************/
105
106 typedef enum {
107     RET_ERROR           = -1,
108     RET_OK              = 0,
109     RET_COPY_AGAIN      = 1,
110     RET_SKIP_NEXT_COPY  = 2,
111     RET_COPY_NEXT_FIELD = 3,
112 } CopyRet;
113
114 typedef struct OpaqueList {
115     struct OpaqueList *next;
116     uint64_t fake_timestamp;
117     uint64_t reordered_opaque;
118     uint8_t pic_type;
119 } OpaqueList;
120
121 typedef struct {
122     AVClass *av_class;
123     AVCodecContext *avctx;
124     AVFrame pic;
125     HANDLE dev;
126
127     AVBitStreamFilterContext *bsfc;
128     AVCodecParserContext *parser;
129
130     uint8_t is_70012;
131     uint8_t *sps_pps_buf;
132     uint32_t sps_pps_size;
133     uint8_t is_nal;
134     uint8_t output_ready;
135     uint8_t need_second_field;
136     uint8_t skip_next_output;
137     uint64_t decode_wait;
138
139     uint64_t last_picture;
140
141     OpaqueList *head;
142     OpaqueList *tail;
143
144     /* Options */
145     uint32_t sWidth;
146     uint8_t bframe_bug;
147 } CHDContext;
148
149 static const AVOption options[] = {
150     { "crystalhd_downscale_width",
151       "Turn on downscaling to the specified width",
152       offsetof(CHDContext, sWidth),
153       FF_OPT_TYPE_INT, 0, 0, UINT32_MAX,
154       AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM, },
155     { NULL, },
156 };
157
158
159 /*****************************************************************************
160  * Helper functions
161  ****************************************************************************/
162
163 static inline BC_MEDIA_SUBTYPE id2subtype(CHDContext *priv, enum CodecID id)
164 {
165     switch (id) {
166     case CODEC_ID_MPEG4:
167         return BC_MSUBTYPE_DIVX;
168     case CODEC_ID_MSMPEG4V3:
169         return BC_MSUBTYPE_DIVX311;
170     case CODEC_ID_MPEG2VIDEO:
171         return BC_MSUBTYPE_MPEG2VIDEO;
172     case CODEC_ID_VC1:
173         return BC_MSUBTYPE_VC1;
174     case CODEC_ID_WMV3:
175         return BC_MSUBTYPE_WMV3;
176     case CODEC_ID_H264:
177         return priv->is_nal ? BC_MSUBTYPE_AVC1 : BC_MSUBTYPE_H264;
178     default:
179         return BC_MSUBTYPE_INVALID;
180     }
181 }
182
183 static inline void print_frame_info(CHDContext *priv, BC_DTS_PROC_OUT *output)
184 {
185     av_log(priv->avctx, AV_LOG_VERBOSE, "\tYBuffSz: %u\n", output->YbuffSz);
186     av_log(priv->avctx, AV_LOG_VERBOSE, "\tYBuffDoneSz: %u\n",
187            output->YBuffDoneSz);
188     av_log(priv->avctx, AV_LOG_VERBOSE, "\tUVBuffDoneSz: %u\n",
189            output->UVBuffDoneSz);
190     av_log(priv->avctx, AV_LOG_VERBOSE, "\tTimestamp: %"PRIu64"\n",
191            output->PicInfo.timeStamp);
192     av_log(priv->avctx, AV_LOG_VERBOSE, "\tPicture Number: %u\n",
193            output->PicInfo.picture_number);
194     av_log(priv->avctx, AV_LOG_VERBOSE, "\tWidth: %u\n",
195            output->PicInfo.width);
196     av_log(priv->avctx, AV_LOG_VERBOSE, "\tHeight: %u\n",
197            output->PicInfo.height);
198     av_log(priv->avctx, AV_LOG_VERBOSE, "\tChroma: 0x%03x\n",
199            output->PicInfo.chroma_format);
200     av_log(priv->avctx, AV_LOG_VERBOSE, "\tPulldown: %u\n",
201            output->PicInfo.pulldown);
202     av_log(priv->avctx, AV_LOG_VERBOSE, "\tFlags: 0x%08x\n",
203            output->PicInfo.flags);
204     av_log(priv->avctx, AV_LOG_VERBOSE, "\tFrame Rate/Res: %u\n",
205            output->PicInfo.frame_rate);
206     av_log(priv->avctx, AV_LOG_VERBOSE, "\tAspect Ratio: %u\n",
207            output->PicInfo.aspect_ratio);
208     av_log(priv->avctx, AV_LOG_VERBOSE, "\tColor Primaries: %u\n",
209            output->PicInfo.colour_primaries);
210     av_log(priv->avctx, AV_LOG_VERBOSE, "\tMetaData: %u\n",
211            output->PicInfo.picture_meta_payload);
212     av_log(priv->avctx, AV_LOG_VERBOSE, "\tSession Number: %u\n",
213            output->PicInfo.sess_num);
214     av_log(priv->avctx, AV_LOG_VERBOSE, "\tycom: %u\n",
215            output->PicInfo.ycom);
216     av_log(priv->avctx, AV_LOG_VERBOSE, "\tCustom Aspect: %u\n",
217            output->PicInfo.custom_aspect_ratio_width_height);
218     av_log(priv->avctx, AV_LOG_VERBOSE, "\tFrames to Drop: %u\n",
219            output->PicInfo.n_drop);
220     av_log(priv->avctx, AV_LOG_VERBOSE, "\tH264 Valid Fields: 0x%08x\n",
221            output->PicInfo.other.h264.valid);
222 }
223
224
225 /*****************************************************************************
226  * OpaqueList functions
227  ****************************************************************************/
228
229 static uint64_t opaque_list_push(CHDContext *priv, uint64_t reordered_opaque,
230                                  uint8_t pic_type)
231 {
232     OpaqueList *newNode = av_mallocz(sizeof (OpaqueList));
233     if (!newNode) {
234         av_log(priv->avctx, AV_LOG_ERROR,
235                "Unable to allocate new node in OpaqueList.\n");
236         return 0;
237     }
238     if (!priv->head) {
239         newNode->fake_timestamp = TIMESTAMP_UNIT;
240         priv->head              = newNode;
241     } else {
242         newNode->fake_timestamp = priv->tail->fake_timestamp + TIMESTAMP_UNIT;
243         priv->tail->next        = newNode;
244     }
245     priv->tail = newNode;
246     newNode->reordered_opaque = reordered_opaque;
247     newNode->pic_type = pic_type;
248
249     return newNode->fake_timestamp;
250 }
251
252 /*
253  * The OpaqueList is built in decode order, while elements will be removed
254  * in presentation order. If frames are reordered, this means we must be
255  * able to remove elements that are not the first element.
256  *
257  * Returned node must be freed by caller.
258  */
259 static OpaqueList *opaque_list_pop(CHDContext *priv, uint64_t fake_timestamp)
260 {
261     OpaqueList *node = priv->head;
262
263     if (!priv->head) {
264         av_log(priv->avctx, AV_LOG_ERROR,
265                "CrystalHD: Attempted to query non-existent timestamps.\n");
266         return NULL;
267     }
268
269     /*
270      * The first element is special-cased because we have to manipulate
271      * the head pointer rather than the previous element in the list.
272      */
273     if (priv->head->fake_timestamp == fake_timestamp) {
274         priv->head = node->next;
275
276         if (!priv->head->next)
277             priv->tail = priv->head;
278
279         node->next = NULL;
280         return node;
281     }
282
283     /*
284      * The list is processed at arm's length so that we have the
285      * previous element available to rewrite its next pointer.
286      */
287     while (node->next) {
288         OpaqueList *current = node->next;
289         if (current->fake_timestamp == fake_timestamp) {
290             node->next = current->next;
291
292             if (!node->next)
293                priv->tail = node;
294
295             current->next = NULL;
296             return current;
297         } else {
298             node = current;
299         }
300     }
301
302     av_log(priv->avctx, AV_LOG_VERBOSE,
303            "CrystalHD: Couldn't match fake_timestamp.\n");
304     return NULL;
305 }
306
307
308 /*****************************************************************************
309  * Video decoder API function definitions
310  ****************************************************************************/
311
312 static void flush(AVCodecContext *avctx)
313 {
314     CHDContext *priv = avctx->priv_data;
315
316     avctx->has_b_frames     = 0;
317     priv->last_picture      = -1;
318     priv->output_ready      = 0;
319     priv->need_second_field = 0;
320     priv->skip_next_output  = 0;
321     priv->decode_wait       = BASE_WAIT;
322
323     if (priv->pic.data[0])
324         avctx->release_buffer(avctx, &priv->pic);
325
326     /* Flush mode 4 flushes all software and hardware buffers. */
327     DtsFlushInput(priv->dev, 4);
328 }
329
330
331 static av_cold int uninit(AVCodecContext *avctx)
332 {
333     CHDContext *priv = avctx->priv_data;
334     HANDLE device;
335
336     device = priv->dev;
337     DtsStopDecoder(device);
338     DtsCloseDecoder(device);
339     DtsDeviceClose(device);
340
341     av_parser_close(priv->parser);
342     if (priv->bsfc) {
343         av_bitstream_filter_close(priv->bsfc);
344     }
345
346     av_free(priv->sps_pps_buf);
347
348     if (priv->pic.data[0])
349         avctx->release_buffer(avctx, &priv->pic);
350
351     if (priv->head) {
352        OpaqueList *node = priv->head;
353        while (node) {
354           OpaqueList *next = node->next;
355           av_free(node);
356           node = next;
357        }
358     }
359
360     return 0;
361 }
362
363
364 static av_cold int init(AVCodecContext *avctx)
365 {
366     CHDContext* priv;
367     BC_STATUS ret;
368     BC_INFO_CRYSTAL version;
369     BC_INPUT_FORMAT format = {
370         .FGTEnable   = FALSE,
371         .Progressive = TRUE,
372         .OptFlags    = 0x80000000 | vdecFrameRate59_94 | 0x40,
373         .width       = avctx->width,
374         .height      = avctx->height,
375     };
376
377     BC_MEDIA_SUBTYPE subtype;
378
379     uint32_t mode = DTS_PLAYBACK_MODE |
380                     DTS_LOAD_FILE_PLAY_FW |
381                     DTS_SKIP_TX_CHK_CPB |
382                     DTS_PLAYBACK_DROP_RPT_MODE |
383                     DTS_SINGLE_THREADED_MODE |
384                     DTS_DFLT_RESOLUTION(vdecRESOLUTION_1080p23_976);
385
386     av_log(avctx, AV_LOG_VERBOSE, "CrystalHD Init for %s\n",
387            avctx->codec->name);
388
389     avctx->pix_fmt = PIX_FMT_YUYV422;
390
391     /* Initialize the library */
392     priv               = avctx->priv_data;
393     priv->avctx        = avctx;
394     priv->is_nal       = avctx->extradata_size > 0 && *(avctx->extradata) == 1;
395     priv->last_picture = -1;
396     priv->decode_wait  = BASE_WAIT;
397
398     subtype = id2subtype(priv, avctx->codec->id);
399     switch (subtype) {
400     case BC_MSUBTYPE_AVC1:
401         {
402             uint8_t *dummy_p;
403             int dummy_int;
404
405             uint32_t orig_data_size = avctx->extradata_size;
406             uint8_t *orig_data = av_malloc(orig_data_size);
407             if (!orig_data) {
408                 av_log(avctx, AV_LOG_ERROR,
409                        "Failed to allocate copy of extradata\n");
410                 return AVERROR(ENOMEM);
411             }
412             memcpy(orig_data, avctx->extradata, orig_data_size);
413
414
415             priv->bsfc = av_bitstream_filter_init("h264_mp4toannexb");
416             if (!priv->bsfc) {
417                 av_log(avctx, AV_LOG_ERROR,
418                        "Cannot open the h264_mp4toannexb BSF!\n");
419                 av_free(orig_data);
420                 return AVERROR_BSF_NOT_FOUND;
421             }
422             av_bitstream_filter_filter(priv->bsfc, avctx, NULL, &dummy_p,
423                                        &dummy_int, NULL, 0, 0);
424
425             priv->sps_pps_buf     = avctx->extradata;
426             priv->sps_pps_size    = avctx->extradata_size;
427             avctx->extradata      = orig_data;
428             avctx->extradata_size = orig_data_size;
429
430             format.pMetaData   = priv->sps_pps_buf;
431             format.metaDataSz  = priv->sps_pps_size;
432             format.startCodeSz = (avctx->extradata[4] & 0x03) + 1;
433         }
434         break;
435     case BC_MSUBTYPE_H264:
436         format.startCodeSz = 4;
437         // Fall-through
438     case BC_MSUBTYPE_VC1:
439     case BC_MSUBTYPE_WVC1:
440     case BC_MSUBTYPE_WMV3:
441     case BC_MSUBTYPE_WMVA:
442     case BC_MSUBTYPE_MPEG2VIDEO:
443     case BC_MSUBTYPE_DIVX:
444     case BC_MSUBTYPE_DIVX311:
445         format.pMetaData  = avctx->extradata;
446         format.metaDataSz = avctx->extradata_size;
447         break;
448     default:
449         av_log(avctx, AV_LOG_ERROR, "CrystalHD: Unknown codec name\n");
450         return AVERROR(EINVAL);
451     }
452     format.mSubtype = subtype;
453
454     if (priv->sWidth) {
455         format.bEnableScaling = 1;
456         format.ScalingParams.sWidth = priv->sWidth;
457     }
458
459     /* Get a decoder instance */
460     av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: starting up\n");
461     // Initialize the Link and Decoder devices
462     ret = DtsDeviceOpen(&priv->dev, mode);
463     if (ret != BC_STS_SUCCESS) {
464         av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: DtsDeviceOpen failed\n");
465         goto fail;
466     }
467
468     ret = DtsCrystalHDVersion(priv->dev, &version);
469     if (ret != BC_STS_SUCCESS) {
470         av_log(avctx, AV_LOG_VERBOSE,
471                "CrystalHD: DtsCrystalHDVersion failed\n");
472         goto fail;
473     }
474     priv->is_70012 = version.device == 0;
475
476     if (priv->is_70012 &&
477         (subtype == BC_MSUBTYPE_DIVX || subtype == BC_MSUBTYPE_DIVX311)) {
478         av_log(avctx, AV_LOG_VERBOSE,
479                "CrystalHD: BCM70012 doesn't support MPEG4-ASP/DivX/Xvid\n");
480         goto fail;
481     }
482
483     ret = DtsSetInputFormat(priv->dev, &format);
484     if (ret != BC_STS_SUCCESS) {
485         av_log(avctx, AV_LOG_ERROR, "CrystalHD: SetInputFormat failed\n");
486         goto fail;
487     }
488
489     ret = DtsOpenDecoder(priv->dev, BC_STREAM_TYPE_ES);
490     if (ret != BC_STS_SUCCESS) {
491         av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsOpenDecoder failed\n");
492         goto fail;
493     }
494
495     ret = DtsSetColorSpace(priv->dev, OUTPUT_MODE422_YUY2);
496     if (ret != BC_STS_SUCCESS) {
497         av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsSetColorSpace failed\n");
498         goto fail;
499     }
500     ret = DtsStartDecoder(priv->dev);
501     if (ret != BC_STS_SUCCESS) {
502         av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartDecoder failed\n");
503         goto fail;
504     }
505     ret = DtsStartCapture(priv->dev);
506     if (ret != BC_STS_SUCCESS) {
507         av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartCapture failed\n");
508         goto fail;
509     }
510
511     if (avctx->codec->id == CODEC_ID_H264) {
512         priv->parser = av_parser_init(avctx->codec->id);
513         if (!priv->parser)
514             av_log(avctx, AV_LOG_WARNING,
515                    "Cannot open the h.264 parser! Interlaced h.264 content "
516                    "will not be detected reliably.\n");
517         priv->parser->flags = PARSER_FLAG_COMPLETE_FRAMES;
518     }
519     av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Init complete.\n");
520
521     return 0;
522
523  fail:
524     uninit(avctx);
525     return -1;
526 }
527
528
529 static inline CopyRet copy_frame(AVCodecContext *avctx,
530                                  BC_DTS_PROC_OUT *output,
531                                  void *data, int *data_size)
532 {
533     BC_STATUS ret;
534     BC_DTS_STATUS decoder_status;
535     uint8_t trust_interlaced;
536     uint8_t interlaced;
537
538     CHDContext *priv = avctx->priv_data;
539     int64_t pkt_pts  = AV_NOPTS_VALUE;
540     uint8_t pic_type = 0;
541
542     uint8_t bottom_field = (output->PicInfo.flags & VDEC_FLAG_BOTTOMFIELD) ==
543                            VDEC_FLAG_BOTTOMFIELD;
544     uint8_t bottom_first = !!(output->PicInfo.flags & VDEC_FLAG_BOTTOM_FIRST);
545
546     int width    = output->PicInfo.width;
547     int height   = output->PicInfo.height;
548     int bwidth;
549     uint8_t *src = output->Ybuff;
550     int sStride;
551     uint8_t *dst;
552     int dStride;
553
554     if (output->PicInfo.timeStamp != 0) {
555         OpaqueList *node = opaque_list_pop(priv, output->PicInfo.timeStamp);
556         if (node) {
557             pkt_pts = node->reordered_opaque;
558             pic_type = node->pic_type;
559             av_free(node);
560         } else {
561             /*
562              * We will encounter a situation where a timestamp cannot be
563              * popped if a second field is being returned. In this case,
564              * each field has the same timestamp and the first one will
565              * cause it to be popped. To keep subsequent calculations
566              * simple, pic_type should be set a FIELD value - doesn't
567              * matter which, but I chose BOTTOM.
568              */
569             pic_type = PICT_BOTTOM_FIELD;
570         }
571         av_log(avctx, AV_LOG_VERBOSE, "output \"pts\": %"PRIu64"\n",
572                output->PicInfo.timeStamp);
573         av_log(avctx, AV_LOG_VERBOSE, "output picture type %d\n",
574                pic_type);
575     }
576
577     ret = DtsGetDriverStatus(priv->dev, &decoder_status);
578     if (ret != BC_STS_SUCCESS) {
579         av_log(avctx, AV_LOG_ERROR,
580                "CrystalHD: GetDriverStatus failed: %u\n", ret);
581        return RET_ERROR;
582     }
583
584     /*
585      * For most content, we can trust the interlaced flag returned
586      * by the hardware, but sometimes we can't. These are the
587      * conditions under which we can trust the flag:
588      *
589      * 1) It's not h.264 content
590      * 2) The UNKNOWN_SRC flag is not set
591      * 3) We know we're expecting a second field
592      * 4) The hardware reports this picture and the next picture
593      *    have the same picture number.
594      *
595      * Note that there can still be interlaced content that will
596      * fail this check, if the hardware hasn't decoded the next
597      * picture or if there is a corruption in the stream. (In either
598      * case a 0 will be returned for the next picture number)
599      */
600     trust_interlaced = avctx->codec->id != CODEC_ID_H264 ||
601                        !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ||
602                        priv->need_second_field ||
603                        (decoder_status.picNumFlags & ~0x40000000) ==
604                        output->PicInfo.picture_number;
605
606     /*
607      * If we got a false negative for trust_interlaced on the first field,
608      * we will realise our mistake here when we see that the picture number is that
609      * of the previous picture. We cannot recover the frame and should discard the
610      * second field to keep the correct number of output frames.
611      */
612     if (output->PicInfo.picture_number == priv->last_picture && !priv->need_second_field) {
613         av_log(avctx, AV_LOG_WARNING,
614                "Incorrectly guessed progressive frame. Discarding second field\n");
615         /* Returning without providing a picture. */
616         return RET_OK;
617     }
618
619     interlaced = (output->PicInfo.flags & VDEC_FLAG_INTERLACED_SRC) &&
620                  trust_interlaced;
621
622     if (!trust_interlaced && (decoder_status.picNumFlags & ~0x40000000) == 0) {
623         av_log(avctx, AV_LOG_VERBOSE,
624                "Next picture number unknown. Assuming progressive frame.\n");
625     }
626
627     av_log(avctx, AV_LOG_VERBOSE, "Interlaced state: %d | trust_interlaced %d\n",
628            interlaced, trust_interlaced);
629
630     if (priv->pic.data[0] && !priv->need_second_field)
631         avctx->release_buffer(avctx, &priv->pic);
632
633     priv->need_second_field = interlaced && !priv->need_second_field;
634
635     priv->pic.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE |
636                              FF_BUFFER_HINTS_REUSABLE;
637     if (!priv->pic.data[0]) {
638         if (avctx->get_buffer(avctx, &priv->pic) < 0) {
639             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
640             return RET_ERROR;
641         }
642     }
643
644     bwidth = av_image_get_linesize(avctx->pix_fmt, width, 0);
645     if (priv->is_70012) {
646         int pStride;
647
648         if (width <= 720)
649             pStride = 720;
650         else if (width <= 1280)
651             pStride = 1280;
652         else if (width <= 1080)
653             pStride = 1080;
654         sStride = av_image_get_linesize(avctx->pix_fmt, pStride, 0);
655     } else {
656         sStride = bwidth;
657     }
658
659     dStride = priv->pic.linesize[0];
660     dst     = priv->pic.data[0];
661
662     av_log(priv->avctx, AV_LOG_VERBOSE, "CrystalHD: Copying out frame\n");
663
664     if (interlaced) {
665         int dY = 0;
666         int sY = 0;
667
668         height /= 2;
669         if (bottom_field) {
670             av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: bottom field\n");
671             dY = 1;
672         } else {
673             av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: top field\n");
674             dY = 0;
675         }
676
677         for (sY = 0; sY < height; dY++, sY++) {
678             memcpy(&(dst[dY * dStride]), &(src[sY * sStride]), bwidth);
679             dY++;
680         }
681     } else {
682         av_image_copy_plane(dst, dStride, src, sStride, bwidth, height);
683     }
684
685     priv->pic.interlaced_frame = interlaced;
686     if (interlaced)
687         priv->pic.top_field_first = !bottom_first;
688
689     priv->pic.pkt_pts = pkt_pts;
690
691     if (!priv->need_second_field) {
692         *data_size       = sizeof(AVFrame);
693         *(AVFrame *)data = priv->pic;
694     }
695
696     /*
697      * Two types of PAFF content have been observed. One form causes the
698      * hardware to return a field pair and the other individual fields,
699      * even though the input is always individual fields. We must skip
700      * copying on the next decode() call to maintain pipeline length in
701      * the first case.
702      */
703     if (!interlaced && (output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) &&
704         (pic_type == PICT_TOP_FIELD || pic_type == PICT_BOTTOM_FIELD)) {
705         av_log(priv->avctx, AV_LOG_VERBOSE, "Fieldpair from two packets.\n");
706         return RET_SKIP_NEXT_COPY;
707     }
708
709     /*
710      * Testing has shown that in all cases where we don't want to return the
711      * full frame immediately, VDEC_FLAG_UNKNOWN_SRC is set.
712      */
713     return priv->need_second_field &&
714            !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ?
715            RET_COPY_NEXT_FIELD : RET_OK;
716 }
717
718
719 static inline CopyRet receive_frame(AVCodecContext *avctx,
720                                     void *data, int *data_size)
721 {
722     BC_STATUS ret;
723     BC_DTS_PROC_OUT output = {
724         .PicInfo.width  = avctx->width,
725         .PicInfo.height = avctx->height,
726     };
727     CHDContext *priv = avctx->priv_data;
728     HANDLE dev       = priv->dev;
729
730     *data_size = 0;
731
732     // Request decoded data from the driver
733     ret = DtsProcOutputNoCopy(dev, OUTPUT_PROC_TIMEOUT, &output);
734     if (ret == BC_STS_FMT_CHANGE) {
735         av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Initial format change\n");
736         avctx->width  = output.PicInfo.width;
737         avctx->height = output.PicInfo.height;
738         return RET_COPY_AGAIN;
739     } else if (ret == BC_STS_SUCCESS) {
740         int copy_ret = -1;
741         if (output.PoutFlags & BC_POUT_FLAGS_PIB_VALID) {
742             if (priv->last_picture == -1) {
743                 /*
744                  * Init to one less, so that the incrementing code doesn't
745                  * need to be special-cased.
746                  */
747                 priv->last_picture = output.PicInfo.picture_number - 1;
748             }
749
750             if (avctx->codec->id == CODEC_ID_MPEG4 &&
751                 output.PicInfo.timeStamp == 0 && priv->bframe_bug) {
752                 av_log(avctx, AV_LOG_VERBOSE,
753                        "CrystalHD: Not returning packed frame twice.\n");
754                 priv->last_picture++;
755                 DtsReleaseOutputBuffs(dev, NULL, FALSE);
756                 return RET_COPY_AGAIN;
757             }
758
759             print_frame_info(priv, &output);
760
761             if (priv->last_picture + 1 < output.PicInfo.picture_number) {
762                 av_log(avctx, AV_LOG_WARNING,
763                        "CrystalHD: Picture Number discontinuity\n");
764                 /*
765                  * Have we lost frames? If so, we need to shrink the
766                  * pipeline length appropriately.
767                  *
768                  * XXX: I have no idea what the semantics of this situation
769                  * are so I don't even know if we've lost frames or which
770                  * ones.
771                  *
772                  * In any case, only warn the first time.
773                  */
774                priv->last_picture = output.PicInfo.picture_number - 1;
775             }
776
777             copy_ret = copy_frame(avctx, &output, data, data_size);
778             if (*data_size > 0) {
779                 avctx->has_b_frames--;
780                 priv->last_picture++;
781                 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Pipeline length: %u\n",
782                        avctx->has_b_frames);
783             }
784         } else {
785             /*
786              * An invalid frame has been consumed.
787              */
788             av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput succeeded with "
789                                         "invalid PIB\n");
790             avctx->has_b_frames--;
791             copy_ret = RET_OK;
792         }
793         DtsReleaseOutputBuffs(dev, NULL, FALSE);
794
795         return copy_ret;
796     } else if (ret == BC_STS_BUSY) {
797         return RET_COPY_AGAIN;
798     } else {
799         av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput failed %d\n", ret);
800         return RET_ERROR;
801     }
802 }
803
804
805 static int decode(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
806 {
807     BC_STATUS ret;
808     BC_DTS_STATUS decoder_status;
809     CopyRet rec_ret;
810     CHDContext *priv   = avctx->priv_data;
811     HANDLE dev         = priv->dev;
812     int len            = avpkt->size;
813     uint8_t pic_type   = 0;
814
815     av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: decode_frame\n");
816
817     if (avpkt->size == 7 && !priv->bframe_bug) {
818         /*
819          * The use of a drop frame triggers the bug
820          */
821         av_log(avctx, AV_LOG_INFO,
822                "CrystalHD: Enabling work-around for packed b-frame bug\n");
823         priv->bframe_bug = 1;
824     } else if (avpkt->size == 8 && priv->bframe_bug) {
825         /*
826          * Delay frames don't trigger the bug
827          */
828         av_log(avctx, AV_LOG_INFO,
829                "CrystalHD: Disabling work-around for packed b-frame bug\n");
830         priv->bframe_bug = 0;
831     }
832
833     if (len) {
834         int32_t tx_free = (int32_t)DtsTxFreeSize(dev);
835
836         if (priv->parser) {
837             uint8_t *in_data = avpkt->data;
838             int in_len = len;
839             int ret = 0;
840
841             if (priv->bsfc) {
842                 ret = av_bitstream_filter_filter(priv->bsfc, avctx, NULL,
843                                                  &in_data, &in_len,
844                                                  avpkt->data, len, 0);
845             }
846
847             if (ret >= 0) {
848                 uint8_t *pout;
849                 int psize;
850                 int index;
851                 H264Context *h = priv->parser->priv_data;
852
853                 index = av_parser_parse2(priv->parser, avctx, &pout, &psize,
854                                          in_data, in_len, avctx->pkt->pts,
855                                          avctx->pkt->dts, 0);
856                 if (index < 0) {
857                     av_log(avctx, AV_LOG_WARNING,
858                            "CrystalHD: Failed to parse h.264 packet to "
859                            "detect interlacing.\n");
860                 } else if (index != in_len) {
861                     av_log(avctx, AV_LOG_WARNING,
862                            "CrystalHD: Failed to parse h.264 packet "
863                            "completely. Interlaced frames may be "
864                            "incorrectly detected\n.");
865                 } else {
866                     av_log(avctx, AV_LOG_VERBOSE,
867                            "CrystalHD: parser picture type %d\n",
868                            h->s.picture_structure);
869                     pic_type = h->s.picture_structure;
870                 }
871             } else {
872                 av_log(avctx, AV_LOG_WARNING,
873                        "CrystalHD: mp4toannexb filter failed to filter "
874                        "packet. Interlaced frames may be incorrectly "
875                        "detected.\n");
876             }
877             if (ret > 0) {
878                 av_freep(&in_data);
879             }
880         }
881
882         if (len < tx_free - 1024) {
883             /*
884              * Despite being notionally opaque, either libcrystalhd or
885              * the hardware itself will mangle pts values that are too
886              * small or too large. The docs claim it should be in units
887              * of 100ns. Given that we're nominally dealing with a black
888              * box on both sides, any transform we do has no guarantee of
889              * avoiding mangling so we need to build a mapping to values
890              * we know will not be mangled.
891              */
892             uint64_t pts = opaque_list_push(priv, avctx->pkt->pts, pic_type);
893             if (!pts) {
894                 return AVERROR(ENOMEM);
895             }
896             av_log(priv->avctx, AV_LOG_VERBOSE,
897                    "input \"pts\": %"PRIu64"\n", pts);
898             ret = DtsProcInput(dev, avpkt->data, len, pts, 0);
899             if (ret == BC_STS_BUSY) {
900                 av_log(avctx, AV_LOG_WARNING,
901                        "CrystalHD: ProcInput returned busy\n");
902                 usleep(BASE_WAIT);
903                 return AVERROR(EBUSY);
904             } else if (ret != BC_STS_SUCCESS) {
905                 av_log(avctx, AV_LOG_ERROR,
906                        "CrystalHD: ProcInput failed: %u\n", ret);
907                 return -1;
908             }
909             avctx->has_b_frames++;
910         } else {
911             av_log(avctx, AV_LOG_WARNING, "CrystalHD: Input buffer full\n");
912             len = 0; // We didn't consume any bytes.
913         }
914     } else {
915         av_log(avctx, AV_LOG_INFO, "CrystalHD: No more input data\n");
916     }
917
918     if (priv->skip_next_output) {
919         av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Skipping next output.\n");
920         priv->skip_next_output = 0;
921         avctx->has_b_frames--;
922         return len;
923     }
924
925     ret = DtsGetDriverStatus(dev, &decoder_status);
926     if (ret != BC_STS_SUCCESS) {
927         av_log(avctx, AV_LOG_ERROR, "CrystalHD: GetDriverStatus failed\n");
928         return -1;
929     }
930
931     /*
932      * No frames ready. Don't try to extract.
933      *
934      * Empirical testing shows that ReadyListCount can be a damn lie,
935      * and ProcOut still fails when count > 0. The same testing showed
936      * that two more iterations were needed before ProcOutput would
937      * succeed.
938      */
939     if (priv->output_ready < 2) {
940         if (decoder_status.ReadyListCount != 0)
941             priv->output_ready++;
942         usleep(BASE_WAIT);
943         av_log(avctx, AV_LOG_INFO, "CrystalHD: Filling pipeline.\n");
944         return len;
945     } else if (decoder_status.ReadyListCount == 0) {
946         /*
947          * After the pipeline is established, if we encounter a lack of frames
948          * that probably means we're not giving the hardware enough time to
949          * decode them, so start increasing the wait time at the end of a
950          * decode call.
951          */
952         usleep(BASE_WAIT);
953         priv->decode_wait += WAIT_UNIT;
954         av_log(avctx, AV_LOG_INFO, "CrystalHD: No frames ready. Returning\n");
955         return len;
956     }
957
958     do {
959         rec_ret = receive_frame(avctx, data, data_size);
960         if (rec_ret == RET_OK && *data_size == 0) {
961             /*
962              * This case is for when the encoded fields are stored
963              * separately and we get a separate avpkt for each one. To keep
964              * the pipeline stable, we should return nothing and wait for
965              * the next time round to grab the second field.
966              * H.264 PAFF is an example of this.
967              */
968             av_log(avctx, AV_LOG_VERBOSE, "Returning after first field.\n");
969             avctx->has_b_frames--;
970         } else if (rec_ret == RET_COPY_NEXT_FIELD) {
971             /*
972              * This case is for when the encoded fields are stored in a
973              * single avpkt but the hardware returns then separately. Unless
974              * we grab the second field before returning, we'll slip another
975              * frame in the pipeline and if that happens a lot, we're sunk.
976              * So we have to get that second field now.
977              * Interlaced mpeg2 and vc1 are examples of this.
978              */
979             av_log(avctx, AV_LOG_VERBOSE, "Trying to get second field.\n");
980             while (1) {
981                 usleep(priv->decode_wait);
982                 ret = DtsGetDriverStatus(dev, &decoder_status);
983                 if (ret == BC_STS_SUCCESS &&
984                     decoder_status.ReadyListCount > 0) {
985                     rec_ret = receive_frame(avctx, data, data_size);
986                     if ((rec_ret == RET_OK && *data_size > 0) ||
987                         rec_ret == RET_ERROR)
988                         break;
989                 }
990             }
991             av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Got second field.\n");
992         } else if (rec_ret == RET_SKIP_NEXT_COPY) {
993             /*
994              * Two input packets got turned into a field pair. Gawd.
995              */
996             av_log(avctx, AV_LOG_VERBOSE,
997                    "Don't output on next decode call.\n");
998             priv->skip_next_output = 1;
999         }
1000         /*
1001          * If rec_ret == RET_COPY_AGAIN, that means that either we just handled
1002          * a FMT_CHANGE event and need to go around again for the actual frame,
1003          * we got a busy status and need to try again, or we're dealing with
1004          * packed b-frames, where the hardware strangely returns the packed
1005          * p-frame twice. We choose to keep the second copy as it carries the
1006          * valid pts.
1007          */
1008     } while (rec_ret == RET_COPY_AGAIN);
1009     usleep(priv->decode_wait);
1010     return len;
1011 }
1012
1013
1014 #if CONFIG_H264_CRYSTALHD_DECODER
1015 static AVClass h264_class = {
1016     "h264_crystalhd",
1017     av_default_item_name,
1018     options,
1019     LIBAVUTIL_VERSION_INT,
1020 };
1021
1022 AVCodec ff_h264_crystalhd_decoder = {
1023     .name           = "h264_crystalhd",
1024     .type           = AVMEDIA_TYPE_VIDEO,
1025     .id             = CODEC_ID_H264,
1026     .priv_data_size = sizeof(CHDContext),
1027     .init           = init,
1028     .close          = uninit,
1029     .decode         = decode,
1030     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1031     .flush          = flush,
1032     .long_name      = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (CrystalHD acceleration)"),
1033     .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1034     .priv_class     = &h264_class,
1035 };
1036 #endif
1037
1038 #if CONFIG_MPEG2_CRYSTALHD_DECODER
1039 static AVClass mpeg2_class = {
1040     "mpeg2_crystalhd",
1041     av_default_item_name,
1042     options,
1043     LIBAVUTIL_VERSION_INT,
1044 };
1045
1046 AVCodec ff_mpeg2_crystalhd_decoder = {
1047     .name           = "mpeg2_crystalhd",
1048     .type           = AVMEDIA_TYPE_VIDEO,
1049     .id             = CODEC_ID_MPEG2VIDEO,
1050     .priv_data_size = sizeof(CHDContext),
1051     .init           = init,
1052     .close          = uninit,
1053     .decode         = decode,
1054     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1055     .flush          = flush,
1056     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-2 Video (CrystalHD acceleration)"),
1057     .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1058     .priv_class     = &mpeg2_class,
1059 };
1060 #endif
1061
1062 #if CONFIG_MPEG4_CRYSTALHD_DECODER
1063 static AVClass mpeg4_class = {
1064     "mpeg4_crystalhd",
1065     av_default_item_name,
1066     options,
1067     LIBAVUTIL_VERSION_INT,
1068 };
1069
1070 AVCodec ff_mpeg4_crystalhd_decoder = {
1071     .name           = "mpeg4_crystalhd",
1072     .type           = AVMEDIA_TYPE_VIDEO,
1073     .id             = CODEC_ID_MPEG4,
1074     .priv_data_size = sizeof(CHDContext),
1075     .init           = init,
1076     .close          = uninit,
1077     .decode         = decode,
1078     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1079     .flush          = flush,
1080     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 (CrystalHD acceleration)"),
1081     .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1082     .priv_class     = &mpeg4_class,
1083 };
1084 #endif
1085
1086 #if CONFIG_MSMPEG4_CRYSTALHD_DECODER
1087 static AVClass msmpeg4_class = {
1088     "msmpeg4_crystalhd",
1089     av_default_item_name,
1090     options,
1091     LIBAVUTIL_VERSION_INT,
1092 };
1093
1094 AVCodec ff_msmpeg4_crystalhd_decoder = {
1095     .name           = "msmpeg4_crystalhd",
1096     .type           = AVMEDIA_TYPE_VIDEO,
1097     .id             = CODEC_ID_MSMPEG4V3,
1098     .priv_data_size = sizeof(CHDContext),
1099     .init           = init,
1100     .close          = uninit,
1101     .decode         = decode,
1102     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1103     .flush          = flush,
1104     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 Microsoft variant version 3 (CrystalHD acceleration)"),
1105     .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1106     .priv_class     = &msmpeg4_class,
1107 };
1108 #endif
1109
1110 #if CONFIG_VC1_CRYSTALHD_DECODER
1111 static AVClass vc1_class = {
1112     "vc1_crystalhd",
1113     av_default_item_name,
1114     options,
1115     LIBAVUTIL_VERSION_INT,
1116 };
1117
1118 AVCodec ff_vc1_crystalhd_decoder = {
1119     .name           = "vc1_crystalhd",
1120     .type           = AVMEDIA_TYPE_VIDEO,
1121     .id             = CODEC_ID_VC1,
1122     .priv_data_size = sizeof(CHDContext),
1123     .init           = init,
1124     .close          = uninit,
1125     .decode         = decode,
1126     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1127     .flush          = flush,
1128     .long_name      = NULL_IF_CONFIG_SMALL("SMPTE VC-1 (CrystalHD acceleration)"),
1129     .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1130     .priv_class     = &vc1_class,
1131 };
1132 #endif
1133
1134 #if CONFIG_WMV3_CRYSTALHD_DECODER
1135 static AVClass wmv3_class = {
1136     "wmv3_crystalhd",
1137     av_default_item_name,
1138     options,
1139     LIBAVUTIL_VERSION_INT,
1140 };
1141
1142 AVCodec ff_wmv3_crystalhd_decoder = {
1143     .name           = "wmv3_crystalhd",
1144     .type           = AVMEDIA_TYPE_VIDEO,
1145     .id             = CODEC_ID_WMV3,
1146     .priv_data_size = sizeof(CHDContext),
1147     .init           = init,
1148     .close          = uninit,
1149     .decode         = decode,
1150     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1151     .flush          = flush,
1152     .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Video 9 (CrystalHD acceleration)"),
1153     .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1154     .priv_class     = &wmv3_class,
1155 };
1156 #endif