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