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