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