]> git.sesse.net Git - ffmpeg/blob - libavcodec/crystalhd.c
Merge remote-tracking branch 'shariman/wmall'
[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       AV_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             priv->bsfc = av_bitstream_filter_init("h264_mp4toannexb");
406             if (!priv->bsfc) {
407                 av_log(avctx, AV_LOG_ERROR,
408                        "Cannot open the h264_mp4toannexb BSF!\n");
409                 return AVERROR_BSF_NOT_FOUND;
410             }
411             av_bitstream_filter_filter(priv->bsfc, avctx, NULL, &dummy_p,
412                                        &dummy_int, NULL, 0, 0);
413         }
414         subtype = BC_MSUBTYPE_H264;
415         // Fall-through
416     case BC_MSUBTYPE_H264:
417         format.startCodeSz = 4;
418         // Fall-through
419     case BC_MSUBTYPE_VC1:
420     case BC_MSUBTYPE_WVC1:
421     case BC_MSUBTYPE_WMV3:
422     case BC_MSUBTYPE_WMVA:
423     case BC_MSUBTYPE_MPEG2VIDEO:
424     case BC_MSUBTYPE_DIVX:
425     case BC_MSUBTYPE_DIVX311:
426         format.pMetaData  = avctx->extradata;
427         format.metaDataSz = avctx->extradata_size;
428         break;
429     default:
430         av_log(avctx, AV_LOG_ERROR, "CrystalHD: Unknown codec name\n");
431         return AVERROR(EINVAL);
432     }
433     format.mSubtype = subtype;
434
435     if (priv->sWidth) {
436         format.bEnableScaling = 1;
437         format.ScalingParams.sWidth = priv->sWidth;
438     }
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         priv->parser->flags = PARSER_FLAG_COMPLETE_FRAMES;
499     }
500     av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Init complete.\n");
501
502     return 0;
503
504  fail:
505     uninit(avctx);
506     return -1;
507 }
508
509
510 static inline CopyRet copy_frame(AVCodecContext *avctx,
511                                  BC_DTS_PROC_OUT *output,
512                                  void *data, int *data_size)
513 {
514     BC_STATUS ret;
515     BC_DTS_STATUS decoder_status;
516     uint8_t trust_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         OpaqueList *node = opaque_list_pop(priv, output->PicInfo.timeStamp);
537         if (node) {
538             pkt_pts = node->reordered_opaque;
539             pic_type = node->pic_type;
540             av_free(node);
541         } else {
542             /*
543              * We will encounter a situation where a timestamp cannot be
544              * popped if a second field is being returned. In this case,
545              * each field has the same timestamp and the first one will
546              * cause it to be popped. To keep subsequent calculations
547              * simple, pic_type should be set a FIELD value - doesn't
548              * matter which, but I chose BOTTOM.
549              */
550             pic_type = PICT_BOTTOM_FIELD;
551         }
552         av_log(avctx, AV_LOG_VERBOSE, "output \"pts\": %"PRIu64"\n",
553                output->PicInfo.timeStamp);
554         av_log(avctx, AV_LOG_VERBOSE, "output picture type %d\n",
555                pic_type);
556     }
557
558     ret = DtsGetDriverStatus(priv->dev, &decoder_status);
559     if (ret != BC_STS_SUCCESS) {
560         av_log(avctx, AV_LOG_ERROR,
561                "CrystalHD: GetDriverStatus failed: %u\n", ret);
562        return RET_ERROR;
563     }
564
565     /*
566      * For most content, we can trust the interlaced flag returned
567      * by the hardware, but sometimes we can't. These are the
568      * conditions under which we can trust the flag:
569      *
570      * 1) It's not h.264 content
571      * 2) The UNKNOWN_SRC flag is not set
572      * 3) We know we're expecting a second field
573      * 4) The hardware reports this picture and the next picture
574      *    have the same picture number.
575      *
576      * Note that there can still be interlaced content that will
577      * fail this check, if the hardware hasn't decoded the next
578      * picture or if there is a corruption in the stream. (In either
579      * case a 0 will be returned for the next picture number)
580      */
581     trust_interlaced = avctx->codec->id != CODEC_ID_H264 ||
582                        !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ||
583                        priv->need_second_field ||
584                        (decoder_status.picNumFlags & ~0x40000000) ==
585                        output->PicInfo.picture_number;
586
587     /*
588      * If we got a false negative for trust_interlaced on the first field,
589      * we will realise our mistake here when we see that the picture number is that
590      * of the previous picture. We cannot recover the frame and should discard the
591      * second field to keep the correct number of output frames.
592      */
593     if (output->PicInfo.picture_number == priv->last_picture && !priv->need_second_field) {
594         av_log(avctx, AV_LOG_WARNING,
595                "Incorrectly guessed progressive frame. Discarding second field\n");
596         /* Returning without providing a picture. */
597         return RET_OK;
598     }
599
600     interlaced = (output->PicInfo.flags & VDEC_FLAG_INTERLACED_SRC) &&
601                  trust_interlaced;
602
603     if (!trust_interlaced && (decoder_status.picNumFlags & ~0x40000000) == 0) {
604         av_log(avctx, AV_LOG_VERBOSE,
605                "Next picture number unknown. Assuming progressive frame.\n");
606     }
607
608     av_log(avctx, AV_LOG_VERBOSE, "Interlaced state: %d | trust_interlaced %d\n",
609            interlaced, trust_interlaced);
610
611     if (priv->pic.data[0] && !priv->need_second_field)
612         avctx->release_buffer(avctx, &priv->pic);
613
614     priv->need_second_field = interlaced && !priv->need_second_field;
615
616     priv->pic.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE |
617                              FF_BUFFER_HINTS_REUSABLE;
618     if (!priv->pic.data[0]) {
619         if (avctx->get_buffer(avctx, &priv->pic) < 0) {
620             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
621             return RET_ERROR;
622         }
623     }
624
625     bwidth = av_image_get_linesize(avctx->pix_fmt, width, 0);
626     if (priv->is_70012) {
627         int pStride;
628
629         if (width <= 720)
630             pStride = 720;
631         else if (width <= 1280)
632             pStride = 1280;
633         else if (width <= 1080)
634             pStride = 1080;
635         sStride = av_image_get_linesize(avctx->pix_fmt, pStride, 0);
636     } else {
637         sStride = bwidth;
638     }
639
640     dStride = priv->pic.linesize[0];
641     dst     = priv->pic.data[0];
642
643     av_log(priv->avctx, AV_LOG_VERBOSE, "CrystalHD: Copying out frame\n");
644
645     if (interlaced) {
646         int dY = 0;
647         int sY = 0;
648
649         height /= 2;
650         if (bottom_field) {
651             av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: bottom field\n");
652             dY = 1;
653         } else {
654             av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: top field\n");
655             dY = 0;
656         }
657
658         for (sY = 0; sY < height; dY++, sY++) {
659             memcpy(&(dst[dY * dStride]), &(src[sY * sStride]), bwidth);
660             dY++;
661         }
662     } else {
663         av_image_copy_plane(dst, dStride, src, sStride, bwidth, height);
664     }
665
666     priv->pic.interlaced_frame = interlaced;
667     if (interlaced)
668         priv->pic.top_field_first = !bottom_first;
669
670     priv->pic.pkt_pts = pkt_pts;
671
672     if (!priv->need_second_field) {
673         *data_size       = sizeof(AVFrame);
674         *(AVFrame *)data = priv->pic;
675     }
676
677     /*
678      * Two types of PAFF content have been observed. One form causes the
679      * hardware to return a field pair and the other individual fields,
680      * even though the input is always individual fields. We must skip
681      * copying on the next decode() call to maintain pipeline length in
682      * the first case.
683      */
684     if (!interlaced && (output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) &&
685         (pic_type == PICT_TOP_FIELD || pic_type == PICT_BOTTOM_FIELD)) {
686         av_log(priv->avctx, AV_LOG_VERBOSE, "Fieldpair from two packets.\n");
687         return RET_SKIP_NEXT_COPY;
688     }
689
690     /*
691      * Testing has shown that in all cases where we don't want to return the
692      * full frame immediately, VDEC_FLAG_UNKNOWN_SRC is set.
693      */
694     return priv->need_second_field &&
695            !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ?
696            RET_COPY_NEXT_FIELD : RET_OK;
697 }
698
699
700 static inline CopyRet receive_frame(AVCodecContext *avctx,
701                                     void *data, int *data_size)
702 {
703     BC_STATUS ret;
704     BC_DTS_PROC_OUT output = {
705         .PicInfo.width  = avctx->width,
706         .PicInfo.height = avctx->height,
707     };
708     CHDContext *priv = avctx->priv_data;
709     HANDLE dev       = priv->dev;
710
711     *data_size = 0;
712
713     // Request decoded data from the driver
714     ret = DtsProcOutputNoCopy(dev, OUTPUT_PROC_TIMEOUT, &output);
715     if (ret == BC_STS_FMT_CHANGE) {
716         av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Initial format change\n");
717         avctx->width  = output.PicInfo.width;
718         avctx->height = output.PicInfo.height;
719         return RET_COPY_AGAIN;
720     } else if (ret == BC_STS_SUCCESS) {
721         int copy_ret = -1;
722         if (output.PoutFlags & BC_POUT_FLAGS_PIB_VALID) {
723             if (priv->last_picture == -1) {
724                 /*
725                  * Init to one less, so that the incrementing code doesn't
726                  * need to be special-cased.
727                  */
728                 priv->last_picture = output.PicInfo.picture_number - 1;
729             }
730
731             if (avctx->codec->id == CODEC_ID_MPEG4 &&
732                 output.PicInfo.timeStamp == 0 && priv->bframe_bug) {
733                 av_log(avctx, AV_LOG_VERBOSE,
734                        "CrystalHD: Not returning packed frame twice.\n");
735                 priv->last_picture++;
736                 DtsReleaseOutputBuffs(dev, NULL, FALSE);
737                 return RET_COPY_AGAIN;
738             }
739
740             print_frame_info(priv, &output);
741
742             if (priv->last_picture + 1 < output.PicInfo.picture_number) {
743                 av_log(avctx, AV_LOG_WARNING,
744                        "CrystalHD: Picture Number discontinuity\n");
745                 /*
746                  * Have we lost frames? If so, we need to shrink the
747                  * pipeline length appropriately.
748                  *
749                  * XXX: I have no idea what the semantics of this situation
750                  * are so I don't even know if we've lost frames or which
751                  * ones.
752                  *
753                  * In any case, only warn the first time.
754                  */
755                priv->last_picture = output.PicInfo.picture_number - 1;
756             }
757
758             copy_ret = copy_frame(avctx, &output, data, data_size);
759             if (*data_size > 0) {
760                 avctx->has_b_frames--;
761                 priv->last_picture++;
762                 av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Pipeline length: %u\n",
763                        avctx->has_b_frames);
764             }
765         } else {
766             /*
767              * An invalid frame has been consumed.
768              */
769             av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput succeeded with "
770                                         "invalid PIB\n");
771             avctx->has_b_frames--;
772             copy_ret = RET_OK;
773         }
774         DtsReleaseOutputBuffs(dev, NULL, FALSE);
775
776         return copy_ret;
777     } else if (ret == BC_STS_BUSY) {
778         return RET_COPY_AGAIN;
779     } else {
780         av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput failed %d\n", ret);
781         return RET_ERROR;
782     }
783 }
784
785
786 static int decode(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
787 {
788     BC_STATUS ret;
789     BC_DTS_STATUS decoder_status;
790     CopyRet rec_ret;
791     CHDContext *priv   = avctx->priv_data;
792     HANDLE dev         = priv->dev;
793     uint8_t *in_data   = avpkt->data;
794     int len            = avpkt->size;
795     int free_data      = 0;
796     uint8_t pic_type   = 0;
797
798     av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: decode_frame\n");
799
800     if (avpkt->size == 7 && !priv->bframe_bug) {
801         /*
802          * The use of a drop frame triggers the bug
803          */
804         av_log(avctx, AV_LOG_INFO,
805                "CrystalHD: Enabling work-around for packed b-frame bug\n");
806         priv->bframe_bug = 1;
807     } else if (avpkt->size == 8 && priv->bframe_bug) {
808         /*
809          * Delay frames don't trigger the bug
810          */
811         av_log(avctx, AV_LOG_INFO,
812                "CrystalHD: Disabling work-around for packed b-frame bug\n");
813         priv->bframe_bug = 0;
814     }
815
816     if (len) {
817         int32_t tx_free = (int32_t)DtsTxFreeSize(dev);
818
819         if (priv->parser) {
820             int ret = 0;
821
822             if (priv->bsfc) {
823                 ret = av_bitstream_filter_filter(priv->bsfc, avctx, NULL,
824                                                  &in_data, &len,
825                                                  avpkt->data, len, 0);
826             }
827             free_data = ret > 0;
828
829             if (ret >= 0) {
830                 uint8_t *pout;
831                 int psize;
832                 int index;
833                 H264Context *h = priv->parser->priv_data;
834
835                 index = av_parser_parse2(priv->parser, avctx, &pout, &psize,
836                                          in_data, len, avctx->pkt->pts,
837                                          avctx->pkt->dts, 0);
838                 if (index < 0) {
839                     av_log(avctx, AV_LOG_WARNING,
840                            "CrystalHD: Failed to parse h.264 packet to "
841                            "detect interlacing.\n");
842                 } else if (index != len) {
843                     av_log(avctx, AV_LOG_WARNING,
844                            "CrystalHD: Failed to parse h.264 packet "
845                            "completely. Interlaced frames may be "
846                            "incorrectly detected\n.");
847                 } else {
848                     av_log(avctx, AV_LOG_VERBOSE,
849                            "CrystalHD: parser picture type %d\n",
850                            h->s.picture_structure);
851                     pic_type = h->s.picture_structure;
852                 }
853             } else {
854                 av_log(avctx, AV_LOG_WARNING,
855                        "CrystalHD: mp4toannexb filter failed to filter "
856                        "packet. Interlaced frames may be incorrectly "
857                        "detected.\n");
858             }
859         }
860
861         if (len < tx_free - 1024) {
862             /*
863              * Despite being notionally opaque, either libcrystalhd or
864              * the hardware itself will mangle pts values that are too
865              * small or too large. The docs claim it should be in units
866              * of 100ns. Given that we're nominally dealing with a black
867              * box on both sides, any transform we do has no guarantee of
868              * avoiding mangling so we need to build a mapping to values
869              * we know will not be mangled.
870              */
871             uint64_t pts = opaque_list_push(priv, avctx->pkt->pts, pic_type);
872             if (!pts) {
873                 if (free_data) {
874                     av_freep(&in_data);
875                 }
876                 return AVERROR(ENOMEM);
877             }
878             av_log(priv->avctx, AV_LOG_VERBOSE,
879                    "input \"pts\": %"PRIu64"\n", pts);
880             ret = DtsProcInput(dev, in_data, len, pts, 0);
881             if (free_data) {
882                 av_freep(&in_data);
883             }
884             if (ret == BC_STS_BUSY) {
885                 av_log(avctx, AV_LOG_WARNING,
886                        "CrystalHD: ProcInput returned busy\n");
887                 usleep(BASE_WAIT);
888                 return AVERROR(EBUSY);
889             } else if (ret != BC_STS_SUCCESS) {
890                 av_log(avctx, AV_LOG_ERROR,
891                        "CrystalHD: ProcInput failed: %u\n", ret);
892                 return -1;
893             }
894             avctx->has_b_frames++;
895         } else {
896             av_log(avctx, AV_LOG_WARNING, "CrystalHD: Input buffer full\n");
897             len = 0; // We didn't consume any bytes.
898         }
899     } else {
900         av_log(avctx, AV_LOG_INFO, "CrystalHD: No more input data\n");
901     }
902
903     if (priv->skip_next_output) {
904         av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Skipping next output.\n");
905         priv->skip_next_output = 0;
906         avctx->has_b_frames--;
907         return len;
908     }
909
910     ret = DtsGetDriverStatus(dev, &decoder_status);
911     if (ret != BC_STS_SUCCESS) {
912         av_log(avctx, AV_LOG_ERROR, "CrystalHD: GetDriverStatus failed\n");
913         return -1;
914     }
915
916     /*
917      * No frames ready. Don't try to extract.
918      *
919      * Empirical testing shows that ReadyListCount can be a damn lie,
920      * and ProcOut still fails when count > 0. The same testing showed
921      * that two more iterations were needed before ProcOutput would
922      * succeed.
923      */
924     if (priv->output_ready < 2) {
925         if (decoder_status.ReadyListCount != 0)
926             priv->output_ready++;
927         usleep(BASE_WAIT);
928         av_log(avctx, AV_LOG_INFO, "CrystalHD: Filling pipeline.\n");
929         return len;
930     } else if (decoder_status.ReadyListCount == 0) {
931         /*
932          * After the pipeline is established, if we encounter a lack of frames
933          * that probably means we're not giving the hardware enough time to
934          * decode them, so start increasing the wait time at the end of a
935          * decode call.
936          */
937         usleep(BASE_WAIT);
938         priv->decode_wait += WAIT_UNIT;
939         av_log(avctx, AV_LOG_INFO, "CrystalHD: No frames ready. Returning\n");
940         return len;
941     }
942
943     do {
944         rec_ret = receive_frame(avctx, data, data_size);
945         if (rec_ret == RET_OK && *data_size == 0) {
946             /*
947              * This case is for when the encoded fields are stored
948              * separately and we get a separate avpkt for each one. To keep
949              * the pipeline stable, we should return nothing and wait for
950              * the next time round to grab the second field.
951              * H.264 PAFF is an example of this.
952              */
953             av_log(avctx, AV_LOG_VERBOSE, "Returning after first field.\n");
954             avctx->has_b_frames--;
955         } else if (rec_ret == RET_COPY_NEXT_FIELD) {
956             /*
957              * This case is for when the encoded fields are stored in a
958              * single avpkt but the hardware returns then separately. Unless
959              * we grab the second field before returning, we'll slip another
960              * frame in the pipeline and if that happens a lot, we're sunk.
961              * So we have to get that second field now.
962              * Interlaced mpeg2 and vc1 are examples of this.
963              */
964             av_log(avctx, AV_LOG_VERBOSE, "Trying to get second field.\n");
965             while (1) {
966                 usleep(priv->decode_wait);
967                 ret = DtsGetDriverStatus(dev, &decoder_status);
968                 if (ret == BC_STS_SUCCESS &&
969                     decoder_status.ReadyListCount > 0) {
970                     rec_ret = receive_frame(avctx, data, data_size);
971                     if ((rec_ret == RET_OK && *data_size > 0) ||
972                         rec_ret == RET_ERROR)
973                         break;
974                 }
975             }
976             av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Got second field.\n");
977         } else if (rec_ret == RET_SKIP_NEXT_COPY) {
978             /*
979              * Two input packets got turned into a field pair. Gawd.
980              */
981             av_log(avctx, AV_LOG_VERBOSE,
982                    "Don't output on next decode call.\n");
983             priv->skip_next_output = 1;
984         }
985         /*
986          * If rec_ret == RET_COPY_AGAIN, that means that either we just handled
987          * a FMT_CHANGE event and need to go around again for the actual frame,
988          * we got a busy status and need to try again, or we're dealing with
989          * packed b-frames, where the hardware strangely returns the packed
990          * p-frame twice. We choose to keep the second copy as it carries the
991          * valid pts.
992          */
993     } while (rec_ret == RET_COPY_AGAIN);
994     usleep(priv->decode_wait);
995     return len;
996 }
997
998
999 #if CONFIG_H264_CRYSTALHD_DECODER
1000 static AVClass h264_class = {
1001     "h264_crystalhd",
1002     av_default_item_name,
1003     options,
1004     LIBAVUTIL_VERSION_INT,
1005 };
1006
1007 AVCodec ff_h264_crystalhd_decoder = {
1008     .name           = "h264_crystalhd",
1009     .type           = AVMEDIA_TYPE_VIDEO,
1010     .id             = CODEC_ID_H264,
1011     .priv_data_size = sizeof(CHDContext),
1012     .init           = init,
1013     .close          = uninit,
1014     .decode         = decode,
1015     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1016     .flush          = flush,
1017     .long_name      = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (CrystalHD acceleration)"),
1018     .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1019     .priv_class     = &h264_class,
1020 };
1021 #endif
1022
1023 #if CONFIG_MPEG2_CRYSTALHD_DECODER
1024 static AVClass mpeg2_class = {
1025     "mpeg2_crystalhd",
1026     av_default_item_name,
1027     options,
1028     LIBAVUTIL_VERSION_INT,
1029 };
1030
1031 AVCodec ff_mpeg2_crystalhd_decoder = {
1032     .name           = "mpeg2_crystalhd",
1033     .type           = AVMEDIA_TYPE_VIDEO,
1034     .id             = CODEC_ID_MPEG2VIDEO,
1035     .priv_data_size = sizeof(CHDContext),
1036     .init           = init,
1037     .close          = uninit,
1038     .decode         = decode,
1039     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1040     .flush          = flush,
1041     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-2 Video (CrystalHD acceleration)"),
1042     .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1043     .priv_class     = &mpeg2_class,
1044 };
1045 #endif
1046
1047 #if CONFIG_MPEG4_CRYSTALHD_DECODER
1048 static AVClass mpeg4_class = {
1049     "mpeg4_crystalhd",
1050     av_default_item_name,
1051     options,
1052     LIBAVUTIL_VERSION_INT,
1053 };
1054
1055 AVCodec ff_mpeg4_crystalhd_decoder = {
1056     .name           = "mpeg4_crystalhd",
1057     .type           = AVMEDIA_TYPE_VIDEO,
1058     .id             = CODEC_ID_MPEG4,
1059     .priv_data_size = sizeof(CHDContext),
1060     .init           = init,
1061     .close          = uninit,
1062     .decode         = decode,
1063     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1064     .flush          = flush,
1065     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 (CrystalHD acceleration)"),
1066     .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1067     .priv_class     = &mpeg4_class,
1068 };
1069 #endif
1070
1071 #if CONFIG_MSMPEG4_CRYSTALHD_DECODER
1072 static AVClass msmpeg4_class = {
1073     "msmpeg4_crystalhd",
1074     av_default_item_name,
1075     options,
1076     LIBAVUTIL_VERSION_INT,
1077 };
1078
1079 AVCodec ff_msmpeg4_crystalhd_decoder = {
1080     .name           = "msmpeg4_crystalhd",
1081     .type           = AVMEDIA_TYPE_VIDEO,
1082     .id             = CODEC_ID_MSMPEG4V3,
1083     .priv_data_size = sizeof(CHDContext),
1084     .init           = init,
1085     .close          = uninit,
1086     .decode         = decode,
1087     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1088     .flush          = flush,
1089     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 Microsoft variant version 3 (CrystalHD acceleration)"),
1090     .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1091     .priv_class     = &msmpeg4_class,
1092 };
1093 #endif
1094
1095 #if CONFIG_VC1_CRYSTALHD_DECODER
1096 static AVClass vc1_class = {
1097     "vc1_crystalhd",
1098     av_default_item_name,
1099     options,
1100     LIBAVUTIL_VERSION_INT,
1101 };
1102
1103 AVCodec ff_vc1_crystalhd_decoder = {
1104     .name           = "vc1_crystalhd",
1105     .type           = AVMEDIA_TYPE_VIDEO,
1106     .id             = CODEC_ID_VC1,
1107     .priv_data_size = sizeof(CHDContext),
1108     .init           = init,
1109     .close          = uninit,
1110     .decode         = decode,
1111     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1112     .flush          = flush,
1113     .long_name      = NULL_IF_CONFIG_SMALL("SMPTE VC-1 (CrystalHD acceleration)"),
1114     .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1115     .priv_class     = &vc1_class,
1116 };
1117 #endif
1118
1119 #if CONFIG_WMV3_CRYSTALHD_DECODER
1120 static AVClass wmv3_class = {
1121     "wmv3_crystalhd",
1122     av_default_item_name,
1123     options,
1124     LIBAVUTIL_VERSION_INT,
1125 };
1126
1127 AVCodec ff_wmv3_crystalhd_decoder = {
1128     .name           = "wmv3_crystalhd",
1129     .type           = AVMEDIA_TYPE_VIDEO,
1130     .id             = CODEC_ID_WMV3,
1131     .priv_data_size = sizeof(CHDContext),
1132     .init           = init,
1133     .close          = uninit,
1134     .decode         = decode,
1135     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
1136     .flush          = flush,
1137     .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Video 9 (CrystalHD acceleration)"),
1138     .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
1139     .priv_class     = &wmv3_class,
1140 };
1141 #endif