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