OSDN Git Service

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