]> git.sesse.net Git - ffmpeg/blob - libavcodec/decode.c
avutil/buffer: Switch AVBuffer API to size_t
[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     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         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(frame->pkt_dts!=AV_NOPTS_VALUE)
398                         frame->pkt_dts += diff_ts;
399                     if (frame->pkt_duration >= diff_ts)
400                         frame->pkt_duration -= diff_ts;
401                 } else {
402                     av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
403                 }
404                 av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
405                        avci->skip_samples, frame->nb_samples);
406                 *discarded_samples += avci->skip_samples;
407                 frame->nb_samples -= avci->skip_samples;
408                 avci->skip_samples = 0;
409             }
410         }
411
412         if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
413             !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
414             if (discard_padding == frame->nb_samples) {
415                 *discarded_samples += frame->nb_samples;
416                 got_frame = 0;
417             } else {
418                 if(avctx->pkt_timebase.num && avctx->sample_rate) {
419                     int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
420                                                    (AVRational){1, avctx->sample_rate},
421                                                    avctx->pkt_timebase);
422                     frame->pkt_duration = diff_ts;
423                 } else {
424                     av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
425                 }
426                 av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
427                        (int)discard_padding, frame->nb_samples);
428                 frame->nb_samples -= discard_padding;
429             }
430         }
431
432         if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
433             AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
434             if (fside) {
435                 AV_WL32(fside->data, avci->skip_samples);
436                 AV_WL32(fside->data + 4, discard_padding);
437                 AV_WL8(fside->data + 8, skip_reason);
438                 AV_WL8(fside->data + 9, discard_reason);
439                 avci->skip_samples = 0;
440             }
441         }
442     }
443
444     if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
445         !avci->showed_multi_packet_warning &&
446         ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
447         av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
448         avci->showed_multi_packet_warning = 1;
449     }
450
451     if (!got_frame)
452         av_frame_unref(frame);
453
454     if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
455         ret = pkt->size;
456
457 #if FF_API_AVCTX_TIMEBASE
458     if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
459         avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
460 #endif
461
462     /* do not stop draining when actual_got_frame != 0 or ret < 0 */
463     /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */
464     if (avci->draining && !actual_got_frame) {
465         if (ret < 0) {
466             /* prevent infinite loop if a decoder wrongly always return error on draining */
467             /* reasonable nb_errors_max = maximum b frames + thread count */
468             int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
469                                 avctx->thread_count : 1);
470
471             if (avci->nb_draining_errors++ >= nb_errors_max) {
472                 av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
473                        "Stop draining and force EOF.\n");
474                 avci->draining_done = 1;
475                 ret = AVERROR_BUG;
476             }
477         } else {
478             avci->draining_done = 1;
479         }
480     }
481
482     if (ret >= pkt->size || ret < 0) {
483         av_packet_unref(pkt);
484         av_packet_unref(avci->last_pkt_props);
485     } else {
486         int consumed = ret;
487
488         pkt->data                += consumed;
489         pkt->size                -= consumed;
490         avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
491         pkt->pts                  = AV_NOPTS_VALUE;
492         pkt->dts                  = AV_NOPTS_VALUE;
493         avci->last_pkt_props->pts = AV_NOPTS_VALUE;
494         avci->last_pkt_props->dts = AV_NOPTS_VALUE;
495     }
496
497     if (got_frame)
498         av_assert0(frame->buf[0]);
499
500     return ret < 0 ? ret : 0;
501 }
502
503 static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
504 {
505     int ret;
506     int64_t discarded_samples = 0;
507
508     while (!frame->buf[0]) {
509         if (discarded_samples > avctx->max_samples)
510             return AVERROR(EAGAIN);
511         ret = decode_simple_internal(avctx, frame, &discarded_samples);
512         if (ret < 0)
513             return ret;
514     }
515
516     return 0;
517 }
518
519 static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
520 {
521     AVCodecInternal *avci = avctx->internal;
522     int ret;
523
524     av_assert0(!frame->buf[0]);
525
526     if (avctx->codec->receive_frame) {
527         ret = avctx->codec->receive_frame(avctx, frame);
528         if (ret != AVERROR(EAGAIN))
529             av_packet_unref(avci->last_pkt_props);
530     } else
531         ret = decode_simple_receive_frame(avctx, frame);
532
533     if (ret == AVERROR_EOF)
534         avci->draining_done = 1;
535
536     if (!ret) {
537         frame->best_effort_timestamp = guess_correct_pts(avctx,
538                                                          frame->pts,
539                                                          frame->pkt_dts);
540
541         /* the only case where decode data is not set should be decoders
542          * that do not call ff_get_buffer() */
543         av_assert0((frame->private_ref && frame->private_ref->size == sizeof(FrameDecodeData)) ||
544                    !(avctx->codec->capabilities & AV_CODEC_CAP_DR1));
545
546         if (frame->private_ref) {
547             FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
548
549             if (fdd->post_process) {
550                 ret = fdd->post_process(avctx, frame);
551                 if (ret < 0) {
552                     av_frame_unref(frame);
553                     return ret;
554                 }
555             }
556         }
557     }
558
559     /* free the per-frame decode data */
560     av_buffer_unref(&frame->private_ref);
561
562     return ret;
563 }
564
565 int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
566 {
567     AVCodecInternal *avci = avctx->internal;
568     int ret;
569
570     if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
571         return AVERROR(EINVAL);
572
573     if (avctx->internal->draining)
574         return AVERROR_EOF;
575
576     if (avpkt && !avpkt->size && avpkt->data)
577         return AVERROR(EINVAL);
578
579     av_packet_unref(avci->buffer_pkt);
580     if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
581         ret = av_packet_ref(avci->buffer_pkt, avpkt);
582         if (ret < 0)
583             return ret;
584     }
585
586     ret = av_bsf_send_packet(avci->bsf, avci->buffer_pkt);
587     if (ret < 0) {
588         av_packet_unref(avci->buffer_pkt);
589         return ret;
590     }
591
592     if (!avci->buffer_frame->buf[0]) {
593         ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
594         if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
595             return ret;
596     }
597
598     return 0;
599 }
600
601 static int apply_cropping(AVCodecContext *avctx, AVFrame *frame)
602 {
603     /* make sure we are noisy about decoders returning invalid cropping data */
604     if (frame->crop_left >= INT_MAX - frame->crop_right        ||
605         frame->crop_top  >= INT_MAX - frame->crop_bottom       ||
606         (frame->crop_left + frame->crop_right) >= frame->width ||
607         (frame->crop_top + frame->crop_bottom) >= frame->height) {
608         av_log(avctx, AV_LOG_WARNING,
609                "Invalid cropping information set by a decoder: "
610                "%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER" "
611                "(frame size %dx%d). This is a bug, please report it\n",
612                frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
613                frame->width, frame->height);
614         frame->crop_left   = 0;
615         frame->crop_right  = 0;
616         frame->crop_top    = 0;
617         frame->crop_bottom = 0;
618         return 0;
619     }
620
621     if (!avctx->apply_cropping)
622         return 0;
623
624     return av_frame_apply_cropping(frame, avctx->flags & AV_CODEC_FLAG_UNALIGNED ?
625                                           AV_FRAME_CROP_UNALIGNED : 0);
626 }
627
628 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
629 {
630     AVCodecInternal *avci = avctx->internal;
631     int ret, changed;
632
633     av_frame_unref(frame);
634
635     if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
636         return AVERROR(EINVAL);
637
638     if (avci->buffer_frame->buf[0]) {
639         av_frame_move_ref(frame, avci->buffer_frame);
640     } else {
641         ret = decode_receive_frame_internal(avctx, frame);
642         if (ret < 0)
643             return ret;
644     }
645
646     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
647         ret = apply_cropping(avctx, frame);
648         if (ret < 0) {
649             av_frame_unref(frame);
650             return ret;
651         }
652     }
653
654     avctx->frame_number++;
655
656     if (avctx->flags & AV_CODEC_FLAG_DROPCHANGED) {
657
658         if (avctx->frame_number == 1) {
659             avci->initial_format = frame->format;
660             switch(avctx->codec_type) {
661             case AVMEDIA_TYPE_VIDEO:
662                 avci->initial_width  = frame->width;
663                 avci->initial_height = frame->height;
664                 break;
665             case AVMEDIA_TYPE_AUDIO:
666                 avci->initial_sample_rate = frame->sample_rate ? frame->sample_rate :
667                                                                  avctx->sample_rate;
668                 avci->initial_channels       = frame->channels;
669                 avci->initial_channel_layout = frame->channel_layout;
670                 break;
671             }
672         }
673
674         if (avctx->frame_number > 1) {
675             changed = avci->initial_format != frame->format;
676
677             switch(avctx->codec_type) {
678             case AVMEDIA_TYPE_VIDEO:
679                 changed |= avci->initial_width  != frame->width ||
680                            avci->initial_height != frame->height;
681                 break;
682             case AVMEDIA_TYPE_AUDIO:
683                 changed |= avci->initial_sample_rate    != frame->sample_rate ||
684                            avci->initial_sample_rate    != avctx->sample_rate ||
685                            avci->initial_channels       != frame->channels ||
686                            avci->initial_channel_layout != frame->channel_layout;
687                 break;
688             }
689
690             if (changed) {
691                 avci->changed_frames_dropped++;
692                 av_log(avctx, AV_LOG_INFO, "dropped changed frame #%d pts %"PRId64
693                                             " drop count: %d \n",
694                                             avctx->frame_number, frame->pts,
695                                             avci->changed_frames_dropped);
696                 av_frame_unref(frame);
697                 return AVERROR_INPUT_CHANGED;
698             }
699         }
700     }
701     return 0;
702 }
703
704 static void get_subtitle_defaults(AVSubtitle *sub)
705 {
706     memset(sub, 0, sizeof(*sub));
707     sub->pts = AV_NOPTS_VALUE;
708 }
709
710 #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
711 static int recode_subtitle(AVCodecContext *avctx, AVPacket **outpkt,
712                            AVPacket *inpkt, AVPacket *buf_pkt)
713 {
714 #if CONFIG_ICONV
715     iconv_t cd = (iconv_t)-1;
716     int ret = 0;
717     char *inb, *outb;
718     size_t inl, outl;
719 #endif
720
721     if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0) {
722         *outpkt = inpkt;
723         return 0;
724     }
725
726 #if CONFIG_ICONV
727     inb = inpkt->data;
728     inl = inpkt->size;
729
730     if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
731         av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
732         return AVERROR(ERANGE);
733     }
734
735     cd = iconv_open("UTF-8", avctx->sub_charenc);
736     av_assert0(cd != (iconv_t)-1);
737
738     ret = av_new_packet(buf_pkt, inl * UTF8_MAX_BYTES);
739     if (ret < 0)
740         goto end;
741     ret = av_packet_copy_props(buf_pkt, inpkt);
742     if (ret < 0)
743         goto end;
744     outb = buf_pkt->data;
745     outl = buf_pkt->size;
746
747     if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
748         iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
749         outl >= buf_pkt->size || inl != 0) {
750         ret = FFMIN(AVERROR(errno), -1);
751         av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
752                "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
753         goto end;
754     }
755     buf_pkt->size -= outl;
756     memset(buf_pkt->data + buf_pkt->size, 0, outl);
757     *outpkt = buf_pkt;
758
759     ret = 0;
760 end:
761     if (ret < 0)
762         av_packet_unref(buf_pkt);
763     if (cd != (iconv_t)-1)
764         iconv_close(cd);
765     return ret;
766 #else
767     av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
768     return AVERROR(EINVAL);
769 #endif
770 }
771
772 static int utf8_check(const uint8_t *str)
773 {
774     const uint8_t *byte;
775     uint32_t codepoint, min;
776
777     while (*str) {
778         byte = str;
779         GET_UTF8(codepoint, *(byte++), return 0;);
780         min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
781               1 << (5 * (byte - str) - 4);
782         if (codepoint < min || codepoint >= 0x110000 ||
783             codepoint == 0xFFFE /* BOM */ ||
784             codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
785             return 0;
786         str = byte;
787     }
788     return 1;
789 }
790
791 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
792                              int *got_sub_ptr,
793                              AVPacket *avpkt)
794 {
795     int ret = 0;
796
797     if (!avpkt->data && avpkt->size) {
798         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
799         return AVERROR(EINVAL);
800     }
801     if (!avctx->codec)
802         return AVERROR(EINVAL);
803     if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
804         av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
805         return AVERROR(EINVAL);
806     }
807
808     *got_sub_ptr = 0;
809     get_subtitle_defaults(sub);
810
811     if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
812         AVCodecInternal *avci = avctx->internal;
813         AVPacket *pkt;
814
815         ret = recode_subtitle(avctx, &pkt, avpkt, avci->buffer_pkt);
816         if (ret < 0)
817             return ret;
818
819         if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
820             sub->pts = av_rescale_q(avpkt->pts,
821                                     avctx->pkt_timebase, AV_TIME_BASE_Q);
822         ret = avctx->codec->decode(avctx, sub, got_sub_ptr, pkt);
823         av_assert1((ret >= 0) >= !!*got_sub_ptr &&
824                    !!*got_sub_ptr >= !!sub->num_rects);
825
826         if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
827             avctx->pkt_timebase.num) {
828             AVRational ms = { 1, 1000 };
829             sub->end_display_time = av_rescale_q(avpkt->duration,
830                                                  avctx->pkt_timebase, ms);
831         }
832
833         if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
834             sub->format = 0;
835         else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
836             sub->format = 1;
837
838         for (unsigned i = 0; i < sub->num_rects; i++) {
839             if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_IGNORE &&
840                 sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
841                 av_log(avctx, AV_LOG_ERROR,
842                        "Invalid UTF-8 in decoded subtitles text; "
843                        "maybe missing -sub_charenc option\n");
844                 avsubtitle_free(sub);
845                 ret = AVERROR_INVALIDDATA;
846                 break;
847             }
848         }
849
850         if (*got_sub_ptr)
851             avctx->frame_number++;
852
853         if (pkt == avci->buffer_pkt) // did we recode?
854             av_packet_unref(avci->buffer_pkt);
855     }
856
857     return ret;
858 }
859
860 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *avctx,
861                                               const enum AVPixelFormat *fmt)
862 {
863     const AVPixFmtDescriptor *desc;
864     const AVCodecHWConfig *config;
865     int i, n;
866
867     // If a device was supplied when the codec was opened, assume that the
868     // user wants to use it.
869     if (avctx->hw_device_ctx && avctx->codec->hw_configs) {
870         AVHWDeviceContext *device_ctx =
871             (AVHWDeviceContext*)avctx->hw_device_ctx->data;
872         for (i = 0;; i++) {
873             config = &avctx->codec->hw_configs[i]->public;
874             if (!config)
875                 break;
876             if (!(config->methods &
877                   AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
878                 continue;
879             if (device_ctx->type != config->device_type)
880                 continue;
881             for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
882                 if (config->pix_fmt == fmt[n])
883                     return fmt[n];
884             }
885         }
886     }
887     // No device or other setup, so we have to choose from things which
888     // don't any other external information.
889
890     // If the last element of the list is a software format, choose it
891     // (this should be best software format if any exist).
892     for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
893     desc = av_pix_fmt_desc_get(fmt[n - 1]);
894     if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
895         return fmt[n - 1];
896
897     // Finally, traverse the list in order and choose the first entry
898     // with no external dependencies (if there is no hardware configuration
899     // information available then this just picks the first entry).
900     for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++) {
901         for (i = 0;; i++) {
902             config = avcodec_get_hw_config(avctx->codec, i);
903             if (!config)
904                 break;
905             if (config->pix_fmt == fmt[n])
906                 break;
907         }
908         if (!config) {
909             // No specific config available, so the decoder must be able
910             // to handle this format without any additional setup.
911             return fmt[n];
912         }
913         if (config->methods & AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
914             // Usable with only internal setup.
915             return fmt[n];
916         }
917     }
918
919     // Nothing is usable, give up.
920     return AV_PIX_FMT_NONE;
921 }
922
923 int ff_decode_get_hw_frames_ctx(AVCodecContext *avctx,
924                                 enum AVHWDeviceType dev_type)
925 {
926     AVHWDeviceContext *device_ctx;
927     AVHWFramesContext *frames_ctx;
928     int ret;
929
930     if (!avctx->hwaccel)
931         return AVERROR(ENOSYS);
932
933     if (avctx->hw_frames_ctx)
934         return 0;
935     if (!avctx->hw_device_ctx) {
936         av_log(avctx, AV_LOG_ERROR, "A hardware frames or device context is "
937                 "required for hardware accelerated decoding.\n");
938         return AVERROR(EINVAL);
939     }
940
941     device_ctx = (AVHWDeviceContext *)avctx->hw_device_ctx->data;
942     if (device_ctx->type != dev_type) {
943         av_log(avctx, AV_LOG_ERROR, "Device type %s expected for hardware "
944                "decoding, but got %s.\n", av_hwdevice_get_type_name(dev_type),
945                av_hwdevice_get_type_name(device_ctx->type));
946         return AVERROR(EINVAL);
947     }
948
949     ret = avcodec_get_hw_frames_parameters(avctx,
950                                            avctx->hw_device_ctx,
951                                            avctx->hwaccel->pix_fmt,
952                                            &avctx->hw_frames_ctx);
953     if (ret < 0)
954         return ret;
955
956     frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
957
958
959     if (frames_ctx->initial_pool_size) {
960         // We guarantee 4 base work surfaces. The function above guarantees 1
961         // (the absolute minimum), so add the missing count.
962         frames_ctx->initial_pool_size += 3;
963     }
964
965     ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
966     if (ret < 0) {
967         av_buffer_unref(&avctx->hw_frames_ctx);
968         return ret;
969     }
970
971     return 0;
972 }
973
974 int avcodec_get_hw_frames_parameters(AVCodecContext *avctx,
975                                      AVBufferRef *device_ref,
976                                      enum AVPixelFormat hw_pix_fmt,
977                                      AVBufferRef **out_frames_ref)
978 {
979     AVBufferRef *frames_ref = NULL;
980     const AVCodecHWConfigInternal *hw_config;
981     const AVHWAccel *hwa;
982     int i, ret;
983
984     for (i = 0;; i++) {
985         hw_config = avctx->codec->hw_configs[i];
986         if (!hw_config)
987             return AVERROR(ENOENT);
988         if (hw_config->public.pix_fmt == hw_pix_fmt)
989             break;
990     }
991
992     hwa = hw_config->hwaccel;
993     if (!hwa || !hwa->frame_params)
994         return AVERROR(ENOENT);
995
996     frames_ref = av_hwframe_ctx_alloc(device_ref);
997     if (!frames_ref)
998         return AVERROR(ENOMEM);
999
1000     ret = hwa->frame_params(avctx, frames_ref);
1001     if (ret >= 0) {
1002         AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frames_ref->data;
1003
1004         if (frames_ctx->initial_pool_size) {
1005             // If the user has requested that extra output surfaces be
1006             // available then add them here.
1007             if (avctx->extra_hw_frames > 0)
1008                 frames_ctx->initial_pool_size += avctx->extra_hw_frames;
1009
1010             // If frame threading is enabled then an extra surface per thread
1011             // is also required.
1012             if (avctx->active_thread_type & FF_THREAD_FRAME)
1013                 frames_ctx->initial_pool_size += avctx->thread_count;
1014         }
1015
1016         *out_frames_ref = frames_ref;
1017     } else {
1018         av_buffer_unref(&frames_ref);
1019     }
1020     return ret;
1021 }
1022
1023 static int hwaccel_init(AVCodecContext *avctx,
1024                         const AVCodecHWConfigInternal *hw_config)
1025 {
1026     const AVHWAccel *hwaccel;
1027     int err;
1028
1029     hwaccel = hw_config->hwaccel;
1030     if (hwaccel->capabilities & AV_HWACCEL_CODEC_CAP_EXPERIMENTAL &&
1031         avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1032         av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
1033                hwaccel->name);
1034         return AVERROR_PATCHWELCOME;
1035     }
1036
1037     if (hwaccel->priv_data_size) {
1038         avctx->internal->hwaccel_priv_data =
1039             av_mallocz(hwaccel->priv_data_size);
1040         if (!avctx->internal->hwaccel_priv_data)
1041             return AVERROR(ENOMEM);
1042     }
1043
1044     avctx->hwaccel = hwaccel;
1045     if (hwaccel->init) {
1046         err = hwaccel->init(avctx);
1047         if (err < 0) {
1048             av_log(avctx, AV_LOG_ERROR, "Failed setup for format %s: "
1049                    "hwaccel initialisation returned error.\n",
1050                    av_get_pix_fmt_name(hw_config->public.pix_fmt));
1051             av_freep(&avctx->internal->hwaccel_priv_data);
1052             avctx->hwaccel = NULL;
1053             return err;
1054         }
1055     }
1056
1057     return 0;
1058 }
1059
1060 static void hwaccel_uninit(AVCodecContext *avctx)
1061 {
1062     if (avctx->hwaccel && avctx->hwaccel->uninit)
1063         avctx->hwaccel->uninit(avctx);
1064
1065     av_freep(&avctx->internal->hwaccel_priv_data);
1066
1067     avctx->hwaccel = NULL;
1068
1069     av_buffer_unref(&avctx->hw_frames_ctx);
1070 }
1071
1072 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1073 {
1074     const AVPixFmtDescriptor *desc;
1075     enum AVPixelFormat *choices;
1076     enum AVPixelFormat ret, user_choice;
1077     const AVCodecHWConfigInternal *hw_config;
1078     const AVCodecHWConfig *config;
1079     int i, n, err;
1080
1081     // Find end of list.
1082     for (n = 0; fmt[n] != AV_PIX_FMT_NONE; n++);
1083     // Must contain at least one entry.
1084     av_assert0(n >= 1);
1085     // If a software format is available, it must be the last entry.
1086     desc = av_pix_fmt_desc_get(fmt[n - 1]);
1087     if (desc->flags & AV_PIX_FMT_FLAG_HWACCEL) {
1088         // No software format is available.
1089     } else {
1090         avctx->sw_pix_fmt = fmt[n - 1];
1091     }
1092
1093     choices = av_malloc_array(n + 1, sizeof(*choices));
1094     if (!choices)
1095         return AV_PIX_FMT_NONE;
1096
1097     memcpy(choices, fmt, (n + 1) * sizeof(*choices));
1098
1099     for (;;) {
1100         // Remove the previous hwaccel, if there was one.
1101         hwaccel_uninit(avctx);
1102
1103         user_choice = avctx->get_format(avctx, choices);
1104         if (user_choice == AV_PIX_FMT_NONE) {
1105             // Explicitly chose nothing, give up.
1106             ret = AV_PIX_FMT_NONE;
1107             break;
1108         }
1109
1110         desc = av_pix_fmt_desc_get(user_choice);
1111         if (!desc) {
1112             av_log(avctx, AV_LOG_ERROR, "Invalid format returned by "
1113                    "get_format() callback.\n");
1114             ret = AV_PIX_FMT_NONE;
1115             break;
1116         }
1117         av_log(avctx, AV_LOG_DEBUG, "Format %s chosen by get_format().\n",
1118                desc->name);
1119
1120         for (i = 0; i < n; i++) {
1121             if (choices[i] == user_choice)
1122                 break;
1123         }
1124         if (i == n) {
1125             av_log(avctx, AV_LOG_ERROR, "Invalid return from get_format(): "
1126                    "%s not in possible list.\n", desc->name);
1127             ret = AV_PIX_FMT_NONE;
1128             break;
1129         }
1130
1131         if (avctx->codec->hw_configs) {
1132             for (i = 0;; i++) {
1133                 hw_config = avctx->codec->hw_configs[i];
1134                 if (!hw_config)
1135                     break;
1136                 if (hw_config->public.pix_fmt == user_choice)
1137                     break;
1138             }
1139         } else {
1140             hw_config = NULL;
1141         }
1142
1143         if (!hw_config) {
1144             // No config available, so no extra setup required.
1145             ret = user_choice;
1146             break;
1147         }
1148         config = &hw_config->public;
1149
1150         if (config->methods &
1151             AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX &&
1152             avctx->hw_frames_ctx) {
1153             const AVHWFramesContext *frames_ctx =
1154                 (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1155             if (frames_ctx->format != user_choice) {
1156                 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1157                        "does not match the format of the provided frames "
1158                        "context.\n", desc->name);
1159                 goto try_again;
1160             }
1161         } else if (config->methods &
1162                    AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX &&
1163                    avctx->hw_device_ctx) {
1164             const AVHWDeviceContext *device_ctx =
1165                 (AVHWDeviceContext*)avctx->hw_device_ctx->data;
1166             if (device_ctx->type != config->device_type) {
1167                 av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1168                        "does not match the type of the provided device "
1169                        "context.\n", desc->name);
1170                 goto try_again;
1171             }
1172         } else if (config->methods &
1173                    AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
1174             // Internal-only setup, no additional configuration.
1175         } else if (config->methods &
1176                    AV_CODEC_HW_CONFIG_METHOD_AD_HOC) {
1177             // Some ad-hoc configuration we can't see and can't check.
1178         } else {
1179             av_log(avctx, AV_LOG_ERROR, "Invalid setup for format %s: "
1180                    "missing configuration.\n", desc->name);
1181             goto try_again;
1182         }
1183         if (hw_config->hwaccel) {
1184             av_log(avctx, AV_LOG_DEBUG, "Format %s requires hwaccel "
1185                    "initialisation.\n", desc->name);
1186             err = hwaccel_init(avctx, hw_config);
1187             if (err < 0)
1188                 goto try_again;
1189         }
1190         ret = user_choice;
1191         break;
1192
1193     try_again:
1194         av_log(avctx, AV_LOG_DEBUG, "Format %s not usable, retrying "
1195                "get_format() without it.\n", desc->name);
1196         for (i = 0; i < n; i++) {
1197             if (choices[i] == user_choice)
1198                 break;
1199         }
1200         for (; i + 1 < n; i++)
1201             choices[i] = choices[i + 1];
1202         --n;
1203     }
1204
1205     av_freep(&choices);
1206     return ret;
1207 }
1208
1209 static void frame_pool_free(void *opaque, uint8_t *data)
1210 {
1211     FramePool *pool = (FramePool*)data;
1212     int i;
1213
1214     for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
1215         av_buffer_pool_uninit(&pool->pools[i]);
1216
1217     av_freep(&data);
1218 }
1219
1220 static AVBufferRef *frame_pool_alloc(void)
1221 {
1222     FramePool *pool = av_mallocz(sizeof(*pool));
1223     AVBufferRef *buf;
1224
1225     if (!pool)
1226         return NULL;
1227
1228     buf = av_buffer_create((uint8_t*)pool, sizeof(*pool),
1229                            frame_pool_free, NULL, 0);
1230     if (!buf) {
1231         av_freep(&pool);
1232         return NULL;
1233     }
1234
1235     return buf;
1236 }
1237
1238 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
1239 {
1240     FramePool *pool = avctx->internal->pool ?
1241                       (FramePool*)avctx->internal->pool->data : NULL;
1242     AVBufferRef *pool_buf;
1243     int i, ret, ch, planes;
1244
1245     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
1246         int planar = av_sample_fmt_is_planar(frame->format);
1247         ch     = frame->channels;
1248         planes = planar ? ch : 1;
1249     }
1250
1251     if (pool && pool->format == frame->format) {
1252         if (avctx->codec_type == AVMEDIA_TYPE_VIDEO &&
1253             pool->width == frame->width && pool->height == frame->height)
1254             return 0;
1255         if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && pool->planes == planes &&
1256             pool->channels == ch && frame->nb_samples == pool->samples)
1257             return 0;
1258     }
1259
1260     pool_buf = frame_pool_alloc();
1261     if (!pool_buf)
1262         return AVERROR(ENOMEM);
1263     pool = (FramePool*)pool_buf->data;
1264
1265     switch (avctx->codec_type) {
1266     case AVMEDIA_TYPE_VIDEO: {
1267         int linesize[4];
1268         int w = frame->width;
1269         int h = frame->height;
1270         int unaligned;
1271         ptrdiff_t linesize1[4];
1272         size_t size[4];
1273
1274         avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
1275
1276         do {
1277             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
1278             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
1279             ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
1280             if (ret < 0)
1281                 goto fail;
1282             // increase alignment of w for next try (rhs gives the lowest bit set in w)
1283             w += w & ~(w - 1);
1284
1285             unaligned = 0;
1286             for (i = 0; i < 4; i++)
1287                 unaligned |= linesize[i] % pool->stride_align[i];
1288         } while (unaligned);
1289
1290         for (i = 0; i < 4; i++)
1291             linesize1[i] = linesize[i];
1292         ret = av_image_fill_plane_sizes(size, avctx->pix_fmt, h, linesize1);
1293         if (ret < 0)
1294             goto fail;
1295
1296         for (i = 0; i < 4; i++) {
1297             pool->linesize[i] = linesize[i];
1298             if (size[i]) {
1299                 if (size[i] > INT_MAX - (16 + STRIDE_ALIGN - 1)) {
1300                     ret = AVERROR(EINVAL);
1301                     goto fail;
1302                 }
1303                 pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
1304                                                      CONFIG_MEMORY_POISONING ?
1305                                                         NULL :
1306                                                         av_buffer_allocz);
1307                 if (!pool->pools[i]) {
1308                     ret = AVERROR(ENOMEM);
1309                     goto fail;
1310                 }
1311             }
1312         }
1313         pool->format = frame->format;
1314         pool->width  = frame->width;
1315         pool->height = frame->height;
1316
1317         break;
1318         }
1319     case AVMEDIA_TYPE_AUDIO: {
1320         ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
1321                                          frame->nb_samples, frame->format, 0);
1322         if (ret < 0)
1323             goto fail;
1324
1325         pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
1326         if (!pool->pools[0]) {
1327             ret = AVERROR(ENOMEM);
1328             goto fail;
1329         }
1330
1331         pool->format     = frame->format;
1332         pool->planes     = planes;
1333         pool->channels   = ch;
1334         pool->samples = frame->nb_samples;
1335         break;
1336         }
1337     default: av_assert0(0);
1338     }
1339
1340     av_buffer_unref(&avctx->internal->pool);
1341     avctx->internal->pool = pool_buf;
1342
1343     return 0;
1344 fail:
1345     av_buffer_unref(&pool_buf);
1346     return ret;
1347 }
1348
1349 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
1350 {
1351     FramePool *pool = (FramePool*)avctx->internal->pool->data;
1352     int planes = pool->planes;
1353     int i;
1354
1355     frame->linesize[0] = pool->linesize[0];
1356
1357     if (planes > AV_NUM_DATA_POINTERS) {
1358         frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
1359         frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
1360         frame->extended_buf  = av_mallocz_array(frame->nb_extended_buf,
1361                                           sizeof(*frame->extended_buf));
1362         if (!frame->extended_data || !frame->extended_buf) {
1363             av_freep(&frame->extended_data);
1364             av_freep(&frame->extended_buf);
1365             return AVERROR(ENOMEM);
1366         }
1367     } else {
1368         frame->extended_data = frame->data;
1369         av_assert0(frame->nb_extended_buf == 0);
1370     }
1371
1372     for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
1373         frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
1374         if (!frame->buf[i])
1375             goto fail;
1376         frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
1377     }
1378     for (i = 0; i < frame->nb_extended_buf; i++) {
1379         frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
1380         if (!frame->extended_buf[i])
1381             goto fail;
1382         frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
1383     }
1384
1385     if (avctx->debug & FF_DEBUG_BUFFERS)
1386         av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
1387
1388     return 0;
1389 fail:
1390     av_frame_unref(frame);
1391     return AVERROR(ENOMEM);
1392 }
1393
1394 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
1395 {
1396     FramePool *pool = (FramePool*)s->internal->pool->data;
1397     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
1398     int i;
1399
1400     if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
1401         av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
1402         return -1;
1403     }
1404
1405     if (!desc) {
1406         av_log(s, AV_LOG_ERROR,
1407             "Unable to get pixel format descriptor for format %s\n",
1408             av_get_pix_fmt_name(pic->format));
1409         return AVERROR(EINVAL);
1410     }
1411
1412     memset(pic->data, 0, sizeof(pic->data));
1413     pic->extended_data = pic->data;
1414
1415     for (i = 0; i < 4 && pool->pools[i]; i++) {
1416         pic->linesize[i] = pool->linesize[i];
1417
1418         pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
1419         if (!pic->buf[i])
1420             goto fail;
1421
1422         pic->data[i] = pic->buf[i]->data;
1423     }
1424     for (; i < AV_NUM_DATA_POINTERS; i++) {
1425         pic->data[i] = NULL;
1426         pic->linesize[i] = 0;
1427     }
1428     if (desc->flags & AV_PIX_FMT_FLAG_PAL)
1429         avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
1430
1431     if (s->debug & FF_DEBUG_BUFFERS)
1432         av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
1433
1434     return 0;
1435 fail:
1436     av_frame_unref(pic);
1437     return AVERROR(ENOMEM);
1438 }
1439
1440 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
1441 {
1442     int ret;
1443
1444     if (avctx->hw_frames_ctx) {
1445         ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
1446         frame->width  = avctx->coded_width;
1447         frame->height = avctx->coded_height;
1448         return ret;
1449     }
1450
1451     if ((ret = update_frame_pool(avctx, frame)) < 0)
1452         return ret;
1453
1454     switch (avctx->codec_type) {
1455     case AVMEDIA_TYPE_VIDEO:
1456         return video_get_buffer(avctx, frame);
1457     case AVMEDIA_TYPE_AUDIO:
1458         return audio_get_buffer(avctx, frame);
1459     default:
1460         return -1;
1461     }
1462 }
1463
1464 static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
1465 {
1466     size_t size;
1467     const uint8_t *side_metadata;
1468
1469     AVDictionary **frame_md = &frame->metadata;
1470
1471     side_metadata = av_packet_get_side_data(avpkt,
1472                                             AV_PKT_DATA_STRINGS_METADATA, &size);
1473     return av_packet_unpack_dictionary(side_metadata, size, frame_md);
1474 }
1475
1476 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1477 {
1478     AVPacket *pkt = avctx->internal->last_pkt_props;
1479     static const struct {
1480         enum AVPacketSideDataType packet;
1481         enum AVFrameSideDataType frame;
1482     } sd[] = {
1483         { AV_PKT_DATA_REPLAYGAIN ,                AV_FRAME_DATA_REPLAYGAIN },
1484         { AV_PKT_DATA_DISPLAYMATRIX,              AV_FRAME_DATA_DISPLAYMATRIX },
1485         { AV_PKT_DATA_SPHERICAL,                  AV_FRAME_DATA_SPHERICAL },
1486         { AV_PKT_DATA_STEREO3D,                   AV_FRAME_DATA_STEREO3D },
1487         { AV_PKT_DATA_AUDIO_SERVICE_TYPE,         AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
1488         { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
1489         { AV_PKT_DATA_CONTENT_LIGHT_LEVEL,        AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
1490         { AV_PKT_DATA_A53_CC,                     AV_FRAME_DATA_A53_CC },
1491         { AV_PKT_DATA_ICC_PROFILE,                AV_FRAME_DATA_ICC_PROFILE },
1492         { AV_PKT_DATA_S12M_TIMECODE,              AV_FRAME_DATA_S12M_TIMECODE },
1493     };
1494
1495     if (IS_EMPTY(pkt) && av_fifo_size(avctx->internal->pkt_props) >= sizeof(*pkt))
1496         av_fifo_generic_read(avctx->internal->pkt_props,
1497                              pkt, sizeof(*pkt), NULL);
1498
1499     frame->pts = pkt->pts;
1500     frame->pkt_pos      = pkt->pos;
1501     frame->pkt_duration = pkt->duration;
1502     frame->pkt_size     = pkt->size;
1503
1504     for (int i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
1505         size_t size;
1506         uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
1507         if (packet_sd) {
1508             AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
1509                                                                sd[i].frame,
1510                                                                size);
1511             if (!frame_sd)
1512                 return AVERROR(ENOMEM);
1513
1514             memcpy(frame_sd->data, packet_sd, size);
1515         }
1516     }
1517     add_metadata_from_side_data(pkt, frame);
1518
1519     if (pkt->flags & AV_PKT_FLAG_DISCARD) {
1520         frame->flags |= AV_FRAME_FLAG_DISCARD;
1521     } else {
1522         frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
1523     }
1524     frame->reordered_opaque = avctx->reordered_opaque;
1525
1526     if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
1527         frame->color_primaries = avctx->color_primaries;
1528     if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
1529         frame->color_trc = avctx->color_trc;
1530     if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
1531         frame->colorspace = avctx->colorspace;
1532     if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
1533         frame->color_range = avctx->color_range;
1534     if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
1535         frame->chroma_location = avctx->chroma_sample_location;
1536
1537     switch (avctx->codec->type) {
1538     case AVMEDIA_TYPE_VIDEO:
1539         frame->format              = avctx->pix_fmt;
1540         if (!frame->sample_aspect_ratio.num)
1541             frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
1542
1543         if (frame->width && frame->height &&
1544             av_image_check_sar(frame->width, frame->height,
1545                                frame->sample_aspect_ratio) < 0) {
1546             av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1547                    frame->sample_aspect_ratio.num,
1548                    frame->sample_aspect_ratio.den);
1549             frame->sample_aspect_ratio = (AVRational){ 0, 1 };
1550         }
1551
1552         break;
1553     case AVMEDIA_TYPE_AUDIO:
1554         if (!frame->sample_rate)
1555             frame->sample_rate    = avctx->sample_rate;
1556         if (frame->format < 0)
1557             frame->format         = avctx->sample_fmt;
1558         if (!frame->channel_layout) {
1559             if (avctx->channel_layout) {
1560                  if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
1561                      avctx->channels) {
1562                      av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
1563                             "configuration.\n");
1564                      return AVERROR(EINVAL);
1565                  }
1566
1567                 frame->channel_layout = avctx->channel_layout;
1568             } else {
1569                 if (avctx->channels > FF_SANE_NB_CHANNELS) {
1570                     av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
1571                            avctx->channels);
1572                     return AVERROR(ENOSYS);
1573                 }
1574             }
1575         }
1576         frame->channels = avctx->channels;
1577         break;
1578     }
1579     return 0;
1580 }
1581
1582 static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
1583 {
1584     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1585         int i;
1586         int num_planes = av_pix_fmt_count_planes(frame->format);
1587         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
1588         int flags = desc ? desc->flags : 0;
1589         if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
1590             num_planes = 2;
1591         for (i = 0; i < num_planes; i++) {
1592             av_assert0(frame->data[i]);
1593         }
1594         // For formats without data like hwaccel allow unused pointers to be non-NULL.
1595         for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
1596             if (frame->data[i])
1597                 av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
1598             frame->data[i] = NULL;
1599         }
1600     }
1601 }
1602
1603 static void decode_data_free(void *opaque, uint8_t *data)
1604 {
1605     FrameDecodeData *fdd = (FrameDecodeData*)data;
1606
1607     if (fdd->post_process_opaque_free)
1608         fdd->post_process_opaque_free(fdd->post_process_opaque);
1609
1610     if (fdd->hwaccel_priv_free)
1611         fdd->hwaccel_priv_free(fdd->hwaccel_priv);
1612
1613     av_freep(&fdd);
1614 }
1615
1616 int ff_attach_decode_data(AVFrame *frame)
1617 {
1618     AVBufferRef *fdd_buf;
1619     FrameDecodeData *fdd;
1620
1621     av_assert1(!frame->private_ref);
1622     av_buffer_unref(&frame->private_ref);
1623
1624     fdd = av_mallocz(sizeof(*fdd));
1625     if (!fdd)
1626         return AVERROR(ENOMEM);
1627
1628     fdd_buf = av_buffer_create((uint8_t*)fdd, sizeof(*fdd), decode_data_free,
1629                                NULL, AV_BUFFER_FLAG_READONLY);
1630     if (!fdd_buf) {
1631         av_freep(&fdd);
1632         return AVERROR(ENOMEM);
1633     }
1634
1635     frame->private_ref = fdd_buf;
1636
1637     return 0;
1638 }
1639
1640 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1641 {
1642     const AVHWAccel *hwaccel = avctx->hwaccel;
1643     int override_dimensions = 1;
1644     int ret;
1645
1646     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1647         if ((unsigned)avctx->width > INT_MAX - STRIDE_ALIGN ||
1648             (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) {
1649             av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
1650             ret = AVERROR(EINVAL);
1651             goto fail;
1652         }
1653
1654         if (frame->width <= 0 || frame->height <= 0) {
1655             frame->width  = FFMAX(avctx->width,  AV_CEIL_RSHIFT(avctx->coded_width,  avctx->lowres));
1656             frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
1657             override_dimensions = 0;
1658         }
1659
1660         if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
1661             av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
1662             ret = AVERROR(EINVAL);
1663             goto fail;
1664         }
1665     } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
1666         if (frame->nb_samples * (int64_t)avctx->channels > avctx->max_samples) {
1667             av_log(avctx, AV_LOG_ERROR, "samples per frame %d, exceeds max_samples %"PRId64"\n", frame->nb_samples, avctx->max_samples);
1668             ret = AVERROR(EINVAL);
1669             goto fail;
1670         }
1671     }
1672     ret = ff_decode_frame_props(avctx, frame);
1673     if (ret < 0)
1674         goto fail;
1675
1676     if (hwaccel) {
1677         if (hwaccel->alloc_frame) {
1678             ret = hwaccel->alloc_frame(avctx, frame);
1679             goto end;
1680         }
1681     } else
1682         avctx->sw_pix_fmt = avctx->pix_fmt;
1683
1684     ret = avctx->get_buffer2(avctx, frame, flags);
1685     if (ret < 0)
1686         goto fail;
1687
1688     validate_avframe_allocation(avctx, frame);
1689
1690     ret = ff_attach_decode_data(frame);
1691     if (ret < 0)
1692         goto fail;
1693
1694 end:
1695     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
1696         !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
1697         frame->width  = avctx->width;
1698         frame->height = avctx->height;
1699     }
1700
1701 fail:
1702     if (ret < 0) {
1703         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1704         av_frame_unref(frame);
1705     }
1706
1707     return ret;
1708 }
1709
1710 static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
1711 {
1712     AVFrame *tmp;
1713     int ret;
1714
1715     av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1716
1717     if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
1718         av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
1719                frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
1720         av_frame_unref(frame);
1721     }
1722
1723     if (!frame->data[0])
1724         return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1725
1726     if ((flags & FF_REGET_BUFFER_FLAG_READONLY) || av_frame_is_writable(frame))
1727         return ff_decode_frame_props(avctx, frame);
1728
1729     tmp = av_frame_alloc();
1730     if (!tmp)
1731         return AVERROR(ENOMEM);
1732
1733     av_frame_move_ref(tmp, frame);
1734
1735     ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1736     if (ret < 0) {
1737         av_frame_free(&tmp);
1738         return ret;
1739     }
1740
1741     av_frame_copy(frame, tmp);
1742     av_frame_free(&tmp);
1743
1744     return 0;
1745 }
1746
1747 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1748 {
1749     int ret = reget_buffer_internal(avctx, frame, flags);
1750     if (ret < 0)
1751         av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1752     return ret;
1753 }
1754
1755 int ff_decode_preinit(AVCodecContext *avctx)
1756 {
1757     int ret = 0;
1758
1759     /* if the decoder init function was already called previously,
1760      * free the already allocated subtitle_header before overwriting it */
1761     av_freep(&avctx->subtitle_header);
1762
1763 #if FF_API_THREAD_SAFE_CALLBACKS
1764 FF_DISABLE_DEPRECATION_WARNINGS
1765     if ((avctx->thread_type & FF_THREAD_FRAME) &&
1766         avctx->get_buffer2 != avcodec_default_get_buffer2 &&
1767         !avctx->thread_safe_callbacks) {
1768         av_log(avctx, AV_LOG_WARNING, "Requested frame threading with a "
1769                "custom get_buffer2() implementation which is not marked as "
1770                "thread safe. This is not supported anymore, make your "
1771                "callback thread-safe.\n");
1772     }
1773 FF_ENABLE_DEPRECATION_WARNINGS
1774 #endif
1775
1776     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && avctx->channels == 0 &&
1777         !(avctx->codec->capabilities & AV_CODEC_CAP_CHANNEL_CONF)) {
1778         av_log(avctx, AV_LOG_ERROR, "Decoder requires channel count but channels not set\n");
1779         return AVERROR(EINVAL);
1780     }
1781     if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {
1782         av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n",
1783                avctx->codec->max_lowres);
1784         avctx->lowres = avctx->codec->max_lowres;
1785     }
1786     if (avctx->sub_charenc) {
1787         if (avctx->codec_type != AVMEDIA_TYPE_SUBTITLE) {
1788             av_log(avctx, AV_LOG_ERROR, "Character encoding is only "
1789                    "supported with subtitles codecs\n");
1790             return AVERROR(EINVAL);
1791         } else if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) {
1792             av_log(avctx, AV_LOG_WARNING, "Codec '%s' is bitmap-based, "
1793                    "subtitles character encoding will be ignored\n",
1794                    avctx->codec_descriptor->name);
1795             avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_DO_NOTHING;
1796         } else {
1797             /* input character encoding is set for a text based subtitle
1798              * codec at this point */
1799             if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_AUTOMATIC)
1800                 avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_PRE_DECODER;
1801
1802             if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_PRE_DECODER) {
1803 #if CONFIG_ICONV
1804                 iconv_t cd = iconv_open("UTF-8", avctx->sub_charenc);
1805                 if (cd == (iconv_t)-1) {
1806                     ret = AVERROR(errno);
1807                     av_log(avctx, AV_LOG_ERROR, "Unable to open iconv context "
1808                            "with input character encoding \"%s\"\n", avctx->sub_charenc);
1809                     return ret;
1810                 }
1811                 iconv_close(cd);
1812 #else
1813                 av_log(avctx, AV_LOG_ERROR, "Character encoding subtitles "
1814                        "conversion needs a libavcodec built with iconv support "
1815                        "for this codec\n");
1816                 return AVERROR(ENOSYS);
1817 #endif
1818             }
1819         }
1820     }
1821
1822     avctx->pts_correction_num_faulty_pts =
1823     avctx->pts_correction_num_faulty_dts = 0;
1824     avctx->pts_correction_last_pts =
1825     avctx->pts_correction_last_dts = INT64_MIN;
1826
1827     if (   !CONFIG_GRAY && avctx->flags & AV_CODEC_FLAG_GRAY
1828         && avctx->codec_descriptor->type == AVMEDIA_TYPE_VIDEO)
1829         av_log(avctx, AV_LOG_WARNING,
1830                "gray decoding requested but not enabled at configuration time\n");
1831     if (avctx->flags2 & AV_CODEC_FLAG2_EXPORT_MVS) {
1832         avctx->export_side_data |= AV_CODEC_EXPORT_DATA_MVS;
1833     }
1834
1835     ret = decode_bsfs_init(avctx);
1836     if (ret < 0)
1837         return ret;
1838
1839     return 0;
1840 }
1841
1842 int ff_copy_palette(void *dst, const AVPacket *src, void *logctx)
1843 {
1844     size_t size;
1845     const void *pal = av_packet_get_side_data(src, AV_PKT_DATA_PALETTE, &size);
1846
1847     if (pal && size == AVPALETTE_SIZE) {
1848         memcpy(dst, pal, AVPALETTE_SIZE);
1849         return 1;
1850     } else if (pal) {
1851         av_log(logctx, AV_LOG_ERROR,
1852                "Palette size %"SIZE_SPECIFIER" is wrong\n", size);
1853     }
1854     return 0;
1855 }