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