]> git.sesse.net Git - ffmpeg/blob - libavcodec/decode.c
7f08f0ec1838eae5bebea2908a09668632579af7
[ffmpeg] / libavcodec / decode.c
1 /*
2  * generic decoding-related code
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include <stdint.h>
22 #include <string.h>
23
24 #include "config.h"
25
26 #if CONFIG_ICONV
27 # include <iconv.h>
28 #endif
29
30 #include "libavutil/avassert.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/bprint.h"
33 #include "libavutil/common.h"
34 #include "libavutil/frame.h"
35 #include "libavutil/hwcontext.h"
36 #include "libavutil/imgutils.h"
37 #include "libavutil/internal.h"
38 #include "libavutil/intmath.h"
39
40 #include "avcodec.h"
41 #include "bytestream.h"
42 #include "decode.h"
43 #include "internal.h"
44 #include "thread.h"
45
46 static int apply_param_change(AVCodecContext *avctx, const AVPacket *avpkt)
47 {
48     int size = 0, ret;
49     const uint8_t *data;
50     uint32_t flags;
51     int64_t val;
52
53     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
54     if (!data)
55         return 0;
56
57     if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
58         av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
59                "changes, but PARAM_CHANGE side data was sent to it.\n");
60         ret = AVERROR(EINVAL);
61         goto fail2;
62     }
63
64     if (size < 4)
65         goto fail;
66
67     flags = bytestream_get_le32(&data);
68     size -= 4;
69
70     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
71         if (size < 4)
72             goto fail;
73         val = bytestream_get_le32(&data);
74         if (val <= 0 || val > INT_MAX) {
75             av_log(avctx, AV_LOG_ERROR, "Invalid channel count");
76             ret = AVERROR_INVALIDDATA;
77             goto fail2;
78         }
79         avctx->channels = val;
80         size -= 4;
81     }
82     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
83         if (size < 8)
84             goto fail;
85         avctx->channel_layout = bytestream_get_le64(&data);
86         size -= 8;
87     }
88     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
89         if (size < 4)
90             goto fail;
91         val = bytestream_get_le32(&data);
92         if (val <= 0 || val > INT_MAX) {
93             av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
94             ret = AVERROR_INVALIDDATA;
95             goto fail2;
96         }
97         avctx->sample_rate = val;
98         size -= 4;
99     }
100     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
101         if (size < 8)
102             goto fail;
103         avctx->width  = bytestream_get_le32(&data);
104         avctx->height = bytestream_get_le32(&data);
105         size -= 8;
106         ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
107         if (ret < 0)
108             goto fail2;
109     }
110
111     return 0;
112 fail:
113     av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
114     ret = AVERROR_INVALIDDATA;
115 fail2:
116     if (ret < 0) {
117         av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
118         if (avctx->err_recognition & AV_EF_EXPLODE)
119             return ret;
120     }
121     return 0;
122 }
123
124 static int extract_packet_props(AVCodecInternal *avci, const AVPacket *pkt)
125 {
126     int ret = 0;
127
128     av_packet_unref(avci->last_pkt_props);
129     if (pkt) {
130         ret = av_packet_copy_props(avci->last_pkt_props, pkt);
131         if (!ret)
132             avci->last_pkt_props->size = pkt->size; // HACK: Needed for ff_init_buffer_info().
133     }
134     return ret;
135 }
136
137 static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
138 {
139     int ret;
140
141     /* move the original frame to our backup */
142     av_frame_unref(avci->to_free);
143     av_frame_move_ref(avci->to_free, frame);
144
145     /* now copy everything except the AVBufferRefs back
146      * note that we make a COPY of the side data, so calling av_frame_free() on
147      * the caller's frame will work properly */
148     ret = av_frame_copy_props(frame, avci->to_free);
149     if (ret < 0)
150         return ret;
151
152     memcpy(frame->data,     avci->to_free->data,     sizeof(frame->data));
153     memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
154     if (avci->to_free->extended_data != avci->to_free->data) {
155         int planes = avci->to_free->channels;
156         int size   = planes * sizeof(*frame->extended_data);
157
158         if (!size) {
159             av_frame_unref(frame);
160             return AVERROR_BUG;
161         }
162
163         frame->extended_data = av_malloc(size);
164         if (!frame->extended_data) {
165             av_frame_unref(frame);
166             return AVERROR(ENOMEM);
167         }
168         memcpy(frame->extended_data, avci->to_free->extended_data,
169                size);
170     } else
171         frame->extended_data = frame->data;
172
173     frame->format         = avci->to_free->format;
174     frame->width          = avci->to_free->width;
175     frame->height         = avci->to_free->height;
176     frame->channel_layout = avci->to_free->channel_layout;
177     frame->nb_samples     = avci->to_free->nb_samples;
178     frame->channels       = avci->to_free->channels;
179
180     return 0;
181 }
182
183 static int bsfs_init(AVCodecContext *avctx)
184 {
185     AVCodecInternal *avci = avctx->internal;
186     DecodeFilterContext *s = &avci->filter;
187     const char *bsfs_str;
188     int ret;
189
190     if (s->nb_bsfs)
191         return 0;
192
193     bsfs_str = avctx->codec->bsfs ? avctx->codec->bsfs : "null";
194     while (bsfs_str && *bsfs_str) {
195         AVBSFContext **tmp;
196         const AVBitStreamFilter *filter;
197         char *bsf;
198
199         bsf = av_get_token(&bsfs_str, ",");
200         if (!bsf) {
201             ret = AVERROR(ENOMEM);
202             goto fail;
203         }
204
205         filter = av_bsf_get_by_name(bsf);
206         if (!filter) {
207             av_log(avctx, AV_LOG_ERROR, "A non-existing bitstream filter %s "
208                    "requested by a decoder. This is a bug, please report it.\n",
209                    bsf);
210             ret = AVERROR_BUG;
211             av_freep(&bsf);
212             goto fail;
213         }
214         av_freep(&bsf);
215
216         tmp = av_realloc_array(s->bsfs, s->nb_bsfs + 1, sizeof(*s->bsfs));
217         if (!tmp) {
218             ret = AVERROR(ENOMEM);
219             goto fail;
220         }
221         s->bsfs = tmp;
222         s->nb_bsfs++;
223
224         ret = av_bsf_alloc(filter, &s->bsfs[s->nb_bsfs - 1]);
225         if (ret < 0)
226             goto fail;
227
228         if (s->nb_bsfs == 1) {
229             /* We do not currently have an API for passing the input timebase into decoders,
230              * but no filters used here should actually need it.
231              * So we make up some plausible-looking number (the MPEG 90kHz timebase) */
232             s->bsfs[s->nb_bsfs - 1]->time_base_in = (AVRational){ 1, 90000 };
233             ret = avcodec_parameters_from_context(s->bsfs[s->nb_bsfs - 1]->par_in,
234                                                   avctx);
235         } else {
236             s->bsfs[s->nb_bsfs - 1]->time_base_in = s->bsfs[s->nb_bsfs - 2]->time_base_out;
237             ret = avcodec_parameters_copy(s->bsfs[s->nb_bsfs - 1]->par_in,
238                                           s->bsfs[s->nb_bsfs - 2]->par_out);
239         }
240         if (ret < 0)
241             goto fail;
242
243         ret = av_bsf_init(s->bsfs[s->nb_bsfs - 1]);
244         if (ret < 0)
245             goto fail;
246     }
247
248     return 0;
249 fail:
250     ff_decode_bsfs_uninit(avctx);
251     return ret;
252 }
253
254 /* try to get one output packet from the filter chain */
255 static int bsfs_poll(AVCodecContext *avctx, AVPacket *pkt)
256 {
257     DecodeFilterContext *s = &avctx->internal->filter;
258     int idx, ret;
259
260     /* start with the last filter in the chain */
261     idx = s->nb_bsfs - 1;
262     while (idx >= 0) {
263         /* request a packet from the currently selected filter */
264         ret = av_bsf_receive_packet(s->bsfs[idx], pkt);
265         if (ret == AVERROR(EAGAIN)) {
266             /* no packets available, try the next filter up the chain */
267             ret = 0;
268             idx--;
269             continue;
270         } else if (ret < 0 && ret != AVERROR_EOF) {
271             return ret;
272         }
273
274         /* got a packet or EOF -- pass it to the caller or to the next filter
275          * down the chain */
276         if (idx == s->nb_bsfs - 1) {
277             return ret;
278         } else {
279             idx++;
280             ret = av_bsf_send_packet(s->bsfs[idx], ret < 0 ? NULL : pkt);
281             if (ret < 0) {
282                 av_log(avctx, AV_LOG_ERROR,
283                        "Error pre-processing a packet before decoding\n");
284                 av_packet_unref(pkt);
285                 return ret;
286             }
287         }
288     }
289
290     return AVERROR(EAGAIN);
291 }
292
293 int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
294 {
295     AVCodecInternal *avci = avctx->internal;
296     int ret;
297
298     if (avci->draining)
299         return AVERROR_EOF;
300
301     ret = bsfs_poll(avctx, pkt);
302     if (ret == AVERROR_EOF)
303         avci->draining = 1;
304     if (ret < 0)
305         return ret;
306
307     ret = extract_packet_props(avctx->internal, pkt);
308     if (ret < 0)
309         goto finish;
310
311     ret = apply_param_change(avctx, pkt);
312     if (ret < 0)
313         goto finish;
314
315     if (avctx->codec->receive_frame)
316         avci->compat_decode_consumed += pkt->size;
317
318     return 0;
319 finish:
320     av_packet_unref(pkt);
321     return ret;
322 }
323
324 /**
325  * Attempt to guess proper monotonic timestamps for decoded video frames
326  * which might have incorrect times. Input timestamps may wrap around, in
327  * which case the output will as well.
328  *
329  * @param pts the pts field of the decoded AVPacket, as passed through
330  * AVFrame.pts
331  * @param dts the dts field of the decoded AVPacket
332  * @return one of the input values, may be AV_NOPTS_VALUE
333  */
334 static int64_t guess_correct_pts(AVCodecContext *ctx,
335                                  int64_t reordered_pts, int64_t dts)
336 {
337     int64_t pts = AV_NOPTS_VALUE;
338
339     if (dts != AV_NOPTS_VALUE) {
340         ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
341         ctx->pts_correction_last_dts = dts;
342     } else if (reordered_pts != AV_NOPTS_VALUE)
343         ctx->pts_correction_last_dts = reordered_pts;
344
345     if (reordered_pts != AV_NOPTS_VALUE) {
346         ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
347         ctx->pts_correction_last_pts = reordered_pts;
348     } else if(dts != AV_NOPTS_VALUE)
349         ctx->pts_correction_last_pts = dts;
350
351     if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
352        && reordered_pts != AV_NOPTS_VALUE)
353         pts = reordered_pts;
354     else
355         pts = dts;
356
357     return pts;
358 }
359
360 /*
361  * The core of the receive_frame_wrapper for the decoders implementing
362  * the simple API. Certain decoders might consume partial packets without
363  * returning any output, so this function needs to be called in a loop until it
364  * returns EAGAIN.
365  **/
366 static int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame)
367 {
368     AVCodecInternal   *avci = avctx->internal;
369     DecodeSimpleContext *ds = &avci->ds;
370     AVPacket           *pkt = ds->in_pkt;
371     // copy to ensure we do not change pkt
372     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(avci->last_pkt_props, 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 apply_cropping(AVCodecContext *avctx, AVFrame *frame)
687 {
688     /* make sure we are noisy about decoders returning invalid cropping data */
689     if (frame->crop_left >= INT_MAX - frame->crop_right        ||
690         frame->crop_top  >= INT_MAX - frame->crop_bottom       ||
691         (frame->crop_left + frame->crop_right) >= frame->width ||
692         (frame->crop_top + frame->crop_bottom) >= frame->height) {
693         av_log(avctx, AV_LOG_WARNING,
694                "Invalid cropping information set by a decoder: "
695                "%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER" "
696                "(frame size %dx%d). This is a bug, please report it\n",
697                frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
698                frame->width, frame->height);
699         frame->crop_left   = 0;
700         frame->crop_right  = 0;
701         frame->crop_top    = 0;
702         frame->crop_bottom = 0;
703         return 0;
704     }
705
706     if (!avctx->apply_cropping)
707         return 0;
708
709     return av_frame_apply_cropping(frame, avctx->flags & AV_CODEC_FLAG_UNALIGNED ?
710                                           AV_FRAME_CROP_UNALIGNED : 0);
711 }
712
713 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
714 {
715     AVCodecInternal *avci = avctx->internal;
716     int ret;
717
718     av_frame_unref(frame);
719
720     if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
721         return AVERROR(EINVAL);
722
723     ret = bsfs_init(avctx);
724     if (ret < 0)
725         return ret;
726
727     if (avci->buffer_frame->buf[0]) {
728         av_frame_move_ref(frame, avci->buffer_frame);
729     } else {
730         ret = decode_receive_frame_internal(avctx, frame);
731         if (ret < 0)
732             return ret;
733     }
734
735     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
736         ret = apply_cropping(avctx, frame);
737         if (ret < 0) {
738             av_frame_unref(frame);
739             return ret;
740         }
741     }
742
743     avctx->frame_number++;
744
745     return 0;
746 }
747
748 static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
749                          int *got_frame, const AVPacket *pkt)
750 {
751     AVCodecInternal *avci = avctx->internal;
752     int ret = 0;
753
754     av_assert0(avci->compat_decode_consumed == 0);
755
756     *got_frame = 0;
757     avci->compat_decode = 1;
758
759     if (avci->compat_decode_partial_size > 0 &&
760         avci->compat_decode_partial_size != pkt->size) {
761         av_log(avctx, AV_LOG_ERROR,
762                "Got unexpected packet size after a partial decode\n");
763         ret = AVERROR(EINVAL);
764         goto finish;
765     }
766
767     if (!avci->compat_decode_partial_size) {
768         ret = avcodec_send_packet(avctx, pkt);
769         if (ret == AVERROR_EOF)
770             ret = 0;
771         else if (ret == AVERROR(EAGAIN)) {
772             /* we fully drain all the output in each decode call, so this should not
773              * ever happen */
774             ret = AVERROR_BUG;
775             goto finish;
776         } else if (ret < 0)
777             goto finish;
778     }
779
780     while (ret >= 0) {
781         ret = avcodec_receive_frame(avctx, frame);
782         if (ret < 0) {
783             if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
784                 ret = 0;
785             goto finish;
786         }
787
788         if (frame != avci->compat_decode_frame) {
789             if (!avctx->refcounted_frames) {
790                 ret = unrefcount_frame(avci, frame);
791                 if (ret < 0)
792                     goto finish;
793             }
794
795             *got_frame = 1;
796             frame = avci->compat_decode_frame;
797         } else {
798             if (!avci->compat_decode_warned) {
799                 av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
800                        "API cannot return all the frames for this decoder. "
801                        "Some frames will be dropped. Update your code to the "
802                        "new decoding API to fix this.\n");
803                 avci->compat_decode_warned = 1;
804             }
805         }
806
807         if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
808             break;
809     }
810
811 finish:
812     if (ret == 0) {
813         /* if there are any bsfs then assume full packet is always consumed */
814         if (avctx->codec->bsfs)
815             ret = pkt->size;
816         else
817             ret = FFMIN(avci->compat_decode_consumed, pkt->size);
818     }
819     avci->compat_decode_consumed = 0;
820     avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
821
822     return ret;
823 }
824
825 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
826                                               int *got_picture_ptr,
827                                               const AVPacket *avpkt)
828 {
829     return compat_decode(avctx, picture, got_picture_ptr, avpkt);
830 }
831
832 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
833                                               AVFrame *frame,
834                                               int *got_frame_ptr,
835                                               const AVPacket *avpkt)
836 {
837     return compat_decode(avctx, frame, got_frame_ptr, avpkt);
838 }
839
840 static void get_subtitle_defaults(AVSubtitle *sub)
841 {
842     memset(sub, 0, sizeof(*sub));
843     sub->pts = AV_NOPTS_VALUE;
844 }
845
846 #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
847 static int recode_subtitle(AVCodecContext *avctx,
848                            AVPacket *outpkt, const AVPacket *inpkt)
849 {
850 #if CONFIG_ICONV
851     iconv_t cd = (iconv_t)-1;
852     int ret = 0;
853     char *inb, *outb;
854     size_t inl, outl;
855     AVPacket tmp;
856 #endif
857
858     if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
859         return 0;
860
861 #if CONFIG_ICONV
862     cd = iconv_open("UTF-8", avctx->sub_charenc);
863     av_assert0(cd != (iconv_t)-1);
864
865     inb = inpkt->data;
866     inl = inpkt->size;
867
868     if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
869         av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
870         ret = AVERROR(ENOMEM);
871         goto end;
872     }
873
874     ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
875     if (ret < 0)
876         goto end;
877     outpkt->buf  = tmp.buf;
878     outpkt->data = tmp.data;
879     outpkt->size = tmp.size;
880     outb = outpkt->data;
881     outl = outpkt->size;
882
883     if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
884         iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
885         outl >= outpkt->size || inl != 0) {
886         ret = FFMIN(AVERROR(errno), -1);
887         av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
888                "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
889         av_packet_unref(&tmp);
890         goto end;
891     }
892     outpkt->size -= outl;
893     memset(outpkt->data + outpkt->size, 0, outl);
894
895 end:
896     if (cd != (iconv_t)-1)
897         iconv_close(cd);
898     return ret;
899 #else
900     av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
901     return AVERROR(EINVAL);
902 #endif
903 }
904
905 static int utf8_check(const uint8_t *str)
906 {
907     const uint8_t *byte;
908     uint32_t codepoint, min;
909
910     while (*str) {
911         byte = str;
912         GET_UTF8(codepoint, *(byte++), return 0;);
913         min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
914               1 << (5 * (byte - str) - 4);
915         if (codepoint < min || codepoint >= 0x110000 ||
916             codepoint == 0xFFFE /* BOM */ ||
917             codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
918             return 0;
919         str = byte;
920     }
921     return 1;
922 }
923
924 #if FF_API_ASS_TIMING
925 static void insert_ts(AVBPrint *buf, int ts)
926 {
927     if (ts == -1) {
928         av_bprintf(buf, "9:59:59.99,");
929     } else {
930         int h, m, s;
931
932         h = ts/360000;  ts -= 360000*h;
933         m = ts/  6000;  ts -=   6000*m;
934         s = ts/   100;  ts -=    100*s;
935         av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
936     }
937 }
938
939 static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
940 {
941     int i;
942     AVBPrint buf;
943
944     av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
945
946     for (i = 0; i < sub->num_rects; i++) {
947         char *final_dialog;
948         const char *dialog;
949         AVSubtitleRect *rect = sub->rects[i];
950         int ts_start, ts_duration = -1;
951         long int layer;
952
953         if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
954             continue;
955
956         av_bprint_clear(&buf);
957
958         /* skip ReadOrder */
959         dialog = strchr(rect->ass, ',');
960         if (!dialog)
961             continue;
962         dialog++;
963
964         /* extract Layer or Marked */
965         layer = strtol(dialog, (char**)&dialog, 10);
966         if (*dialog != ',')
967             continue;
968         dialog++;
969
970         /* rescale timing to ASS time base (ms) */
971         ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
972         if (pkt->duration != -1)
973             ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
974         sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
975
976         /* construct ASS (standalone file form with timestamps) string */
977         av_bprintf(&buf, "Dialogue: %ld,", layer);
978         insert_ts(&buf, ts_start);
979         insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
980         av_bprintf(&buf, "%s\r\n", dialog);
981
982         final_dialog = av_strdup(buf.str);
983         if (!av_bprint_is_complete(&buf) || !final_dialog) {
984             av_freep(&final_dialog);
985             av_bprint_finalize(&buf, NULL);
986             return AVERROR(ENOMEM);
987         }
988         av_freep(&rect->ass);
989         rect->ass = final_dialog;
990     }
991
992     av_bprint_finalize(&buf, NULL);
993     return 0;
994 }
995 #endif
996
997 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
998                              int *got_sub_ptr,
999                              AVPacket *avpkt)
1000 {
1001     int i, ret = 0;
1002     AVCodecInternal *avci = avctx->internal;
1003
1004     if (!avpkt->data && avpkt->size) {
1005         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1006         return AVERROR(EINVAL);
1007     }
1008     if (!avctx->codec)
1009         return AVERROR(EINVAL);
1010     if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
1011         av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
1012         return AVERROR(EINVAL);
1013     }
1014
1015     *got_sub_ptr = 0;
1016     get_subtitle_defaults(sub);
1017
1018     if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
1019         AVPacket pkt_recoded;
1020         AVPacket tmp = *avpkt;
1021 #if FF_API_MERGE_SD
1022 FF_DISABLE_DEPRECATION_WARNINGS
1023         int did_split = avci->compat_decode_partial_size ?
1024                         ff_packet_split_and_drop_side_data(&tmp) :
1025                         av_packet_split_side_data(&tmp);
1026         //apply_param_change(avctx, &tmp);
1027
1028         if (did_split) {
1029             /* FFMIN() prevents overflow in case the packet wasn't allocated with
1030              * proper padding.
1031              * If the side data is smaller than the buffer padding size, the
1032              * remaining bytes should have already been filled with zeros by the
1033              * original packet allocation anyway. */
1034             memset(tmp.data + tmp.size, 0,
1035                    FFMIN(avpkt->size - tmp.size, AV_INPUT_BUFFER_PADDING_SIZE));
1036         }
1037 FF_ENABLE_DEPRECATION_WARNINGS
1038 #endif
1039
1040         pkt_recoded = tmp;
1041         ret = recode_subtitle(avctx, &pkt_recoded, &tmp);
1042         if (ret < 0) {
1043             *got_sub_ptr = 0;
1044         } else {
1045              ret = extract_packet_props(avctx->internal, &pkt_recoded);
1046              if (ret < 0)
1047                 return ret;
1048
1049             if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
1050                 sub->pts = av_rescale_q(avpkt->pts,
1051                                         avctx->pkt_timebase, AV_TIME_BASE_Q);
1052             ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
1053             av_assert1((ret >= 0) >= !!*got_sub_ptr &&
1054                        !!*got_sub_ptr >= !!sub->num_rects);
1055
1056 #if FF_API_ASS_TIMING
1057             if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
1058                 && *got_sub_ptr && sub->num_rects) {
1059                 const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
1060                                                               : avctx->time_base;
1061                 int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
1062                 if (err < 0)
1063                     ret = err;
1064             }
1065 #endif
1066
1067             if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
1068                 avctx->pkt_timebase.num) {
1069                 AVRational ms = { 1, 1000 };
1070                 sub->end_display_time = av_rescale_q(avpkt->duration,
1071                                                      avctx->pkt_timebase, ms);
1072             }
1073
1074             if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
1075                 sub->format = 0;
1076             else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
1077                 sub->format = 1;
1078
1079             for (i = 0; i < sub->num_rects; i++) {
1080                 if (sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
1081                     av_log(avctx, AV_LOG_ERROR,
1082                            "Invalid UTF-8 in decoded subtitles text; "
1083                            "maybe missing -sub_charenc option\n");
1084                     avsubtitle_free(sub);
1085                     ret = AVERROR_INVALIDDATA;
1086                     break;
1087                 }
1088             }
1089
1090             if (tmp.data != pkt_recoded.data) { // did we recode?
1091                 /* prevent from destroying side data from original packet */
1092                 pkt_recoded.side_data = NULL;
1093                 pkt_recoded.side_data_elems = 0;
1094
1095                 av_packet_unref(&pkt_recoded);
1096             }
1097         }
1098
1099 #if FF_API_MERGE_SD
1100         if (did_split) {
1101             av_packet_free_side_data(&tmp);
1102             if(ret == tmp.size)
1103                 ret = avpkt->size;
1104         }
1105 #endif
1106
1107         if (*got_sub_ptr)
1108             avctx->frame_number++;
1109     }
1110
1111     return ret;
1112 }
1113
1114 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
1115 {
1116     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
1117     return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
1118 }
1119
1120 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
1121 {
1122     while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
1123         ++fmt;
1124     return fmt[0];
1125 }
1126
1127 static AVHWAccel *find_hwaccel(enum AVCodecID codec_id,
1128                                enum AVPixelFormat pix_fmt)
1129 {
1130     AVHWAccel *hwaccel = NULL;
1131
1132     while ((hwaccel = av_hwaccel_next(hwaccel)))
1133         if (hwaccel->id == codec_id
1134             && hwaccel->pix_fmt == pix_fmt)
1135             return hwaccel;
1136     return NULL;
1137 }
1138
1139 static int setup_hwaccel(AVCodecContext *avctx,
1140                          const enum AVPixelFormat fmt,
1141                          const char *name)
1142 {
1143     AVHWAccel *hwa = find_hwaccel(avctx->codec_id, fmt);
1144     int ret        = 0;
1145
1146     if (!hwa) {
1147         av_log(avctx, AV_LOG_ERROR,
1148                "Could not find an AVHWAccel for the pixel format: %s",
1149                name);
1150         return AVERROR(ENOENT);
1151     }
1152
1153     if (hwa->capabilities & AV_HWACCEL_CODEC_CAP_EXPERIMENTAL &&
1154         avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1155         av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
1156                hwa->name);
1157         return AVERROR_PATCHWELCOME;
1158     }
1159
1160     if (hwa->priv_data_size) {
1161         avctx->internal->hwaccel_priv_data = av_mallocz(hwa->priv_data_size);
1162         if (!avctx->internal->hwaccel_priv_data)
1163             return AVERROR(ENOMEM);
1164     }
1165
1166     avctx->hwaccel = hwa;
1167     if (hwa->init) {
1168         ret = hwa->init(avctx);
1169         if (ret < 0) {
1170             av_freep(&avctx->internal->hwaccel_priv_data);
1171             avctx->hwaccel = NULL;
1172             return ret;
1173         }
1174     }
1175
1176     return 0;
1177 }
1178
1179 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1180 {
1181     const AVPixFmtDescriptor *desc;
1182     enum AVPixelFormat *choices;
1183     enum AVPixelFormat ret;
1184     unsigned n = 0;
1185
1186     while (fmt[n] != AV_PIX_FMT_NONE)
1187         ++n;
1188
1189     av_assert0(n >= 1);
1190     avctx->sw_pix_fmt = fmt[n - 1];
1191     av_assert2(!is_hwaccel_pix_fmt(avctx->sw_pix_fmt));
1192
1193     choices = av_malloc_array(n + 1, sizeof(*choices));
1194     if (!choices)
1195         return AV_PIX_FMT_NONE;
1196
1197     memcpy(choices, fmt, (n + 1) * sizeof(*choices));
1198
1199     for (;;) {
1200         if (avctx->hwaccel && avctx->hwaccel->uninit)
1201             avctx->hwaccel->uninit(avctx);
1202         av_freep(&avctx->internal->hwaccel_priv_data);
1203         avctx->hwaccel = NULL;
1204
1205         av_buffer_unref(&avctx->hw_frames_ctx);
1206
1207         ret = avctx->get_format(avctx, choices);
1208
1209         desc = av_pix_fmt_desc_get(ret);
1210         if (!desc) {
1211             ret = AV_PIX_FMT_NONE;
1212             break;
1213         }
1214
1215         if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1216             break;
1217
1218         if (avctx->hw_frames_ctx) {
1219             AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1220             if (hw_frames_ctx->format != ret) {
1221                 av_log(avctx, AV_LOG_ERROR, "Format returned from get_buffer() "
1222                        "does not match the format of provided AVHWFramesContext\n");
1223                 ret = AV_PIX_FMT_NONE;
1224                 break;
1225             }
1226         }
1227
1228         if (!setup_hwaccel(avctx, ret, desc->name))
1229             break;
1230
1231         /* Remove failed hwaccel from choices */
1232         for (n = 0; choices[n] != ret; n++)
1233             av_assert0(choices[n] != AV_PIX_FMT_NONE);
1234
1235         do
1236             choices[n] = choices[n + 1];
1237         while (choices[n++] != AV_PIX_FMT_NONE);
1238     }
1239
1240     av_freep(&choices);
1241     return ret;
1242 }
1243
1244 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
1245 {
1246     FramePool *pool = avctx->internal->pool;
1247     int i, ret;
1248
1249     switch (avctx->codec_type) {
1250     case AVMEDIA_TYPE_VIDEO: {
1251         uint8_t *data[4];
1252         int linesize[4];
1253         int size[4] = { 0 };
1254         int w = frame->width;
1255         int h = frame->height;
1256         int tmpsize, unaligned;
1257
1258         if (pool->format == frame->format &&
1259             pool->width == frame->width && pool->height == frame->height)
1260             return 0;
1261
1262         avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
1263
1264         do {
1265             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
1266             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
1267             ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
1268             if (ret < 0)
1269                 return ret;
1270             // increase alignment of w for next try (rhs gives the lowest bit set in w)
1271             w += w & ~(w - 1);
1272
1273             unaligned = 0;
1274             for (i = 0; i < 4; i++)
1275                 unaligned |= linesize[i] % pool->stride_align[i];
1276         } while (unaligned);
1277
1278         tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
1279                                          NULL, linesize);
1280         if (tmpsize < 0)
1281             return -1;
1282
1283         for (i = 0; i < 3 && data[i + 1]; i++)
1284             size[i] = data[i + 1] - data[i];
1285         size[i] = tmpsize - (data[i] - data[0]);
1286
1287         for (i = 0; i < 4; i++) {
1288             av_buffer_pool_uninit(&pool->pools[i]);
1289             pool->linesize[i] = linesize[i];
1290             if (size[i]) {
1291                 pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
1292                                                      CONFIG_MEMORY_POISONING ?
1293                                                         NULL :
1294                                                         av_buffer_allocz);
1295                 if (!pool->pools[i]) {
1296                     ret = AVERROR(ENOMEM);
1297                     goto fail;
1298                 }
1299             }
1300         }
1301         pool->format = frame->format;
1302         pool->width  = frame->width;
1303         pool->height = frame->height;
1304
1305         break;
1306         }
1307     case AVMEDIA_TYPE_AUDIO: {
1308         int ch     = frame->channels; //av_get_channel_layout_nb_channels(frame->channel_layout);
1309         int planar = av_sample_fmt_is_planar(frame->format);
1310         int planes = planar ? ch : 1;
1311
1312         if (pool->format == frame->format && pool->planes == planes &&
1313             pool->channels == ch && frame->nb_samples == pool->samples)
1314             return 0;
1315
1316         av_buffer_pool_uninit(&pool->pools[0]);
1317         ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
1318                                          frame->nb_samples, frame->format, 0);
1319         if (ret < 0)
1320             goto fail;
1321
1322         pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
1323         if (!pool->pools[0]) {
1324             ret = AVERROR(ENOMEM);
1325             goto fail;
1326         }
1327
1328         pool->format     = frame->format;
1329         pool->planes     = planes;
1330         pool->channels   = ch;
1331         pool->samples = frame->nb_samples;
1332         break;
1333         }
1334     default: av_assert0(0);
1335     }
1336     return 0;
1337 fail:
1338     for (i = 0; i < 4; i++)
1339         av_buffer_pool_uninit(&pool->pools[i]);
1340     pool->format = -1;
1341     pool->planes = pool->channels = pool->samples = 0;
1342     pool->width  = pool->height = 0;
1343     return ret;
1344 }
1345
1346 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
1347 {
1348     FramePool *pool = avctx->internal->pool;
1349     int planes = pool->planes;
1350     int i;
1351
1352     frame->linesize[0] = pool->linesize[0];
1353
1354     if (planes > AV_NUM_DATA_POINTERS) {
1355         frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
1356         frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
1357         frame->extended_buf  = av_mallocz_array(frame->nb_extended_buf,
1358                                           sizeof(*frame->extended_buf));
1359         if (!frame->extended_data || !frame->extended_buf) {
1360             av_freep(&frame->extended_data);
1361             av_freep(&frame->extended_buf);
1362             return AVERROR(ENOMEM);
1363         }
1364     } else {
1365         frame->extended_data = frame->data;
1366         av_assert0(frame->nb_extended_buf == 0);
1367     }
1368
1369     for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
1370         frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
1371         if (!frame->buf[i])
1372             goto fail;
1373         frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
1374     }
1375     for (i = 0; i < frame->nb_extended_buf; i++) {
1376         frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
1377         if (!frame->extended_buf[i])
1378             goto fail;
1379         frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
1380     }
1381
1382     if (avctx->debug & FF_DEBUG_BUFFERS)
1383         av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
1384
1385     return 0;
1386 fail:
1387     av_frame_unref(frame);
1388     return AVERROR(ENOMEM);
1389 }
1390
1391 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
1392 {
1393     FramePool *pool = s->internal->pool;
1394     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
1395     int i;
1396
1397     if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
1398         av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
1399         return -1;
1400     }
1401
1402     if (!desc) {
1403         av_log(s, AV_LOG_ERROR,
1404             "Unable to get pixel format descriptor for format %s\n",
1405             av_get_pix_fmt_name(pic->format));
1406         return AVERROR(EINVAL);
1407     }
1408
1409     memset(pic->data, 0, sizeof(pic->data));
1410     pic->extended_data = pic->data;
1411
1412     for (i = 0; i < 4 && pool->pools[i]; i++) {
1413         pic->linesize[i] = pool->linesize[i];
1414
1415         pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
1416         if (!pic->buf[i])
1417             goto fail;
1418
1419         pic->data[i] = pic->buf[i]->data;
1420     }
1421     for (; i < AV_NUM_DATA_POINTERS; i++) {
1422         pic->data[i] = NULL;
1423         pic->linesize[i] = 0;
1424     }
1425     if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
1426         desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)
1427         avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
1428
1429     if (s->debug & FF_DEBUG_BUFFERS)
1430         av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
1431
1432     return 0;
1433 fail:
1434     av_frame_unref(pic);
1435     return AVERROR(ENOMEM);
1436 }
1437
1438 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
1439 {
1440     int ret;
1441
1442     if (avctx->hw_frames_ctx) {
1443         ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
1444         frame->width  = avctx->coded_width;
1445         frame->height = avctx->coded_height;
1446         return ret;
1447     }
1448
1449     if ((ret = update_frame_pool(avctx, frame)) < 0)
1450         return ret;
1451
1452     switch (avctx->codec_type) {
1453     case AVMEDIA_TYPE_VIDEO:
1454         return video_get_buffer(avctx, frame);
1455     case AVMEDIA_TYPE_AUDIO:
1456         return audio_get_buffer(avctx, frame);
1457     default:
1458         return -1;
1459     }
1460 }
1461
1462 static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
1463 {
1464     int size;
1465     const uint8_t *side_metadata;
1466
1467     AVDictionary **frame_md = &frame->metadata;
1468
1469     side_metadata = av_packet_get_side_data(avpkt,
1470                                             AV_PKT_DATA_STRINGS_METADATA, &size);
1471     return av_packet_unpack_dictionary(side_metadata, size, frame_md);
1472 }
1473
1474 int ff_init_buffer_info(AVCodecContext *avctx, AVFrame *frame)
1475 {
1476     const AVPacket *pkt = avctx->internal->last_pkt_props;
1477     int i;
1478     static const struct {
1479         enum AVPacketSideDataType packet;
1480         enum AVFrameSideDataType frame;
1481     } sd[] = {
1482         { AV_PKT_DATA_REPLAYGAIN ,                AV_FRAME_DATA_REPLAYGAIN },
1483         { AV_PKT_DATA_DISPLAYMATRIX,              AV_FRAME_DATA_DISPLAYMATRIX },
1484         { AV_PKT_DATA_SPHERICAL,                  AV_FRAME_DATA_SPHERICAL },
1485         { AV_PKT_DATA_STEREO3D,                   AV_FRAME_DATA_STEREO3D },
1486         { AV_PKT_DATA_AUDIO_SERVICE_TYPE,         AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
1487         { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
1488         { AV_PKT_DATA_CONTENT_LIGHT_LEVEL,        AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
1489         { AV_PKT_DATA_A53_CC,                     AV_FRAME_DATA_A53_CC },
1490     };
1491
1492     if (pkt) {
1493         frame->pts = pkt->pts;
1494 #if FF_API_PKT_PTS
1495 FF_DISABLE_DEPRECATION_WARNINGS
1496         frame->pkt_pts = pkt->pts;
1497 FF_ENABLE_DEPRECATION_WARNINGS
1498 #endif
1499         frame->pkt_pos      = pkt->pos;
1500         frame->pkt_duration = pkt->duration;
1501         frame->pkt_size     = pkt->size;
1502
1503         for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
1504             int size;
1505             uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
1506             if (packet_sd) {
1507                 AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
1508                                                                    sd[i].frame,
1509                                                                    size);
1510                 if (!frame_sd)
1511                     return AVERROR(ENOMEM);
1512
1513                 memcpy(frame_sd->data, packet_sd, size);
1514             }
1515         }
1516         add_metadata_from_side_data(pkt, frame);
1517
1518         if (pkt->flags & AV_PKT_FLAG_DISCARD) {
1519             frame->flags |= AV_FRAME_FLAG_DISCARD;
1520         } else {
1521             frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
1522         }
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 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1583 {
1584     return ff_init_buffer_info(avctx, frame);
1585 }
1586
1587 static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
1588 {
1589     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1590         int i;
1591         int num_planes = av_pix_fmt_count_planes(frame->format);
1592         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
1593         int flags = desc ? desc->flags : 0;
1594         if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
1595             num_planes = 2;
1596         for (i = 0; i < num_planes; i++) {
1597             av_assert0(frame->data[i]);
1598         }
1599         // For now do not enforce anything for palette of pseudopal formats
1600         if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PSEUDOPAL))
1601             num_planes = 2;
1602         // For formats without data like hwaccel allow unused pointers to be non-NULL.
1603         for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
1604             if (frame->data[i])
1605                 av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
1606             frame->data[i] = NULL;
1607         }
1608     }
1609 }
1610
1611 static int get_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
1612 {
1613     const AVHWAccel *hwaccel = avctx->hwaccel;
1614     int override_dimensions = 1;
1615     int ret;
1616
1617     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1618         if ((ret = av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) {
1619             av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
1620             return AVERROR(EINVAL);
1621         }
1622
1623         if (frame->width <= 0 || frame->height <= 0) {
1624             frame->width  = FFMAX(avctx->width,  AV_CEIL_RSHIFT(avctx->coded_width,  avctx->lowres));
1625             frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
1626             override_dimensions = 0;
1627         }
1628
1629         if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
1630             av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
1631             return AVERROR(EINVAL);
1632         }
1633     }
1634     ret = ff_decode_frame_props(avctx, frame);
1635     if (ret < 0)
1636         return ret;
1637
1638     if (hwaccel) {
1639         if (hwaccel->alloc_frame) {
1640             ret = hwaccel->alloc_frame(avctx, frame);
1641             goto end;
1642         }
1643     } else
1644         avctx->sw_pix_fmt = avctx->pix_fmt;
1645
1646     ret = avctx->get_buffer2(avctx, frame, flags);
1647     if (ret >= 0)
1648         validate_avframe_allocation(avctx, frame);
1649
1650 end:
1651     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
1652         !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
1653         frame->width  = avctx->width;
1654         frame->height = avctx->height;
1655     }
1656
1657     return ret;
1658 }
1659
1660 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1661 {
1662     int ret = get_buffer_internal(avctx, frame, flags);
1663     if (ret < 0) {
1664         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1665         frame->width = frame->height = 0;
1666     }
1667     return ret;
1668 }
1669
1670 static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame)
1671 {
1672     AVFrame *tmp;
1673     int ret;
1674
1675     av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1676
1677     if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
1678         av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
1679                frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
1680         av_frame_unref(frame);
1681     }
1682
1683     ff_init_buffer_info(avctx, frame);
1684
1685     if (!frame->data[0])
1686         return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1687
1688     if (av_frame_is_writable(frame))
1689         return ff_decode_frame_props(avctx, frame);
1690
1691     tmp = av_frame_alloc();
1692     if (!tmp)
1693         return AVERROR(ENOMEM);
1694
1695     av_frame_move_ref(tmp, frame);
1696
1697     ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1698     if (ret < 0) {
1699         av_frame_free(&tmp);
1700         return ret;
1701     }
1702
1703     av_frame_copy(frame, tmp);
1704     av_frame_free(&tmp);
1705
1706     return 0;
1707 }
1708
1709 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
1710 {
1711     int ret = reget_buffer_internal(avctx, frame);
1712     if (ret < 0)
1713         av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1714     return ret;
1715 }
1716
1717 void avcodec_flush_buffers(AVCodecContext *avctx)
1718 {
1719     avctx->internal->draining      = 0;
1720     avctx->internal->draining_done = 0;
1721     avctx->internal->nb_draining_errors = 0;
1722     av_frame_unref(avctx->internal->buffer_frame);
1723     av_frame_unref(avctx->internal->compat_decode_frame);
1724     av_packet_unref(avctx->internal->buffer_pkt);
1725     avctx->internal->buffer_pkt_valid = 0;
1726
1727     av_packet_unref(avctx->internal->ds.in_pkt);
1728
1729     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1730         ff_thread_flush(avctx);
1731     else if (avctx->codec->flush)
1732         avctx->codec->flush(avctx);
1733
1734     avctx->pts_correction_last_pts =
1735     avctx->pts_correction_last_dts = INT64_MIN;
1736
1737     ff_decode_bsfs_uninit(avctx);
1738
1739     if (!avctx->refcounted_frames)
1740         av_frame_unref(avctx->internal->to_free);
1741 }
1742
1743 void ff_decode_bsfs_uninit(AVCodecContext *avctx)
1744 {
1745     DecodeFilterContext *s = &avctx->internal->filter;
1746     int i;
1747
1748     for (i = 0; i < s->nb_bsfs; i++)
1749         av_bsf_free(&s->bsfs[i]);
1750     av_freep(&s->bsfs);
1751     s->nb_bsfs = 0;
1752 }