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