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