]> git.sesse.net Git - ffmpeg/blob - libavcodec/decode.c
Merge commit '2a9e1c122eed66be1b26b747342b848300b226c7'
[ffmpeg] / libavcodec / decode.c
1 /*
2  * generic decoding-related code
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include <stdint.h>
22 #include <string.h>
23
24 #include "config.h"
25
26 #if CONFIG_ICONV
27 # include <iconv.h>
28 #endif
29
30 #include "libavutil/avassert.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/bprint.h"
33 #include "libavutil/common.h"
34 #include "libavutil/frame.h"
35 #include "libavutil/hwcontext.h"
36 #include "libavutil/imgutils.h"
37 #include "libavutil/internal.h"
38 #include "libavutil/intmath.h"
39 #include "libavutil/opt.h"
40
41 #include "avcodec.h"
42 #include "bytestream.h"
43 #include "decode.h"
44 #include "hwaccel.h"
45 #include "internal.h"
46 #include "thread.h"
47
48 static int apply_param_change(AVCodecContext *avctx, const AVPacket *avpkt)
49 {
50     int size = 0, ret;
51     const uint8_t *data;
52     uint32_t flags;
53     int64_t val;
54
55     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
56     if (!data)
57         return 0;
58
59     if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
60         av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
61                "changes, but PARAM_CHANGE side data was sent to it.\n");
62         ret = AVERROR(EINVAL);
63         goto fail2;
64     }
65
66     if (size < 4)
67         goto fail;
68
69     flags = bytestream_get_le32(&data);
70     size -= 4;
71
72     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
73         if (size < 4)
74             goto fail;
75         val = bytestream_get_le32(&data);
76         if (val <= 0 || val > INT_MAX) {
77             av_log(avctx, AV_LOG_ERROR, "Invalid channel count");
78             ret = AVERROR_INVALIDDATA;
79             goto fail2;
80         }
81         avctx->channels = val;
82         size -= 4;
83     }
84     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
85         if (size < 8)
86             goto fail;
87         avctx->channel_layout = bytestream_get_le64(&data);
88         size -= 8;
89     }
90     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
91         if (size < 4)
92             goto fail;
93         val = bytestream_get_le32(&data);
94         if (val <= 0 || val > INT_MAX) {
95             av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
96             ret = AVERROR_INVALIDDATA;
97             goto fail2;
98         }
99         avctx->sample_rate = val;
100         size -= 4;
101     }
102     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
103         if (size < 8)
104             goto fail;
105         avctx->width  = bytestream_get_le32(&data);
106         avctx->height = bytestream_get_le32(&data);
107         size -= 8;
108         ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
109         if (ret < 0)
110             goto fail2;
111     }
112
113     return 0;
114 fail:
115     av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
116     ret = AVERROR_INVALIDDATA;
117 fail2:
118     if (ret < 0) {
119         av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
120         if (avctx->err_recognition & AV_EF_EXPLODE)
121             return ret;
122     }
123     return 0;
124 }
125
126 static int extract_packet_props(AVCodecInternal *avci, const AVPacket *pkt)
127 {
128     int ret = 0;
129
130     av_packet_unref(avci->last_pkt_props);
131     if (pkt) {
132         ret = av_packet_copy_props(avci->last_pkt_props, pkt);
133         if (!ret)
134             avci->last_pkt_props->size = pkt->size; // HACK: Needed for ff_decode_frame_props().
135     }
136     return ret;
137 }
138
139 static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
140 {
141     int ret;
142
143     /* move the original frame to our backup */
144     av_frame_unref(avci->to_free);
145     av_frame_move_ref(avci->to_free, frame);
146
147     /* now copy everything except the AVBufferRefs back
148      * note that we make a COPY of the side data, so calling av_frame_free() on
149      * the caller's frame will work properly */
150     ret = av_frame_copy_props(frame, avci->to_free);
151     if (ret < 0)
152         return ret;
153
154     memcpy(frame->data,     avci->to_free->data,     sizeof(frame->data));
155     memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
156     if (avci->to_free->extended_data != avci->to_free->data) {
157         int planes = avci->to_free->channels;
158         int size   = planes * sizeof(*frame->extended_data);
159
160         if (!size) {
161             av_frame_unref(frame);
162             return AVERROR_BUG;
163         }
164
165         frame->extended_data = av_malloc(size);
166         if (!frame->extended_data) {
167             av_frame_unref(frame);
168             return AVERROR(ENOMEM);
169         }
170         memcpy(frame->extended_data, avci->to_free->extended_data,
171                size);
172     } else
173         frame->extended_data = frame->data;
174
175     frame->format         = avci->to_free->format;
176     frame->width          = avci->to_free->width;
177     frame->height         = avci->to_free->height;
178     frame->channel_layout = avci->to_free->channel_layout;
179     frame->nb_samples     = avci->to_free->nb_samples;
180     frame->channels       = avci->to_free->channels;
181
182     return 0;
183 }
184
185 int ff_decode_bsfs_init(AVCodecContext *avctx)
186 {
187     AVCodecInternal *avci = avctx->internal;
188     DecodeFilterContext *s = &avci->filter;
189     const char *bsfs_str;
190     int ret;
191
192     if (s->nb_bsfs)
193         return 0;
194
195     bsfs_str = avctx->codec->bsfs ? avctx->codec->bsfs : "null";
196     while (bsfs_str && *bsfs_str) {
197         AVBSFContext **tmp;
198         const AVBitStreamFilter *filter;
199         char *bsf, *bsf_options_str, *bsf_name;
200
201         bsf = av_get_token(&bsfs_str, ",");
202         if (!bsf) {
203             ret = AVERROR(ENOMEM);
204             goto fail;
205         }
206         bsf_name = av_strtok(bsf, "=", &bsf_options_str);
207         if (!bsf_name) {
208             av_freep(&bsf);
209             ret = AVERROR(ENOMEM);
210             goto fail;
211         }
212
213         filter = av_bsf_get_by_name(bsf_name);
214         if (!filter) {
215             av_log(avctx, AV_LOG_ERROR, "A non-existing bitstream filter %s "
216                    "requested by a decoder. This is a bug, please report it.\n",
217                    bsf_name);
218             av_freep(&bsf);
219             ret = AVERROR_BUG;
220             goto fail;
221         }
222
223         tmp = av_realloc_array(s->bsfs, s->nb_bsfs + 1, sizeof(*s->bsfs));
224         if (!tmp) {
225             av_freep(&bsf);
226             ret = AVERROR(ENOMEM);
227             goto fail;
228         }
229         s->bsfs = tmp;
230         s->nb_bsfs++;
231
232         ret = av_bsf_alloc(filter, &s->bsfs[s->nb_bsfs - 1]);
233         if (ret < 0) {
234             av_freep(&bsf);
235             goto fail;
236         }
237
238         if (s->nb_bsfs == 1) {
239             /* We do not currently have an API for passing the input timebase into decoders,
240              * but no filters used here should actually need it.
241              * So we make up some plausible-looking number (the MPEG 90kHz timebase) */
242             s->bsfs[s->nb_bsfs - 1]->time_base_in = (AVRational){ 1, 90000 };
243             ret = avcodec_parameters_from_context(s->bsfs[s->nb_bsfs - 1]->par_in,
244                                                   avctx);
245         } else {
246             s->bsfs[s->nb_bsfs - 1]->time_base_in = s->bsfs[s->nb_bsfs - 2]->time_base_out;
247             ret = avcodec_parameters_copy(s->bsfs[s->nb_bsfs - 1]->par_in,
248                                           s->bsfs[s->nb_bsfs - 2]->par_out);
249         }
250         if (ret < 0) {
251             av_freep(&bsf);
252             goto fail;
253         }
254
255         if (bsf_options_str && filter->priv_class) {
256             const AVOption *opt = av_opt_next(s->bsfs[s->nb_bsfs - 1]->priv_data, NULL);
257             const char * shorthand[2] = {NULL};
258
259             if (opt)
260                 shorthand[0] = opt->name;
261
262             ret = av_opt_set_from_string(s->bsfs[s->nb_bsfs - 1]->priv_data, bsf_options_str, shorthand, "=", ":");
263             if (ret < 0) {
264                 if (ret != AVERROR(ENOMEM)) {
265                     av_log(avctx, AV_LOG_ERROR, "Invalid options for bitstream filter %s "
266                            "requested by the decoder. This is a bug, please report it.\n",
267                            bsf_name);
268                     ret = AVERROR_BUG;
269                 }
270                 av_freep(&bsf);
271                 goto fail;
272             }
273         }
274         av_freep(&bsf);
275
276         ret = av_bsf_init(s->bsfs[s->nb_bsfs - 1]);
277         if (ret < 0)
278             goto fail;
279
280         if (*bsfs_str)
281             bsfs_str++;
282     }
283
284     ret = avcodec_parameters_to_context(avctx, s->bsfs[s->nb_bsfs - 1]->par_out);
285     if (ret < 0)
286         return ret;
287
288     return 0;
289 fail:
290     ff_decode_bsfs_uninit(avctx);
291     return ret;
292 }
293
294 /* try to get one output packet from the filter chain */
295 static int bsfs_poll(AVCodecContext *avctx, AVPacket *pkt)
296 {
297     DecodeFilterContext *s = &avctx->internal->filter;
298     int idx, ret;
299
300     /* start with the last filter in the chain */
301     idx = s->nb_bsfs - 1;
302     while (idx >= 0) {
303         /* request a packet from the currently selected filter */
304         ret = av_bsf_receive_packet(s->bsfs[idx], pkt);
305         if (ret == AVERROR(EAGAIN)) {
306             /* no packets available, try the next filter up the chain */
307             ret = 0;
308             idx--;
309             continue;
310         } else if (ret < 0 && ret != AVERROR_EOF) {
311             return ret;
312         }
313
314         /* got a packet or EOF -- pass it to the caller or to the next filter
315          * down the chain */
316         if (idx == s->nb_bsfs - 1) {
317             return ret;
318         } else {
319             idx++;
320             ret = av_bsf_send_packet(s->bsfs[idx], ret < 0 ? NULL : pkt);
321             if (ret < 0) {
322                 av_log(avctx, AV_LOG_ERROR,
323                        "Error pre-processing a packet before decoding\n");
324                 av_packet_unref(pkt);
325                 return ret;
326             }
327         }
328     }
329
330     return AVERROR(EAGAIN);
331 }
332
333 int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
334 {
335     AVCodecInternal *avci = avctx->internal;
336     int ret;
337
338     if (avci->draining)
339         return AVERROR_EOF;
340
341     ret = bsfs_poll(avctx, pkt);
342     if (ret == AVERROR_EOF)
343         avci->draining = 1;
344     if (ret < 0)
345         return ret;
346
347     ret = extract_packet_props(avctx->internal, pkt);
348     if (ret < 0)
349         goto finish;
350
351     ret = apply_param_change(avctx, pkt);
352     if (ret < 0)
353         goto finish;
354
355     if (avctx->codec->receive_frame)
356         avci->compat_decode_consumed += pkt->size;
357
358     return 0;
359 finish:
360     av_packet_unref(pkt);
361     return ret;
362 }
363
364 /**
365  * Attempt to guess proper monotonic timestamps for decoded video frames
366  * which might have incorrect times. Input timestamps may wrap around, in
367  * which case the output will as well.
368  *
369  * @param pts the pts field of the decoded AVPacket, as passed through
370  * AVFrame.pts
371  * @param dts the dts field of the decoded AVPacket
372  * @return one of the input values, may be AV_NOPTS_VALUE
373  */
374 static int64_t guess_correct_pts(AVCodecContext *ctx,
375                                  int64_t reordered_pts, int64_t dts)
376 {
377     int64_t pts = AV_NOPTS_VALUE;
378
379     if (dts != AV_NOPTS_VALUE) {
380         ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
381         ctx->pts_correction_last_dts = dts;
382     } else if (reordered_pts != AV_NOPTS_VALUE)
383         ctx->pts_correction_last_dts = reordered_pts;
384
385     if (reordered_pts != AV_NOPTS_VALUE) {
386         ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
387         ctx->pts_correction_last_pts = reordered_pts;
388     } else if(dts != AV_NOPTS_VALUE)
389         ctx->pts_correction_last_pts = dts;
390
391     if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
392        && reordered_pts != AV_NOPTS_VALUE)
393         pts = reordered_pts;
394     else
395         pts = dts;
396
397     return pts;
398 }
399
400 /*
401  * The core of the receive_frame_wrapper for the decoders implementing
402  * the simple API. Certain decoders might consume partial packets without
403  * returning any output, so this function needs to be called in a loop until it
404  * returns EAGAIN.
405  **/
406 static int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame)
407 {
408     AVCodecInternal   *avci = avctx->internal;
409     DecodeSimpleContext *ds = &avci->ds;
410     AVPacket           *pkt = ds->in_pkt;
411     // copy to ensure we do not change pkt
412     int got_frame, actual_got_frame;
413     int ret;
414
415     if (!pkt->data && !avci->draining) {
416         av_packet_unref(pkt);
417         ret = ff_decode_get_packet(avctx, pkt);
418         if (ret < 0 && ret != AVERROR_EOF)
419             return ret;
420     }
421
422     // Some codecs (at least wma lossless) will crash when feeding drain packets
423     // after EOF was signaled.
424     if (avci->draining_done)
425         return AVERROR_EOF;
426
427     if (!pkt->data &&
428         !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||
429           avctx->active_thread_type & FF_THREAD_FRAME))
430         return AVERROR_EOF;
431
432     got_frame = 0;
433
434     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) {
435         ret = ff_thread_decode_frame(avctx, frame, &got_frame, pkt);
436     } else {
437         ret = avctx->codec->decode(avctx, frame, &got_frame, pkt);
438
439         if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
440             frame->pkt_dts = pkt->dts;
441         if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
442             if(!avctx->has_b_frames)
443                 frame->pkt_pos = pkt->pos;
444             //FIXME these should be under if(!avctx->has_b_frames)
445             /* get_buffer is supposed to set frame parameters */
446             if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
447                 if (!frame->sample_aspect_ratio.num)  frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
448                 if (!frame->width)                    frame->width               = avctx->width;
449                 if (!frame->height)                   frame->height              = avctx->height;
450                 if (frame->format == AV_PIX_FMT_NONE) frame->format              = avctx->pix_fmt;
451             }
452         }
453     }
454     emms_c();
455     actual_got_frame = got_frame;
456
457     if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
458         if (frame->flags & AV_FRAME_FLAG_DISCARD)
459             got_frame = 0;
460         if (got_frame)
461             frame->best_effort_timestamp = guess_correct_pts(avctx,
462                                                              frame->pts,
463                                                              frame->pkt_dts);
464     } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
465         uint8_t *side;
466         int side_size;
467         uint32_t discard_padding = 0;
468         uint8_t skip_reason = 0;
469         uint8_t discard_reason = 0;
470
471         if (ret >= 0 && got_frame) {
472             frame->best_effort_timestamp = guess_correct_pts(avctx,
473                                                              frame->pts,
474                                                              frame->pkt_dts);
475             if (frame->format == AV_SAMPLE_FMT_NONE)
476                 frame->format = avctx->sample_fmt;
477             if (!frame->channel_layout)
478                 frame->channel_layout = avctx->channel_layout;
479             if (!frame->channels)
480                 frame->channels = avctx->channels;
481             if (!frame->sample_rate)
482                 frame->sample_rate = avctx->sample_rate;
483         }
484
485         side= av_packet_get_side_data(avci->last_pkt_props, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
486         if(side && side_size>=10) {
487             avctx->internal->skip_samples = AV_RL32(side) * avctx->internal->skip_samples_multiplier;
488             discard_padding = AV_RL32(side + 4);
489             av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
490                    avctx->internal->skip_samples, (int)discard_padding);
491             skip_reason = AV_RL8(side + 8);
492             discard_reason = AV_RL8(side + 9);
493         }
494
495         if ((frame->flags & AV_FRAME_FLAG_DISCARD) && got_frame &&
496             !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
497             avctx->internal->skip_samples = FFMAX(0, avctx->internal->skip_samples - frame->nb_samples);
498             got_frame = 0;
499         }
500
501         if (avctx->internal->skip_samples > 0 && got_frame &&
502             !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
503             if(frame->nb_samples <= avctx->internal->skip_samples){
504                 got_frame = 0;
505                 avctx->internal->skip_samples -= frame->nb_samples;
506                 av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
507                        avctx->internal->skip_samples);
508             } else {
509                 av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,
510                                 frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);
511                 if(avctx->pkt_timebase.num && avctx->sample_rate) {
512                     int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,
513                                                    (AVRational){1, avctx->sample_rate},
514                                                    avctx->pkt_timebase);
515                     if(frame->pts!=AV_NOPTS_VALUE)
516                         frame->pts += diff_ts;
517 #if FF_API_PKT_PTS
518 FF_DISABLE_DEPRECATION_WARNINGS
519                     if(frame->pkt_pts!=AV_NOPTS_VALUE)
520                         frame->pkt_pts += diff_ts;
521 FF_ENABLE_DEPRECATION_WARNINGS
522 #endif
523                     if(frame->pkt_dts!=AV_NOPTS_VALUE)
524                         frame->pkt_dts += diff_ts;
525                     if (frame->pkt_duration >= diff_ts)
526                         frame->pkt_duration -= diff_ts;
527                 } else {
528                     av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
529                 }
530                 av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
531                        avctx->internal->skip_samples, frame->nb_samples);
532                 frame->nb_samples -= avctx->internal->skip_samples;
533                 avctx->internal->skip_samples = 0;
534             }
535         }
536
537         if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
538             !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
539             if (discard_padding == frame->nb_samples) {
540                 got_frame = 0;
541             } else {
542                 if(avctx->pkt_timebase.num && avctx->sample_rate) {
543                     int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
544                                                    (AVRational){1, avctx->sample_rate},
545                                                    avctx->pkt_timebase);
546                     frame->pkt_duration = diff_ts;
547                 } else {
548                     av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
549                 }
550                 av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
551                        (int)discard_padding, frame->nb_samples);
552                 frame->nb_samples -= discard_padding;
553             }
554         }
555
556         if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
557             AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
558             if (fside) {
559                 AV_WL32(fside->data, avctx->internal->skip_samples);
560                 AV_WL32(fside->data + 4, discard_padding);
561                 AV_WL8(fside->data + 8, skip_reason);
562                 AV_WL8(fside->data + 9, discard_reason);
563                 avctx->internal->skip_samples = 0;
564             }
565         }
566     }
567
568     if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
569         !avci->showed_multi_packet_warning &&
570         ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
571         av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
572         avci->showed_multi_packet_warning = 1;
573     }
574
575     if (!got_frame)
576         av_frame_unref(frame);
577
578     if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
579         ret = pkt->size;
580
581 #if FF_API_AVCTX_TIMEBASE
582     if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
583         avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
584 #endif
585
586     /* do not stop draining when actual_got_frame != 0 or ret < 0 */
587     /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */
588     if (avctx->internal->draining && !actual_got_frame) {
589         if (ret < 0) {
590             /* prevent infinite loop if a decoder wrongly always return error on draining */
591             /* reasonable nb_errors_max = maximum b frames + thread count */
592             int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
593                                 avctx->thread_count : 1);
594
595             if (avci->nb_draining_errors++ >= nb_errors_max) {
596                 av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
597                        "Stop draining and force EOF.\n");
598                 avci->draining_done = 1;
599                 ret = AVERROR_BUG;
600             }
601         } else {
602             avci->draining_done = 1;
603         }
604     }
605
606     avci->compat_decode_consumed += ret;
607
608     if (ret >= pkt->size || ret < 0) {
609         av_packet_unref(pkt);
610     } else {
611         int consumed = ret;
612
613         pkt->data                += consumed;
614         pkt->size                -= consumed;
615         avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
616         pkt->pts                  = AV_NOPTS_VALUE;
617         pkt->dts                  = AV_NOPTS_VALUE;
618         avci->last_pkt_props->pts = AV_NOPTS_VALUE;
619         avci->last_pkt_props->dts = AV_NOPTS_VALUE;
620     }
621
622     if (got_frame)
623         av_assert0(frame->buf[0]);
624
625     return ret < 0 ? ret : 0;
626 }
627
628 static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
629 {
630     int ret;
631
632     while (!frame->buf[0]) {
633         ret = decode_simple_internal(avctx, frame);
634         if (ret < 0)
635             return ret;
636     }
637
638     return 0;
639 }
640
641 static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
642 {
643     AVCodecInternal *avci = avctx->internal;
644     int ret;
645
646     av_assert0(!frame->buf[0]);
647
648     if (avctx->codec->receive_frame)
649         ret = avctx->codec->receive_frame(avctx, frame);
650     else
651         ret = decode_simple_receive_frame(avctx, frame);
652
653     if (ret == AVERROR_EOF)
654         avci->draining_done = 1;
655
656     if (!ret) {
657         /* the only case where decode data is not set should be decoders
658          * that do not call ff_get_buffer() */
659         av_assert0((frame->private_ref && frame->private_ref->size == sizeof(FrameDecodeData)) ||
660                    !(avctx->codec->capabilities & AV_CODEC_CAP_DR1));
661
662         if (frame->private_ref) {
663             FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
664
665             if (fdd->post_process) {
666                 ret = fdd->post_process(avctx, frame);
667                 if (ret < 0) {
668                     av_frame_unref(frame);
669                     return ret;
670                 }
671             }
672         }
673     }
674
675     /* free the per-frame decode data */
676     av_buffer_unref(&frame->private_ref);
677
678     return ret;
679 }
680
681 int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
682 {
683     AVCodecInternal *avci = avctx->internal;
684     int ret;
685
686     if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
687         return AVERROR(EINVAL);
688
689     if (avctx->internal->draining)
690         return AVERROR_EOF;
691
692     if (avpkt && !avpkt->size && avpkt->data)
693         return AVERROR(EINVAL);
694
695     av_packet_unref(avci->buffer_pkt);
696     if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
697         ret = av_packet_ref(avci->buffer_pkt, avpkt);
698         if (ret < 0)
699             return ret;
700     }
701
702     ret = av_bsf_send_packet(avci->filter.bsfs[0], avci->buffer_pkt);
703     if (ret < 0) {
704         av_packet_unref(avci->buffer_pkt);
705         return ret;
706     }
707
708     if (!avci->buffer_frame->buf[0]) {
709         ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
710         if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
711             return ret;
712     }
713
714     return 0;
715 }
716
717 static int apply_cropping(AVCodecContext *avctx, AVFrame *frame)
718 {
719     /* make sure we are noisy about decoders returning invalid cropping data */
720     if (frame->crop_left >= INT_MAX - frame->crop_right        ||
721         frame->crop_top  >= INT_MAX - frame->crop_bottom       ||
722         (frame->crop_left + frame->crop_right) >= frame->width ||
723         (frame->crop_top + frame->crop_bottom) >= frame->height) {
724         av_log(avctx, AV_LOG_WARNING,
725                "Invalid cropping information set by a decoder: "
726                "%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER" "
727                "(frame size %dx%d). This is a bug, please report it\n",
728                frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
729                frame->width, frame->height);
730         frame->crop_left   = 0;
731         frame->crop_right  = 0;
732         frame->crop_top    = 0;
733         frame->crop_bottom = 0;
734         return 0;
735     }
736
737     if (!avctx->apply_cropping)
738         return 0;
739
740     return av_frame_apply_cropping(frame, avctx->flags & AV_CODEC_FLAG_UNALIGNED ?
741                                           AV_FRAME_CROP_UNALIGNED : 0);
742 }
743
744 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
745 {
746     AVCodecInternal *avci = avctx->internal;
747     int ret;
748
749     av_frame_unref(frame);
750
751     if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
752         return AVERROR(EINVAL);
753
754     if (avci->buffer_frame->buf[0]) {
755         av_frame_move_ref(frame, avci->buffer_frame);
756     } else {
757         ret = decode_receive_frame_internal(avctx, frame);
758         if (ret < 0)
759             return ret;
760     }
761
762     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
763         ret = apply_cropping(avctx, frame);
764         if (ret < 0) {
765             av_frame_unref(frame);
766             return ret;
767         }
768     }
769
770     avctx->frame_number++;
771
772     return 0;
773 }
774
775 static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
776                          int *got_frame, const AVPacket *pkt)
777 {
778     AVCodecInternal *avci = avctx->internal;
779     int ret = 0;
780
781     av_assert0(avci->compat_decode_consumed == 0);
782
783     if (avci->draining_done && pkt && pkt->size != 0) {
784         av_log(avctx, AV_LOG_WARNING, "Got unexpected packet after EOF\n");
785         avcodec_flush_buffers(avctx);
786     }
787
788     *got_frame = 0;
789     avci->compat_decode = 1;
790
791     if (avci->compat_decode_partial_size > 0 &&
792         avci->compat_decode_partial_size != pkt->size) {
793         av_log(avctx, AV_LOG_ERROR,
794                "Got unexpected packet size after a partial decode\n");
795         ret = AVERROR(EINVAL);
796         goto finish;
797     }
798
799     if (!avci->compat_decode_partial_size) {
800         ret = avcodec_send_packet(avctx, pkt);
801         if (ret == AVERROR_EOF)
802             ret = 0;
803         else if (ret == AVERROR(EAGAIN)) {
804             /* we fully drain all the output in each decode call, so this should not
805              * ever happen */
806             ret = AVERROR_BUG;
807             goto finish;
808         } else if (ret < 0)
809             goto finish;
810     }
811
812     while (ret >= 0) {
813         ret = avcodec_receive_frame(avctx, frame);
814         if (ret < 0) {
815             if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
816                 ret = 0;
817             goto finish;
818         }
819
820         if (frame != avci->compat_decode_frame) {
821             if (!avctx->refcounted_frames) {
822                 ret = unrefcount_frame(avci, frame);
823                 if (ret < 0)
824                     goto finish;
825             }
826
827             *got_frame = 1;
828             frame = avci->compat_decode_frame;
829         } else {
830             if (!avci->compat_decode_warned) {
831                 av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
832                        "API cannot return all the frames for this decoder. "
833                        "Some frames will be dropped. Update your code to the "
834                        "new decoding API to fix this.\n");
835                 avci->compat_decode_warned = 1;
836             }
837         }
838
839         if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
840             break;
841     }
842
843 finish:
844     if (ret == 0) {
845         /* if there are any bsfs then assume full packet is always consumed */
846         if (avctx->codec->bsfs)
847             ret = pkt->size;
848         else
849             ret = FFMIN(avci->compat_decode_consumed, pkt->size);
850     }
851     avci->compat_decode_consumed = 0;
852     avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
853
854     return ret;
855 }
856
857 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
858                                               int *got_picture_ptr,
859                                               const AVPacket *avpkt)
860 {
861     return compat_decode(avctx, picture, got_picture_ptr, avpkt);
862 }
863
864 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
865                                               AVFrame *frame,
866                                               int *got_frame_ptr,
867                                               const AVPacket *avpkt)
868 {
869     return compat_decode(avctx, frame, got_frame_ptr, avpkt);
870 }
871
872 static void get_subtitle_defaults(AVSubtitle *sub)
873 {
874     memset(sub, 0, sizeof(*sub));
875     sub->pts = AV_NOPTS_VALUE;
876 }
877
878 #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
879 static int recode_subtitle(AVCodecContext *avctx,
880                            AVPacket *outpkt, const AVPacket *inpkt)
881 {
882 #if CONFIG_ICONV
883     iconv_t cd = (iconv_t)-1;
884     int ret = 0;
885     char *inb, *outb;
886     size_t inl, outl;
887     AVPacket tmp;
888 #endif
889
890     if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
891         return 0;
892
893 #if CONFIG_ICONV
894     cd = iconv_open("UTF-8", avctx->sub_charenc);
895     av_assert0(cd != (iconv_t)-1);
896
897     inb = inpkt->data;
898     inl = inpkt->size;
899
900     if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
901         av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
902         ret = AVERROR(ENOMEM);
903         goto end;
904     }
905
906     ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
907     if (ret < 0)
908         goto end;
909     outpkt->buf  = tmp.buf;
910     outpkt->data = tmp.data;
911     outpkt->size = tmp.size;
912     outb = outpkt->data;
913     outl = outpkt->size;
914
915     if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
916         iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
917         outl >= outpkt->size || inl != 0) {
918         ret = FFMIN(AVERROR(errno), -1);
919         av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
920                "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
921         av_packet_unref(&tmp);
922         goto end;
923     }
924     outpkt->size -= outl;
925     memset(outpkt->data + outpkt->size, 0, outl);
926
927 end:
928     if (cd != (iconv_t)-1)
929         iconv_close(cd);
930     return ret;
931 #else
932     av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
933     return AVERROR(EINVAL);
934 #endif
935 }
936
937 static int utf8_check(const uint8_t *str)
938 {
939     const uint8_t *byte;
940     uint32_t codepoint, min;
941
942     while (*str) {
943         byte = str;
944         GET_UTF8(codepoint, *(byte++), return 0;);
945         min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
946               1 << (5 * (byte - str) - 4);
947         if (codepoint < min || codepoint >= 0x110000 ||
948             codepoint == 0xFFFE /* BOM */ ||
949             codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
950             return 0;
951         str = byte;
952     }
953     return 1;
954 }
955
956 #if FF_API_ASS_TIMING
957 static void insert_ts(AVBPrint *buf, int ts)
958 {
959     if (ts == -1) {
960         av_bprintf(buf, "9:59:59.99,");
961     } else {
962         int h, m, s;
963
964         h = ts/360000;  ts -= 360000*h;
965         m = ts/  6000;  ts -=   6000*m;
966         s = ts/   100;  ts -=    100*s;
967         av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
968     }
969 }
970
971 static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
972 {
973     int i;
974     AVBPrint buf;
975
976     av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
977
978     for (i = 0; i < sub->num_rects; i++) {
979         char *final_dialog;
980         const char *dialog;
981         AVSubtitleRect *rect = sub->rects[i];
982         int ts_start, ts_duration = -1;
983         long int layer;
984
985         if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
986             continue;
987
988         av_bprint_clear(&buf);
989
990         /* skip ReadOrder */
991         dialog = strchr(rect->ass, ',');
992         if (!dialog)
993             continue;
994         dialog++;
995
996         /* extract Layer or Marked */
997         layer = strtol(dialog, (char**)&dialog, 10);
998         if (*dialog != ',')
999             continue;
1000         dialog++;
1001
1002         /* rescale timing to ASS time base (ms) */
1003         ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
1004         if (pkt->duration != -1)
1005             ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
1006         sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
1007
1008         /* construct ASS (standalone file form with timestamps) string */
1009         av_bprintf(&buf, "Dialogue: %ld,", layer);
1010         insert_ts(&buf, ts_start);
1011         insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
1012         av_bprintf(&buf, "%s\r\n", dialog);
1013
1014         final_dialog = av_strdup(buf.str);
1015         if (!av_bprint_is_complete(&buf) || !final_dialog) {
1016             av_freep(&final_dialog);
1017             av_bprint_finalize(&buf, NULL);
1018             return AVERROR(ENOMEM);
1019         }
1020         av_freep(&rect->ass);
1021         rect->ass = final_dialog;
1022     }
1023
1024     av_bprint_finalize(&buf, NULL);
1025     return 0;
1026 }
1027 #endif
1028
1029 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1030                              int *got_sub_ptr,
1031                              AVPacket *avpkt)
1032 {
1033     int i, ret = 0;
1034
1035     if (!avpkt->data && avpkt->size) {
1036         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1037         return AVERROR(EINVAL);
1038     }
1039     if (!avctx->codec)
1040         return AVERROR(EINVAL);
1041     if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
1042         av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
1043         return AVERROR(EINVAL);
1044     }
1045
1046     *got_sub_ptr = 0;
1047     get_subtitle_defaults(sub);
1048
1049     if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
1050         AVPacket pkt_recoded = *avpkt;
1051
1052         ret = recode_subtitle(avctx, &pkt_recoded, avpkt);
1053         if (ret < 0) {
1054             *got_sub_ptr = 0;
1055         } else {
1056              ret = extract_packet_props(avctx->internal, &pkt_recoded);
1057              if (ret < 0)
1058                 return ret;
1059
1060             if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
1061                 sub->pts = av_rescale_q(avpkt->pts,
1062                                         avctx->pkt_timebase, AV_TIME_BASE_Q);
1063             ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
1064             av_assert1((ret >= 0) >= !!*got_sub_ptr &&
1065                        !!*got_sub_ptr >= !!sub->num_rects);
1066
1067 #if FF_API_ASS_TIMING
1068             if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
1069                 && *got_sub_ptr && sub->num_rects) {
1070                 const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
1071                                                               : avctx->time_base;
1072                 int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
1073                 if (err < 0)
1074                     ret = err;
1075             }
1076 #endif
1077
1078             if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
1079                 avctx->pkt_timebase.num) {
1080                 AVRational ms = { 1, 1000 };
1081                 sub->end_display_time = av_rescale_q(avpkt->duration,
1082                                                      avctx->pkt_timebase, ms);
1083             }
1084
1085             if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
1086                 sub->format = 0;
1087             else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
1088                 sub->format = 1;
1089
1090             for (i = 0; i < sub->num_rects; i++) {
1091                 if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_IGNORE &&
1092                     sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
1093                     av_log(avctx, AV_LOG_ERROR,
1094                            "Invalid UTF-8 in decoded subtitles text; "
1095                            "maybe missing -sub_charenc option\n");
1096                     avsubtitle_free(sub);
1097                     ret = AVERROR_INVALIDDATA;
1098                     break;
1099                 }
1100             }
1101
1102             if (avpkt->data != pkt_recoded.data) { // did we recode?
1103                 /* prevent from destroying side data from original packet */
1104                 pkt_recoded.side_data = NULL;
1105                 pkt_recoded.side_data_elems = 0;
1106
1107                 av_packet_unref(&pkt_recoded);
1108             }
1109         }
1110
1111         if (*got_sub_ptr)
1112             avctx->frame_number++;
1113     }
1114
1115     return ret;
1116 }
1117
1118 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *avctx,
1119                                               const enum AVPixelFormat *fmt)
1120 {
1121     const AVPixFmtDescriptor *desc;
1122     const AVCodecHWConfig *config;
1123     int i, n;
1124
1125     // If a device was supplied when the codec was opened, assume that the
1126     // user wants to use it.
1127     if (avctx->hw_device_ctx && avctx->codec->hw_configs) {
1128         AVHWDeviceContext *device_ctx =
1129             (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1130         for (i = 0;; i++) {
1131             config = &avctx->codec->hw_configs[i]->public;
1132             if (!config)
1133                 break;
1134             if (!(config->methods &
1135                   AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
1136                 continue;
1137             if (device_ctx->type != config->device_type)
1138                 continue;
1139             for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1140                 if (config->pix_fmt == fmt[n])
1141                     return fmt[n];
1142             }
1143         }
1144     }
1145     // No device or other setup, so we have to choose from things which
1146     // don't any other external information.
1147
1148     // If the last element of the list is a software format, choose it
1149     // (this should be best software format if any exist).
1150     for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1151     desc = av_pix_fmt_desc_get(fmt[n - 1]);
1152     if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1153         return fmt[n - 1];
1154
1155     // Finally, traverse the list in order and choose the first entry
1156     // with no external dependencies (if there is no hardware configuration
1157     // information available then this just picks the first entry).
1158     for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
1159         for (i = 0;; i++) {
1160             config = avcodec_get_hw_config(avctx->codec, i);
1161             if (!config)
1162                 break;
1163             if (config->pix_fmt == fmt[n])
1164                 break;
1165         }
1166         if (!config) {
1167             // No specific config available, so the decoder must be able
1168             // to handle this format without any additional setup.
1169             return fmt[n];
1170         }
1171         if (config->methods & AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1172             // Usable with only internal setup.
1173             return fmt[n];
1174         }
1175     }
1176
1177     // Nothing is usable, give up.
1178     return AV_PIX_FMT_NONE;
1179 }
1180
1181 int ff_decode_get_hw_frames_ctx(AVCodecContext *avctx,
1182                                 enum AVHWDeviceType dev_type)
1183 {
1184     AVHWDeviceContext *device_ctx;
1185     AVHWFramesContext *frames_ctx;
1186     int ret;
1187
1188     if (!avctx->hwaccel)
1189         return AVERROR(ENOSYS);
1190
1191     if (avctx->hw_frames_ctx)
1192         return 0;
1193     if (!avctx->hw_device_ctx) {
1194         av_log(avctx, AV_LOG_ERROR, "A hardware frames or device context is "
1195                 "required for hardware accelerated decoding.\n");
1196         return AVERROR(EINVAL);
1197     }
1198
1199     device_ctx = (AVHWDeviceContext *)avctx->hw_device_ctx->data;
1200     if (device_ctx->type != dev_type) {
1201         av_log(avctx, AV_LOG_ERROR, "Device type %s expected for hardware "
1202                "decoding, but got %s.\n", av_hwdevice_get_type_name(dev_type),
1203                av_hwdevice_get_type_name(device_ctx->type));
1204         return AVERROR(EINVAL);
1205     }
1206
1207     ret = avcodec_get_hw_frames_parameters(avctx,
1208                                            avctx->hw_device_ctx,
1209                                            avctx->hwaccel->pix_fmt,
1210                                            &avctx->hw_frames_ctx);
1211     if (ret < 0)
1212         return ret;
1213
1214     frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1215
1216
1217     if (frames_ctx->initial_pool_size) {
1218         // We guarantee 4 base work surfaces. The function above guarantees 1
1219         // (the absolute minimum), so add the missing count.
1220         frames_ctx->initial_pool_size += 3;
1221     }
1222
1223     ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
1224     if (ret < 0) {
1225         av_buffer_unref(&avctx->hw_frames_ctx);
1226         return ret;
1227     }
1228
1229     return 0;
1230 }
1231
1232 int avcodec_get_hw_frames_parameters(AVCodecContext *avctx,
1233                                      AVBufferRef *device_ref,
1234                                      enum AVPixelFormat hw_pix_fmt,
1235                                      AVBufferRef **out_frames_ref)
1236 {
1237     AVBufferRef *frames_ref = NULL;
1238     const AVCodecHWConfigInternal *hw_config;
1239     const AVHWAccel *hwa;
1240     int i, ret;
1241
1242     for (i = 0;; i++) {
1243         hw_config = avctx->codec->hw_configs[i];
1244         if (!hw_config)
1245             return AVERROR(ENOENT);
1246         if (hw_config->public.pix_fmt == hw_pix_fmt)
1247             break;
1248     }
1249
1250     hwa = hw_config->hwaccel;
1251     if (!hwa || !hwa->frame_params)
1252         return AVERROR(ENOENT);
1253
1254     frames_ref = av_hwframe_ctx_alloc(device_ref);
1255     if (!frames_ref)
1256         return AVERROR(ENOMEM);
1257
1258     ret = hwa->frame_params(avctx, frames_ref);
1259     if (ret >= 0) {
1260         AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frames_ref->data;
1261
1262         if (frames_ctx->initial_pool_size) {
1263             // If the user has requested that extra output surfaces be
1264             // available then add them here.
1265             if (avctx->extra_hw_frames > 0)
1266                 frames_ctx->initial_pool_size += avctx->extra_hw_frames;
1267
1268             // If frame threading is enabled then an extra surface per thread
1269             // is also required.
1270             if (avctx->active_thread_type & FF_THREAD_FRAME)
1271                 frames_ctx->initial_pool_size += avctx->thread_count;
1272         }
1273
1274         *out_frames_ref = frames_ref;
1275     } else {
1276         av_buffer_unref(&frames_ref);
1277     }
1278     return ret;
1279 }
1280
1281 static int hwaccel_init(AVCodecContext *avctx,
1282                         const AVCodecHWConfigInternal *hw_config)
1283 {
1284     const AVHWAccel *hwaccel;
1285     int err;
1286
1287     hwaccel = hw_config->hwaccel;
1288     if (hwaccel->capabilities & AV_HWACCEL_CODEC_CAP_EXPERIMENTAL &&
1289         avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1290         av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
1291                hwaccel->name);
1292         return AVERROR_PATCHWELCOME;
1293     }
1294
1295     if (hwaccel->priv_data_size) {
1296         avctx->internal->hwaccel_priv_data =
1297             av_mallocz(hwaccel->priv_data_size);
1298         if (!avctx->internal->hwaccel_priv_data)
1299             return AVERROR(ENOMEM);
1300     }
1301
1302     avctx->hwaccel = hwaccel;
1303     if (hwaccel->init) {
1304         err = hwaccel->init(avctx);
1305         if (err < 0) {
1306             av_log(avctx, AV_LOG_ERROR, "Failed setup for format %s: "
1307                    "hwaccel initialisation returned error.\n",
1308                    av_get_pix_fmt_name(hw_config->public.pix_fmt));
1309             av_freep(&avctx->internal->hwaccel_priv_data);
1310             avctx->hwaccel = NULL;
1311             return err;
1312         }
1313     }
1314
1315     return 0;
1316 }
1317
1318 static void hwaccel_uninit(AVCodecContext *avctx)
1319 {
1320     if (avctx->hwaccel && avctx->hwaccel->uninit)
1321         avctx->hwaccel->uninit(avctx);
1322
1323     av_freep(&avctx->internal->hwaccel_priv_data);
1324
1325     avctx->hwaccel = NULL;
1326
1327     av_buffer_unref(&avctx->hw_frames_ctx);
1328 }
1329
1330 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1331 {
1332     const AVPixFmtDescriptor *desc;
1333     enum AVPixelFormat *choices;
1334     enum AVPixelFormat ret, user_choice;
1335     const AVCodecHWConfigInternal *hw_config;
1336     const AVCodecHWConfig *config;
1337     int i, n, err;
1338
1339     // Find end of list.
1340     for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1341     // Must contain at least one entry.
1342     av_assert0(n >= 1);
1343     // If a software format is available, it must be the last entry.
1344     desc = av_pix_fmt_desc_get(fmt[n - 1]);
1345     if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
1346         // No software format is available.
1347     } else {
1348         avctx->sw_pix_fmt = fmt[n - 1];
1349     }
1350
1351     choices = av_malloc_array(n + 1, sizeof(*choices));
1352     if (!choices)
1353         return AV_PIX_FMT_NONE;
1354
1355     memcpy(choices, fmt, (n + 1) * sizeof(*choices));
1356
1357     for (;;) {
1358         // Remove the previous hwaccel, if there was one.
1359         hwaccel_uninit(avctx);
1360
1361         user_choice = avctx->get_format(avctx, choices);
1362         if (user_choice == AV_PIX_FMT_NONE) {
1363             // Explicitly chose nothing, give up.
1364             ret = AV_PIX_FMT_NONE;
1365             break;
1366         }
1367
1368         desc = av_pix_fmt_desc_get(user_choice);
1369         if (!desc) {
1370             av_log(avctx, AV_LOG_ERROR, "Invalid format returned by "
1371                    "get_format() callback.\n");
1372             ret = AV_PIX_FMT_NONE;
1373             break;
1374         }
1375         av_log(avctx, AV_LOG_DEBUG, "Format %s chosen by get_format().\n",
1376                desc->name);
1377
1378         for (i = 0; i < n; i++) {
1379             if (choices[i] == user_choice)
1380                 break;
1381         }
1382         if (i == n) {
1383             av_log(avctx, AV_LOG_ERROR, "Invalid return from get_format(): "
1384                    "%s not in possible list.\n", desc->name);
1385             break;
1386         }
1387
1388         if (avctx->codec->hw_configs) {
1389             for (i = 0;; i++) {
1390                 hw_config = avctx->codec->hw_configs[i];
1391                 if (!hw_config)
1392                     break;
1393                 if (hw_config->public.pix_fmt == user_choice)
1394                     break;
1395             }
1396         } else {
1397             hw_config = NULL;
1398         }
1399
1400         if (!hw_config) {
1401             // No config available, so no extra setup required.
1402             ret = user_choice;
1403             break;
1404         }
1405         config = &hw_config->public;
1406
1407         if (config->methods &
1408             AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX &&
1409             avctx->hw_frames_ctx) {
1410             const AVHWFramesContext *frames_ctx =
1411                 (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1412             if (frames_ctx->format != user_choice) {
1413                 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1414                        "does not match the format of the provided frames "
1415                        "context.\n", desc->name);
1416                 goto try_again;
1417             }
1418         } else if (config->methods &
1419                    AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
1420                    avctx->hw_device_ctx) {
1421             const AVHWDeviceContext *device_ctx =
1422                 (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1423             if (device_ctx->type != config->device_type) {
1424                 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1425                        "does not match the type of the provided device "
1426                        "context.\n", desc->name);
1427                 goto try_again;
1428             }
1429         } else if (config->methods &
1430                    AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1431             // Internal-only setup, no additional configuration.
1432         } else if (config->methods &
1433                    AV_CODEC_HW_CONFIG_METHOD_AD_HOC) {
1434             // Some ad-hoc configuration we can't see and can't check.
1435         } else {
1436             av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1437                    "missing configuration.\n", desc->name);
1438             goto try_again;
1439         }
1440         if (hw_config->hwaccel) {
1441             av_log(avctx, AV_LOG_DEBUG, "Format %s requires hwaccel "
1442                    "initialisation.\n", desc->name);
1443             err = hwaccel_init(avctx, hw_config);
1444             if (err < 0)
1445                 goto try_again;
1446         }
1447         ret = user_choice;
1448         break;
1449
1450     try_again:
1451         av_log(avctx, AV_LOG_DEBUG, "Format %s not usable, retrying "
1452                "get_format() without it.\n", desc->name);
1453         for (i = 0; i < n; i++) {
1454             if (choices[i] == user_choice)
1455                 break;
1456         }
1457         for (; i + 1 < n; i++)
1458             choices[i] = choices[i + 1];
1459         --n;
1460     }
1461
1462     av_freep(&choices);
1463     return ret;
1464 }
1465
1466 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
1467 {
1468     FramePool *pool = avctx->internal->pool;
1469     int i, ret;
1470
1471     switch (avctx->codec_type) {
1472     case AVMEDIA_TYPE_VIDEO: {
1473         uint8_t *data[4];
1474         int linesize[4];
1475         int size[4] = { 0 };
1476         int w = frame->width;
1477         int h = frame->height;
1478         int tmpsize, unaligned;
1479
1480         if (pool->format == frame->format &&
1481             pool->width == frame->width && pool->height == frame->height)
1482             return 0;
1483
1484         avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
1485
1486         do {
1487             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
1488             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
1489             ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
1490             if (ret < 0)
1491                 return ret;
1492             // increase alignment of w for next try (rhs gives the lowest bit set in w)
1493             w += w & ~(w - 1);
1494
1495             unaligned = 0;
1496             for (i = 0; i < 4; i++)
1497                 unaligned |= linesize[i] % pool->stride_align[i];
1498         } while (unaligned);
1499
1500         tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
1501                                          NULL, linesize);
1502         if (tmpsize < 0)
1503             return -1;
1504
1505         for (i = 0; i < 3 && data[i + 1]; i++)
1506             size[i] = data[i + 1] - data[i];
1507         size[i] = tmpsize - (data[i] - data[0]);
1508
1509         for (i = 0; i < 4; i++) {
1510             av_buffer_pool_uninit(&pool->pools[i]);
1511             pool->linesize[i] = linesize[i];
1512             if (size[i]) {
1513                 pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
1514                                                      CONFIG_MEMORY_POISONING ?
1515                                                         NULL :
1516                                                         av_buffer_allocz);
1517                 if (!pool->pools[i]) {
1518                     ret = AVERROR(ENOMEM);
1519                     goto fail;
1520                 }
1521             }
1522         }
1523         pool->format = frame->format;
1524         pool->width  = frame->width;
1525         pool->height = frame->height;
1526
1527         break;
1528         }
1529     case AVMEDIA_TYPE_AUDIO: {
1530         int ch     = frame->channels; //av_get_channel_layout_nb_channels(frame->channel_layout);
1531         int planar = av_sample_fmt_is_planar(frame->format);
1532         int planes = planar ? ch : 1;
1533
1534         if (pool->format == frame->format && pool->planes == planes &&
1535             pool->channels == ch && frame->nb_samples == pool->samples)
1536             return 0;
1537
1538         av_buffer_pool_uninit(&pool->pools[0]);
1539         ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
1540                                          frame->nb_samples, frame->format, 0);
1541         if (ret < 0)
1542             goto fail;
1543
1544         pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
1545         if (!pool->pools[0]) {
1546             ret = AVERROR(ENOMEM);
1547             goto fail;
1548         }
1549
1550         pool->format     = frame->format;
1551         pool->planes     = planes;
1552         pool->channels   = ch;
1553         pool->samples = frame->nb_samples;
1554         break;
1555         }
1556     default: av_assert0(0);
1557     }
1558     return 0;
1559 fail:
1560     for (i = 0; i < 4; i++)
1561         av_buffer_pool_uninit(&pool->pools[i]);
1562     pool->format = -1;
1563     pool->planes = pool->channels = pool->samples = 0;
1564     pool->width  = pool->height = 0;
1565     return ret;
1566 }
1567
1568 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
1569 {
1570     FramePool *pool = avctx->internal->pool;
1571     int planes = pool->planes;
1572     int i;
1573
1574     frame->linesize[0] = pool->linesize[0];
1575
1576     if (planes > AV_NUM_DATA_POINTERS) {
1577         frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
1578         frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
1579         frame->extended_buf  = av_mallocz_array(frame->nb_extended_buf,
1580                                           sizeof(*frame->extended_buf));
1581         if (!frame->extended_data || !frame->extended_buf) {
1582             av_freep(&frame->extended_data);
1583             av_freep(&frame->extended_buf);
1584             return AVERROR(ENOMEM);
1585         }
1586     } else {
1587         frame->extended_data = frame->data;
1588         av_assert0(frame->nb_extended_buf == 0);
1589     }
1590
1591     for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
1592         frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
1593         if (!frame->buf[i])
1594             goto fail;
1595         frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
1596     }
1597     for (i = 0; i < frame->nb_extended_buf; i++) {
1598         frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
1599         if (!frame->extended_buf[i])
1600             goto fail;
1601         frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
1602     }
1603
1604     if (avctx->debug & FF_DEBUG_BUFFERS)
1605         av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
1606
1607     return 0;
1608 fail:
1609     av_frame_unref(frame);
1610     return AVERROR(ENOMEM);
1611 }
1612
1613 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
1614 {
1615     FramePool *pool = s->internal->pool;
1616     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
1617     int i;
1618
1619     if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
1620         av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
1621         return -1;
1622     }
1623
1624     if (!desc) {
1625         av_log(s, AV_LOG_ERROR,
1626             "Unable to get pixel format descriptor for format %s\n",
1627             av_get_pix_fmt_name(pic->format));
1628         return AVERROR(EINVAL);
1629     }
1630
1631     memset(pic->data, 0, sizeof(pic->data));
1632     pic->extended_data = pic->data;
1633
1634     for (i = 0; i < 4 && pool->pools[i]; i++) {
1635         pic->linesize[i] = pool->linesize[i];
1636
1637         pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
1638         if (!pic->buf[i])
1639             goto fail;
1640
1641         pic->data[i] = pic->buf[i]->data;
1642     }
1643     for (; i < AV_NUM_DATA_POINTERS; i++) {
1644         pic->data[i] = NULL;
1645         pic->linesize[i] = 0;
1646     }
1647     if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
1648         ((desc->flags & FF_PSEUDOPAL) && pic->data[1]))
1649         avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
1650
1651     if (s->debug & FF_DEBUG_BUFFERS)
1652         av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
1653
1654     return 0;
1655 fail:
1656     av_frame_unref(pic);
1657     return AVERROR(ENOMEM);
1658 }
1659
1660 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
1661 {
1662     int ret;
1663
1664     if (avctx->hw_frames_ctx) {
1665         ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
1666         frame->width  = avctx->coded_width;
1667         frame->height = avctx->coded_height;
1668         return ret;
1669     }
1670
1671     if ((ret = update_frame_pool(avctx, frame)) < 0)
1672         return ret;
1673
1674     switch (avctx->codec_type) {
1675     case AVMEDIA_TYPE_VIDEO:
1676         return video_get_buffer(avctx, frame);
1677     case AVMEDIA_TYPE_AUDIO:
1678         return audio_get_buffer(avctx, frame);
1679     default:
1680         return -1;
1681     }
1682 }
1683
1684 static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
1685 {
1686     int size;
1687     const uint8_t *side_metadata;
1688
1689     AVDictionary **frame_md = &frame->metadata;
1690
1691     side_metadata = av_packet_get_side_data(avpkt,
1692                                             AV_PKT_DATA_STRINGS_METADATA, &size);
1693     return av_packet_unpack_dictionary(side_metadata, size, frame_md);
1694 }
1695
1696 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1697 {
1698     const AVPacket *pkt = avctx->internal->last_pkt_props;
1699     int i;
1700     static const struct {
1701         enum AVPacketSideDataType packet;
1702         enum AVFrameSideDataType frame;
1703     } sd[] = {
1704         { AV_PKT_DATA_REPLAYGAIN ,                AV_FRAME_DATA_REPLAYGAIN },
1705         { AV_PKT_DATA_DISPLAYMATRIX,              AV_FRAME_DATA_DISPLAYMATRIX },
1706         { AV_PKT_DATA_SPHERICAL,                  AV_FRAME_DATA_SPHERICAL },
1707         { AV_PKT_DATA_STEREO3D,                   AV_FRAME_DATA_STEREO3D },
1708         { AV_PKT_DATA_AUDIO_SERVICE_TYPE,         AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
1709         { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
1710         { AV_PKT_DATA_CONTENT_LIGHT_LEVEL,        AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
1711         { AV_PKT_DATA_A53_CC,                     AV_FRAME_DATA_A53_CC },
1712     };
1713
1714     if (pkt) {
1715         frame->pts = pkt->pts;
1716 #if FF_API_PKT_PTS
1717 FF_DISABLE_DEPRECATION_WARNINGS
1718         frame->pkt_pts = pkt->pts;
1719 FF_ENABLE_DEPRECATION_WARNINGS
1720 #endif
1721         frame->pkt_pos      = pkt->pos;
1722         frame->pkt_duration = pkt->duration;
1723         frame->pkt_size     = pkt->size;
1724
1725         for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
1726             int size;
1727             uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
1728             if (packet_sd) {
1729                 AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
1730                                                                    sd[i].frame,
1731                                                                    size);
1732                 if (!frame_sd)
1733                     return AVERROR(ENOMEM);
1734
1735                 memcpy(frame_sd->data, packet_sd, size);
1736             }
1737         }
1738         add_metadata_from_side_data(pkt, frame);
1739
1740         if (pkt->flags & AV_PKT_FLAG_DISCARD) {
1741             frame->flags |= AV_FRAME_FLAG_DISCARD;
1742         } else {
1743             frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
1744         }
1745     }
1746     frame->reordered_opaque = avctx->reordered_opaque;
1747
1748     if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
1749         frame->color_primaries = avctx->color_primaries;
1750     if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
1751         frame->color_trc = avctx->color_trc;
1752     if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
1753         frame->colorspace = avctx->colorspace;
1754     if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
1755         frame->color_range = avctx->color_range;
1756     if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
1757         frame->chroma_location = avctx->chroma_sample_location;
1758
1759     switch (avctx->codec->type) {
1760     case AVMEDIA_TYPE_VIDEO:
1761         frame->format              = avctx->pix_fmt;
1762         if (!frame->sample_aspect_ratio.num)
1763             frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
1764
1765         if (frame->width && frame->height &&
1766             av_image_check_sar(frame->width, frame->height,
1767                                frame->sample_aspect_ratio) < 0) {
1768             av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1769                    frame->sample_aspect_ratio.num,
1770                    frame->sample_aspect_ratio.den);
1771             frame->sample_aspect_ratio = (AVRational){ 0, 1 };
1772         }
1773
1774         break;
1775     case AVMEDIA_TYPE_AUDIO:
1776         if (!frame->sample_rate)
1777             frame->sample_rate    = avctx->sample_rate;
1778         if (frame->format < 0)
1779             frame->format         = avctx->sample_fmt;
1780         if (!frame->channel_layout) {
1781             if (avctx->channel_layout) {
1782                  if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
1783                      avctx->channels) {
1784                      av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
1785                             "configuration.\n");
1786                      return AVERROR(EINVAL);
1787                  }
1788
1789                 frame->channel_layout = avctx->channel_layout;
1790             } else {
1791                 if (avctx->channels > FF_SANE_NB_CHANNELS) {
1792                     av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
1793                            avctx->channels);
1794                     return AVERROR(ENOSYS);
1795                 }
1796             }
1797         }
1798         frame->channels = avctx->channels;
1799         break;
1800     }
1801     return 0;
1802 }
1803
1804 static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
1805 {
1806     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1807         int i;
1808         int num_planes = av_pix_fmt_count_planes(frame->format);
1809         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
1810         int flags = desc ? desc->flags : 0;
1811         if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
1812             num_planes = 2;
1813         if ((flags & FF_PSEUDOPAL) && frame->data[1])
1814             num_planes = 2;
1815         for (i = 0; i < num_planes; i++) {
1816             av_assert0(frame->data[i]);
1817         }
1818         // For formats without data like hwaccel allow unused pointers to be non-NULL.
1819         for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
1820             if (frame->data[i])
1821                 av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
1822             frame->data[i] = NULL;
1823         }
1824     }
1825 }
1826
1827 static void decode_data_free(void *opaque, uint8_t *data)
1828 {
1829     FrameDecodeData *fdd = (FrameDecodeData*)data;
1830
1831     if (fdd->post_process_opaque_free)
1832         fdd->post_process_opaque_free(fdd->post_process_opaque);
1833
1834     if (fdd->hwaccel_priv_free)
1835         fdd->hwaccel_priv_free(fdd->hwaccel_priv);
1836
1837     av_freep(&fdd);
1838 }
1839
1840 int ff_attach_decode_data(AVFrame *frame)
1841 {
1842     AVBufferRef *fdd_buf;
1843     FrameDecodeData *fdd;
1844
1845     av_assert1(!frame->private_ref);
1846     av_buffer_unref(&frame->private_ref);
1847
1848     fdd = av_mallocz(sizeof(*fdd));
1849     if (!fdd)
1850         return AVERROR(ENOMEM);
1851
1852     fdd_buf = av_buffer_create((uint8_t*)fdd, sizeof(*fdd), decode_data_free,
1853                                NULL, AV_BUFFER_FLAG_READONLY);
1854     if (!fdd_buf) {
1855         av_freep(&fdd);
1856         return AVERROR(ENOMEM);
1857     }
1858
1859     frame->private_ref = fdd_buf;
1860
1861     return 0;
1862 }
1863
1864 static int get_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
1865 {
1866     const AVHWAccel *hwaccel = avctx->hwaccel;
1867     int override_dimensions = 1;
1868     int ret;
1869
1870     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1871         if ((ret = av_image_check_size2(FFALIGN(avctx->width, STRIDE_ALIGN), avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) {
1872             av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
1873             return AVERROR(EINVAL);
1874         }
1875
1876         if (frame->width <= 0 || frame->height <= 0) {
1877             frame->width  = FFMAX(avctx->width,  AV_CEIL_RSHIFT(avctx->coded_width,  avctx->lowres));
1878             frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
1879             override_dimensions = 0;
1880         }
1881
1882         if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
1883             av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
1884             return AVERROR(EINVAL);
1885         }
1886     }
1887     ret = ff_decode_frame_props(avctx, frame);
1888     if (ret < 0)
1889         return ret;
1890
1891     if (hwaccel) {
1892         if (hwaccel->alloc_frame) {
1893             ret = hwaccel->alloc_frame(avctx, frame);
1894             goto end;
1895         }
1896     } else
1897         avctx->sw_pix_fmt = avctx->pix_fmt;
1898
1899     ret = avctx->get_buffer2(avctx, frame, flags);
1900     if (ret < 0)
1901         goto end;
1902
1903     validate_avframe_allocation(avctx, frame);
1904
1905     ret = ff_attach_decode_data(frame);
1906     if (ret < 0)
1907         goto end;
1908
1909 end:
1910     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
1911         !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
1912         frame->width  = avctx->width;
1913         frame->height = avctx->height;
1914     }
1915
1916     if (ret < 0)
1917         av_frame_unref(frame);
1918
1919     return ret;
1920 }
1921
1922 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1923 {
1924     int ret = get_buffer_internal(avctx, frame, flags);
1925     if (ret < 0) {
1926         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1927         frame->width = frame->height = 0;
1928     }
1929     return ret;
1930 }
1931
1932 static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame)
1933 {
1934     AVFrame *tmp;
1935     int ret;
1936
1937     av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1938
1939     if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
1940         av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
1941                frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
1942         av_frame_unref(frame);
1943     }
1944
1945     if (!frame->data[0])
1946         return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1947
1948     if (av_frame_is_writable(frame))
1949         return ff_decode_frame_props(avctx, frame);
1950
1951     tmp = av_frame_alloc();
1952     if (!tmp)
1953         return AVERROR(ENOMEM);
1954
1955     av_frame_move_ref(tmp, frame);
1956
1957     ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1958     if (ret < 0) {
1959         av_frame_free(&tmp);
1960         return ret;
1961     }
1962
1963     av_frame_copy(frame, tmp);
1964     av_frame_free(&tmp);
1965
1966     return 0;
1967 }
1968
1969 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
1970 {
1971     int ret = reget_buffer_internal(avctx, frame);
1972     if (ret < 0)
1973         av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1974     return ret;
1975 }
1976
1977 static void bsfs_flush(AVCodecContext *avctx)
1978 {
1979     DecodeFilterContext *s = &avctx->internal->filter;
1980
1981     for (int i = 0; i < s->nb_bsfs; i++)
1982         av_bsf_flush(s->bsfs[i]);
1983 }
1984
1985 void avcodec_flush_buffers(AVCodecContext *avctx)
1986 {
1987     avctx->internal->draining      = 0;
1988     avctx->internal->draining_done = 0;
1989     avctx->internal->nb_draining_errors = 0;
1990     av_frame_unref(avctx->internal->buffer_frame);
1991     av_frame_unref(avctx->internal->compat_decode_frame);
1992     av_packet_unref(avctx->internal->buffer_pkt);
1993     avctx->internal->buffer_pkt_valid = 0;
1994
1995     av_packet_unref(avctx->internal->ds.in_pkt);
1996
1997     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1998         ff_thread_flush(avctx);
1999     else if (avctx->codec->flush)
2000         avctx->codec->flush(avctx);
2001
2002     avctx->pts_correction_last_pts =
2003     avctx->pts_correction_last_dts = INT64_MIN;
2004
2005     bsfs_flush(avctx);
2006
2007     if (!avctx->refcounted_frames)
2008         av_frame_unref(avctx->internal->to_free);
2009 }
2010
2011 void ff_decode_bsfs_uninit(AVCodecContext *avctx)
2012 {
2013     DecodeFilterContext *s = &avctx->internal->filter;
2014     int i;
2015
2016     for (i = 0; i < s->nb_bsfs; i++)
2017         av_bsf_free(&s->bsfs[i]);
2018     av_freep(&s->bsfs);
2019     s->nb_bsfs = 0;
2020 }