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