]> git.sesse.net Git - ffmpeg/blob - libavcodec/decode.c
Merge commit '6151e9128ce2a84a443c82b78f5b5cb364ba2ab4'
[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(pkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
466         if(side && side_size>=10) {
467             avctx->internal->skip_samples = AV_RL32(side) * avctx->internal->skip_samples_multiplier;
468             discard_padding = AV_RL32(side + 4);
469             av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
470                    avctx->internal->skip_samples, (int)discard_padding);
471             skip_reason = AV_RL8(side + 8);
472             discard_reason = AV_RL8(side + 9);
473         }
474
475         if ((frame->flags & AV_FRAME_FLAG_DISCARD) && got_frame &&
476             !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
477             avctx->internal->skip_samples = FFMAX(0, avctx->internal->skip_samples - frame->nb_samples);
478             got_frame = 0;
479         }
480
481         if (avctx->internal->skip_samples > 0 && got_frame &&
482             !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
483             if(frame->nb_samples <= avctx->internal->skip_samples){
484                 got_frame = 0;
485                 avctx->internal->skip_samples -= frame->nb_samples;
486                 av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
487                        avctx->internal->skip_samples);
488             } else {
489                 av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,
490                                 frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);
491                 if(avctx->pkt_timebase.num && avctx->sample_rate) {
492                     int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,
493                                                    (AVRational){1, avctx->sample_rate},
494                                                    avctx->pkt_timebase);
495                     if(frame->pts!=AV_NOPTS_VALUE)
496                         frame->pts += diff_ts;
497 #if FF_API_PKT_PTS
498 FF_DISABLE_DEPRECATION_WARNINGS
499                     if(frame->pkt_pts!=AV_NOPTS_VALUE)
500                         frame->pkt_pts += diff_ts;
501 FF_ENABLE_DEPRECATION_WARNINGS
502 #endif
503                     if(frame->pkt_dts!=AV_NOPTS_VALUE)
504                         frame->pkt_dts += diff_ts;
505                     if (frame->pkt_duration >= diff_ts)
506                         frame->pkt_duration -= diff_ts;
507                 } else {
508                     av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
509                 }
510                 av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
511                        avctx->internal->skip_samples, frame->nb_samples);
512                 frame->nb_samples -= avctx->internal->skip_samples;
513                 avctx->internal->skip_samples = 0;
514             }
515         }
516
517         if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
518             !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
519             if (discard_padding == frame->nb_samples) {
520                 got_frame = 0;
521             } else {
522                 if(avctx->pkt_timebase.num && avctx->sample_rate) {
523                     int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
524                                                    (AVRational){1, avctx->sample_rate},
525                                                    avctx->pkt_timebase);
526                     frame->pkt_duration = diff_ts;
527                 } else {
528                     av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
529                 }
530                 av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
531                        (int)discard_padding, frame->nb_samples);
532                 frame->nb_samples -= discard_padding;
533             }
534         }
535
536         if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
537             AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
538             if (fside) {
539                 AV_WL32(fside->data, avctx->internal->skip_samples);
540                 AV_WL32(fside->data + 4, discard_padding);
541                 AV_WL8(fside->data + 8, skip_reason);
542                 AV_WL8(fside->data + 9, discard_reason);
543                 avctx->internal->skip_samples = 0;
544             }
545         }
546     }
547 #if FF_API_MERGE_SD
548     if (did_split) {
549         av_packet_free_side_data(&tmp);
550         if(ret == tmp.size)
551             ret = pkt->size;
552     }
553 #endif
554
555     if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
556         !avci->showed_multi_packet_warning &&
557         ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
558         av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
559         avci->showed_multi_packet_warning = 1;
560     }
561
562     if (!got_frame)
563         av_frame_unref(frame);
564
565     if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
566         ret = pkt->size;
567
568 #if FF_API_AVCTX_TIMEBASE
569     if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
570         avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
571 #endif
572
573     /* do not stop draining when actual_got_frame != 0 or ret < 0 */
574     /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */
575     if (avctx->internal->draining && !actual_got_frame) {
576         if (ret < 0) {
577             /* prevent infinite loop if a decoder wrongly always return error on draining */
578             /* reasonable nb_errors_max = maximum b frames + thread count */
579             int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
580                                 avctx->thread_count : 1);
581
582             if (avci->nb_draining_errors++ >= nb_errors_max) {
583                 av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
584                        "Stop draining and force EOF.\n");
585                 avci->draining_done = 1;
586                 ret = AVERROR_BUG;
587             }
588         } else {
589             avci->draining_done = 1;
590         }
591     }
592
593     avci->compat_decode_consumed += ret;
594
595     if (ret >= pkt->size || ret < 0) {
596         av_packet_unref(pkt);
597     } else {
598         int consumed = ret;
599
600         pkt->data                += consumed;
601         pkt->size                -= consumed;
602         avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
603         pkt->pts                  = AV_NOPTS_VALUE;
604         pkt->dts                  = AV_NOPTS_VALUE;
605         avci->last_pkt_props->pts = AV_NOPTS_VALUE;
606         avci->last_pkt_props->dts = AV_NOPTS_VALUE;
607     }
608
609     if (got_frame)
610         av_assert0(frame->buf[0]);
611
612     return ret < 0 ? ret : 0;
613 }
614
615 static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
616 {
617     int ret;
618
619     while (!frame->buf[0]) {
620         ret = decode_simple_internal(avctx, frame);
621         if (ret < 0)
622             return ret;
623     }
624
625     return 0;
626 }
627
628 static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
629 {
630     AVCodecInternal *avci = avctx->internal;
631     int ret;
632
633     av_assert0(!frame->buf[0]);
634
635     if (avctx->codec->receive_frame)
636         ret = avctx->codec->receive_frame(avctx, frame);
637     else
638         ret = decode_simple_receive_frame(avctx, frame);
639
640     if (ret == AVERROR_EOF)
641         avci->draining_done = 1;
642
643     return ret;
644 }
645
646 int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
647 {
648     AVCodecInternal *avci = avctx->internal;
649     int ret;
650
651     if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
652         return AVERROR(EINVAL);
653
654     if (avctx->internal->draining)
655         return AVERROR_EOF;
656
657     if (avpkt && !avpkt->size && avpkt->data)
658         return AVERROR(EINVAL);
659
660     ret = bsfs_init(avctx);
661     if (ret < 0)
662         return ret;
663
664     av_packet_unref(avci->buffer_pkt);
665     if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
666         ret = av_packet_ref(avci->buffer_pkt, avpkt);
667         if (ret < 0)
668             return ret;
669     }
670
671     ret = av_bsf_send_packet(avci->filter.bsfs[0], avci->buffer_pkt);
672     if (ret < 0) {
673         av_packet_unref(avci->buffer_pkt);
674         return ret;
675     }
676
677     if (!avci->buffer_frame->buf[0]) {
678         ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
679         if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
680             return ret;
681     }
682
683     return 0;
684 }
685
686 static int calc_cropping_offsets(size_t offsets[4], const AVFrame *frame,
687                                  const AVPixFmtDescriptor *desc)
688 {
689     int i, j;
690
691     for (i = 0; frame->data[i]; i++) {
692         const AVComponentDescriptor *comp = NULL;
693         int shift_x = (i == 1 || i == 2) ? desc->log2_chroma_w : 0;
694         int shift_y = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;
695
696         if (desc->flags & (AV_PIX_FMT_FLAG_PAL | AV_PIX_FMT_FLAG_PSEUDOPAL) && i == 1) {
697             offsets[i] = 0;
698             break;
699         }
700
701         /* find any component descriptor for this plane */
702         for (j = 0; j < desc->nb_components; j++) {
703             if (desc->comp[j].plane == i) {
704                 comp = &desc->comp[j];
705                 break;
706             }
707         }
708         if (!comp)
709             return AVERROR_BUG;
710
711         offsets[i] = (frame->crop_top  >> shift_y) * frame->linesize[i] +
712                      (frame->crop_left >> shift_x) * comp->step;
713     }
714
715     return 0;
716 }
717
718 static int apply_cropping(AVCodecContext *avctx, AVFrame *frame)
719 {
720     const AVPixFmtDescriptor *desc;
721     size_t offsets[4];
722     int i;
723
724     /* make sure we are noisy about decoders returning invalid cropping data */
725     if (frame->crop_left >= INT_MAX - frame->crop_right        ||
726         frame->crop_top  >= INT_MAX - frame->crop_bottom       ||
727         (frame->crop_left + frame->crop_right) >= frame->width ||
728         (frame->crop_top + frame->crop_bottom) >= frame->height) {
729         av_log(avctx, AV_LOG_WARNING,
730                "Invalid cropping information set by a decoder: "
731                "%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER" "
732                "(frame size %dx%d). This is a bug, please report it\n",
733                frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
734                frame->width, frame->height);
735         frame->crop_left   = 0;
736         frame->crop_right  = 0;
737         frame->crop_top    = 0;
738         frame->crop_bottom = 0;
739         return 0;
740     }
741
742     if (!avctx->apply_cropping)
743         return 0;
744
745     desc = av_pix_fmt_desc_get(frame->format);
746     if (!desc)
747         return AVERROR_BUG;
748
749     /* Apply just the right/bottom cropping for hwaccel formats. Bitstream
750      * formats cannot be easily handled here either (and corresponding decoders
751      * should not export any cropping anyway), so do the same for those as well.
752      * */
753     if (desc->flags & (AV_PIX_FMT_FLAG_BITSTREAM | AV_PIX_FMT_FLAG_HWACCEL)) {
754         frame->width      -= frame->crop_right;
755         frame->height     -= frame->crop_bottom;
756         frame->crop_right  = 0;
757         frame->crop_bottom = 0;
758         return 0;
759     }
760
761     /* calculate the offsets for each plane */
762     calc_cropping_offsets(offsets, frame, desc);
763
764     /* adjust the offsets to avoid breaking alignment */
765     if (!(avctx->flags & AV_CODEC_FLAG_UNALIGNED)) {
766         int min_log2_align = INT_MAX;
767
768         for (i = 0; frame->data[i]; i++) {
769             int log2_align = offsets[i] ? ff_ctz(offsets[i]) : INT_MAX;
770             min_log2_align = FFMIN(log2_align, min_log2_align);
771         }
772
773         if (min_log2_align < 5) {
774             frame->crop_left &= ~((1 << min_log2_align) - 1);
775             calc_cropping_offsets(offsets, frame, desc);
776         }
777     }
778
779     for (i = 0; frame->data[i]; i++)
780         frame->data[i] += offsets[i];
781
782     frame->width      -= (frame->crop_left + frame->crop_right);
783     frame->height     -= (frame->crop_top  + frame->crop_bottom);
784     frame->crop_left   = 0;
785     frame->crop_right  = 0;
786     frame->crop_top    = 0;
787     frame->crop_bottom = 0;
788
789     return 0;
790 }
791
792 int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
793 {
794     AVCodecInternal *avci = avctx->internal;
795     int ret;
796
797     av_frame_unref(frame);
798
799     if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
800         return AVERROR(EINVAL);
801
802     ret = bsfs_init(avctx);
803     if (ret < 0)
804         return ret;
805
806     if (avci->buffer_frame->buf[0]) {
807         av_frame_move_ref(frame, avci->buffer_frame);
808     } else {
809         ret = decode_receive_frame_internal(avctx, frame);
810         if (ret < 0)
811             return ret;
812     }
813
814     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
815         ret = apply_cropping(avctx, frame);
816         if (ret < 0) {
817             av_frame_unref(frame);
818             return ret;
819         }
820     }
821
822     avctx->frame_number++;
823
824     return 0;
825 }
826
827 static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
828                          int *got_frame, const AVPacket *pkt)
829 {
830     AVCodecInternal *avci = avctx->internal;
831     int ret = 0;
832
833     av_assert0(avci->compat_decode_consumed == 0);
834
835     *got_frame = 0;
836     avci->compat_decode = 1;
837
838     if (avci->compat_decode_partial_size > 0 &&
839         avci->compat_decode_partial_size != pkt->size) {
840         av_log(avctx, AV_LOG_ERROR,
841                "Got unexpected packet size after a partial decode\n");
842         ret = AVERROR(EINVAL);
843         goto finish;
844     }
845
846     if (!avci->compat_decode_partial_size) {
847         ret = avcodec_send_packet(avctx, pkt);
848         if (ret == AVERROR_EOF)
849             ret = 0;
850         else if (ret == AVERROR(EAGAIN)) {
851             /* we fully drain all the output in each decode call, so this should not
852              * ever happen */
853             ret = AVERROR_BUG;
854             goto finish;
855         } else if (ret < 0)
856             goto finish;
857     }
858
859     while (ret >= 0) {
860         ret = avcodec_receive_frame(avctx, frame);
861         if (ret < 0) {
862             if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
863                 ret = 0;
864             goto finish;
865         }
866
867         if (frame != avci->compat_decode_frame) {
868             if (!avctx->refcounted_frames) {
869                 ret = unrefcount_frame(avci, frame);
870                 if (ret < 0)
871                     goto finish;
872             }
873
874             *got_frame = 1;
875             frame = avci->compat_decode_frame;
876         } else {
877             if (!avci->compat_decode_warned) {
878                 av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
879                        "API cannot return all the frames for this decoder. "
880                        "Some frames will be dropped. Update your code to the "
881                        "new decoding API to fix this.\n");
882                 avci->compat_decode_warned = 1;
883             }
884         }
885
886         if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
887             break;
888     }
889
890 finish:
891     if (ret == 0) {
892         /* if there are any bsfs then assume full packet is always consumed */
893         if (avctx->codec->bsfs)
894             ret = pkt->size;
895         else
896             ret = FFMIN(avci->compat_decode_consumed, pkt->size);
897     }
898     avci->compat_decode_consumed = 0;
899     avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
900
901     return ret;
902 }
903
904 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
905                                               int *got_picture_ptr,
906                                               const AVPacket *avpkt)
907 {
908     return compat_decode(avctx, picture, got_picture_ptr, avpkt);
909 }
910
911 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
912                                               AVFrame *frame,
913                                               int *got_frame_ptr,
914                                               const AVPacket *avpkt)
915 {
916     return compat_decode(avctx, frame, got_frame_ptr, avpkt);
917 }
918
919 static void get_subtitle_defaults(AVSubtitle *sub)
920 {
921     memset(sub, 0, sizeof(*sub));
922     sub->pts = AV_NOPTS_VALUE;
923 }
924
925 #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
926 static int recode_subtitle(AVCodecContext *avctx,
927                            AVPacket *outpkt, const AVPacket *inpkt)
928 {
929 #if CONFIG_ICONV
930     iconv_t cd = (iconv_t)-1;
931     int ret = 0;
932     char *inb, *outb;
933     size_t inl, outl;
934     AVPacket tmp;
935 #endif
936
937     if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
938         return 0;
939
940 #if CONFIG_ICONV
941     cd = iconv_open("UTF-8", avctx->sub_charenc);
942     av_assert0(cd != (iconv_t)-1);
943
944     inb = inpkt->data;
945     inl = inpkt->size;
946
947     if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
948         av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
949         ret = AVERROR(ENOMEM);
950         goto end;
951     }
952
953     ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
954     if (ret < 0)
955         goto end;
956     outpkt->buf  = tmp.buf;
957     outpkt->data = tmp.data;
958     outpkt->size = tmp.size;
959     outb = outpkt->data;
960     outl = outpkt->size;
961
962     if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
963         iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
964         outl >= outpkt->size || inl != 0) {
965         ret = FFMIN(AVERROR(errno), -1);
966         av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
967                "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
968         av_packet_unref(&tmp);
969         goto end;
970     }
971     outpkt->size -= outl;
972     memset(outpkt->data + outpkt->size, 0, outl);
973
974 end:
975     if (cd != (iconv_t)-1)
976         iconv_close(cd);
977     return ret;
978 #else
979     av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
980     return AVERROR(EINVAL);
981 #endif
982 }
983
984 static int utf8_check(const uint8_t *str)
985 {
986     const uint8_t *byte;
987     uint32_t codepoint, min;
988
989     while (*str) {
990         byte = str;
991         GET_UTF8(codepoint, *(byte++), return 0;);
992         min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
993               1 << (5 * (byte - str) - 4);
994         if (codepoint < min || codepoint >= 0x110000 ||
995             codepoint == 0xFFFE /* BOM */ ||
996             codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
997             return 0;
998         str = byte;
999     }
1000     return 1;
1001 }
1002
1003 #if FF_API_ASS_TIMING
1004 static void insert_ts(AVBPrint *buf, int ts)
1005 {
1006     if (ts == -1) {
1007         av_bprintf(buf, "9:59:59.99,");
1008     } else {
1009         int h, m, s;
1010
1011         h = ts/360000;  ts -= 360000*h;
1012         m = ts/  6000;  ts -=   6000*m;
1013         s = ts/   100;  ts -=    100*s;
1014         av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
1015     }
1016 }
1017
1018 static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
1019 {
1020     int i;
1021     AVBPrint buf;
1022
1023     av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
1024
1025     for (i = 0; i < sub->num_rects; i++) {
1026         char *final_dialog;
1027         const char *dialog;
1028         AVSubtitleRect *rect = sub->rects[i];
1029         int ts_start, ts_duration = -1;
1030         long int layer;
1031
1032         if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
1033             continue;
1034
1035         av_bprint_clear(&buf);
1036
1037         /* skip ReadOrder */
1038         dialog = strchr(rect->ass, ',');
1039         if (!dialog)
1040             continue;
1041         dialog++;
1042
1043         /* extract Layer or Marked */
1044         layer = strtol(dialog, (char**)&dialog, 10);
1045         if (*dialog != ',')
1046             continue;
1047         dialog++;
1048
1049         /* rescale timing to ASS time base (ms) */
1050         ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
1051         if (pkt->duration != -1)
1052             ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
1053         sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
1054
1055         /* construct ASS (standalone file form with timestamps) string */
1056         av_bprintf(&buf, "Dialogue: %ld,", layer);
1057         insert_ts(&buf, ts_start);
1058         insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
1059         av_bprintf(&buf, "%s\r\n", dialog);
1060
1061         final_dialog = av_strdup(buf.str);
1062         if (!av_bprint_is_complete(&buf) || !final_dialog) {
1063             av_freep(&final_dialog);
1064             av_bprint_finalize(&buf, NULL);
1065             return AVERROR(ENOMEM);
1066         }
1067         av_freep(&rect->ass);
1068         rect->ass = final_dialog;
1069     }
1070
1071     av_bprint_finalize(&buf, NULL);
1072     return 0;
1073 }
1074 #endif
1075
1076 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1077                              int *got_sub_ptr,
1078                              AVPacket *avpkt)
1079 {
1080     int i, ret = 0;
1081     AVCodecInternal *avci = avctx->internal;
1082
1083     if (!avpkt->data && avpkt->size) {
1084         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1085         return AVERROR(EINVAL);
1086     }
1087     if (!avctx->codec)
1088         return AVERROR(EINVAL);
1089     if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
1090         av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
1091         return AVERROR(EINVAL);
1092     }
1093
1094     *got_sub_ptr = 0;
1095     get_subtitle_defaults(sub);
1096
1097     if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
1098         AVPacket pkt_recoded;
1099         AVPacket tmp = *avpkt;
1100 #if FF_API_MERGE_SD
1101 FF_DISABLE_DEPRECATION_WARNINGS
1102         int did_split = avci->compat_decode_partial_size ?
1103                         ff_packet_split_and_drop_side_data(&tmp) :
1104                         av_packet_split_side_data(&tmp);
1105         //apply_param_change(avctx, &tmp);
1106
1107         if (did_split) {
1108             /* FFMIN() prevents overflow in case the packet wasn't allocated with
1109              * proper padding.
1110              * If the side data is smaller than the buffer padding size, the
1111              * remaining bytes should have already been filled with zeros by the
1112              * original packet allocation anyway. */
1113             memset(tmp.data + tmp.size, 0,
1114                    FFMIN(avpkt->size - tmp.size, AV_INPUT_BUFFER_PADDING_SIZE));
1115         }
1116 FF_ENABLE_DEPRECATION_WARNINGS
1117 #endif
1118
1119         pkt_recoded = tmp;
1120         ret = recode_subtitle(avctx, &pkt_recoded, &tmp);
1121         if (ret < 0) {
1122             *got_sub_ptr = 0;
1123         } else {
1124              ret = extract_packet_props(avctx->internal, &pkt_recoded);
1125              if (ret < 0)
1126                 return ret;
1127
1128             if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
1129                 sub->pts = av_rescale_q(avpkt->pts,
1130                                         avctx->pkt_timebase, AV_TIME_BASE_Q);
1131             ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
1132             av_assert1((ret >= 0) >= !!*got_sub_ptr &&
1133                        !!*got_sub_ptr >= !!sub->num_rects);
1134
1135 #if FF_API_ASS_TIMING
1136             if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
1137                 && *got_sub_ptr && sub->num_rects) {
1138                 const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
1139                                                               : avctx->time_base;
1140                 int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
1141                 if (err < 0)
1142                     ret = err;
1143             }
1144 #endif
1145
1146             if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
1147                 avctx->pkt_timebase.num) {
1148                 AVRational ms = { 1, 1000 };
1149                 sub->end_display_time = av_rescale_q(avpkt->duration,
1150                                                      avctx->pkt_timebase, ms);
1151             }
1152
1153             if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
1154                 sub->format = 0;
1155             else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
1156                 sub->format = 1;
1157
1158             for (i = 0; i < sub->num_rects; i++) {
1159                 if (sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
1160                     av_log(avctx, AV_LOG_ERROR,
1161                            "Invalid UTF-8 in decoded subtitles text; "
1162                            "maybe missing -sub_charenc option\n");
1163                     avsubtitle_free(sub);
1164                     ret = AVERROR_INVALIDDATA;
1165                     break;
1166                 }
1167             }
1168
1169             if (tmp.data != pkt_recoded.data) { // did we recode?
1170                 /* prevent from destroying side data from original packet */
1171                 pkt_recoded.side_data = NULL;
1172                 pkt_recoded.side_data_elems = 0;
1173
1174                 av_packet_unref(&pkt_recoded);
1175             }
1176         }
1177
1178 #if FF_API_MERGE_SD
1179         if (did_split) {
1180             av_packet_free_side_data(&tmp);
1181             if(ret == tmp.size)
1182                 ret = avpkt->size;
1183         }
1184 #endif
1185
1186         if (*got_sub_ptr)
1187             avctx->frame_number++;
1188     }
1189
1190     return ret;
1191 }
1192
1193 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
1194 {
1195     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
1196     return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
1197 }
1198
1199 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
1200 {
1201     while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
1202         ++fmt;
1203     return fmt[0];
1204 }
1205
1206 static AVHWAccel *find_hwaccel(enum AVCodecID codec_id,
1207                                enum AVPixelFormat pix_fmt)
1208 {
1209     AVHWAccel *hwaccel = NULL;
1210
1211     while ((hwaccel = av_hwaccel_next(hwaccel)))
1212         if (hwaccel->id == codec_id
1213             && hwaccel->pix_fmt == pix_fmt)
1214             return hwaccel;
1215     return NULL;
1216 }
1217
1218 static int setup_hwaccel(AVCodecContext *avctx,
1219                          const enum AVPixelFormat fmt,
1220                          const char *name)
1221 {
1222     AVHWAccel *hwa = find_hwaccel(avctx->codec_id, fmt);
1223     int ret        = 0;
1224
1225     if (!hwa) {
1226         av_log(avctx, AV_LOG_ERROR,
1227                "Could not find an AVHWAccel for the pixel format: %s",
1228                name);
1229         return AVERROR(ENOENT);
1230     }
1231
1232     if (hwa->capabilities & HWACCEL_CODEC_CAP_EXPERIMENTAL &&
1233         avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1234         av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
1235                hwa->name);
1236         return AVERROR_PATCHWELCOME;
1237     }
1238
1239     if (hwa->priv_data_size) {
1240         avctx->internal->hwaccel_priv_data = av_mallocz(hwa->priv_data_size);
1241         if (!avctx->internal->hwaccel_priv_data)
1242             return AVERROR(ENOMEM);
1243     }
1244
1245     if (hwa->init) {
1246         ret = hwa->init(avctx);
1247         if (ret < 0) {
1248             av_freep(&avctx->internal->hwaccel_priv_data);
1249             return ret;
1250         }
1251     }
1252
1253     avctx->hwaccel = hwa;
1254
1255     return 0;
1256 }
1257
1258 int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1259 {
1260     const AVPixFmtDescriptor *desc;
1261     enum AVPixelFormat *choices;
1262     enum AVPixelFormat ret;
1263     unsigned n = 0;
1264
1265     while (fmt[n] != AV_PIX_FMT_NONE)
1266         ++n;
1267
1268     av_assert0(n >= 1);
1269     avctx->sw_pix_fmt = fmt[n - 1];
1270     av_assert2(!is_hwaccel_pix_fmt(avctx->sw_pix_fmt));
1271
1272     choices = av_malloc_array(n + 1, sizeof(*choices));
1273     if (!choices)
1274         return AV_PIX_FMT_NONE;
1275
1276     memcpy(choices, fmt, (n + 1) * sizeof(*choices));
1277
1278     for (;;) {
1279         if (avctx->hwaccel && avctx->hwaccel->uninit)
1280             avctx->hwaccel->uninit(avctx);
1281         av_freep(&avctx->internal->hwaccel_priv_data);
1282         avctx->hwaccel = NULL;
1283
1284         av_buffer_unref(&avctx->hw_frames_ctx);
1285
1286         ret = avctx->get_format(avctx, choices);
1287
1288         desc = av_pix_fmt_desc_get(ret);
1289         if (!desc) {
1290             ret = AV_PIX_FMT_NONE;
1291             break;
1292         }
1293
1294         if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1295             break;
1296 #if FF_API_CAP_VDPAU
1297         if (avctx->codec->capabilities&AV_CODEC_CAP_HWACCEL_VDPAU)
1298             break;
1299 #endif
1300
1301         if (avctx->hw_frames_ctx) {
1302             AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1303             if (hw_frames_ctx->format != ret) {
1304                 av_log(avctx, AV_LOG_ERROR, "Format returned from get_buffer() "
1305                        "does not match the format of provided AVHWFramesContext\n");
1306                 ret = AV_PIX_FMT_NONE;
1307                 break;
1308             }
1309         }
1310
1311         if (!setup_hwaccel(avctx, ret, desc->name))
1312             break;
1313
1314         /* Remove failed hwaccel from choices */
1315         for (n = 0; choices[n] != ret; n++)
1316             av_assert0(choices[n] != AV_PIX_FMT_NONE);
1317
1318         do
1319             choices[n] = choices[n + 1];
1320         while (choices[n++] != AV_PIX_FMT_NONE);
1321     }
1322
1323     av_freep(&choices);
1324     return ret;
1325 }
1326
1327 static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
1328 {
1329     FramePool *pool = avctx->internal->pool;
1330     int i, ret;
1331
1332     switch (avctx->codec_type) {
1333     case AVMEDIA_TYPE_VIDEO: {
1334         uint8_t *data[4];
1335         int linesize[4];
1336         int size[4] = { 0 };
1337         int w = frame->width;
1338         int h = frame->height;
1339         int tmpsize, unaligned;
1340
1341         if (pool->format == frame->format &&
1342             pool->width == frame->width && pool->height == frame->height)
1343             return 0;
1344
1345         avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
1346
1347         do {
1348             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
1349             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
1350             ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
1351             if (ret < 0)
1352                 return ret;
1353             // increase alignment of w for next try (rhs gives the lowest bit set in w)
1354             w += w & ~(w - 1);
1355
1356             unaligned = 0;
1357             for (i = 0; i < 4; i++)
1358                 unaligned |= linesize[i] % pool->stride_align[i];
1359         } while (unaligned);
1360
1361         tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
1362                                          NULL, linesize);
1363         if (tmpsize < 0)
1364             return -1;
1365
1366         for (i = 0; i < 3 && data[i + 1]; i++)
1367             size[i] = data[i + 1] - data[i];
1368         size[i] = tmpsize - (data[i] - data[0]);
1369
1370         for (i = 0; i < 4; i++) {
1371             av_buffer_pool_uninit(&pool->pools[i]);
1372             pool->linesize[i] = linesize[i];
1373             if (size[i]) {
1374                 pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
1375                                                      CONFIG_MEMORY_POISONING ?
1376                                                         NULL :
1377                                                         av_buffer_allocz);
1378                 if (!pool->pools[i]) {
1379                     ret = AVERROR(ENOMEM);
1380                     goto fail;
1381                 }
1382             }
1383         }
1384         pool->format = frame->format;
1385         pool->width  = frame->width;
1386         pool->height = frame->height;
1387
1388         break;
1389         }
1390     case AVMEDIA_TYPE_AUDIO: {
1391         int ch     = frame->channels; //av_get_channel_layout_nb_channels(frame->channel_layout);
1392         int planar = av_sample_fmt_is_planar(frame->format);
1393         int planes = planar ? ch : 1;
1394
1395         if (pool->format == frame->format && pool->planes == planes &&
1396             pool->channels == ch && frame->nb_samples == pool->samples)
1397             return 0;
1398
1399         av_buffer_pool_uninit(&pool->pools[0]);
1400         ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
1401                                          frame->nb_samples, frame->format, 0);
1402         if (ret < 0)
1403             goto fail;
1404
1405         pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
1406         if (!pool->pools[0]) {
1407             ret = AVERROR(ENOMEM);
1408             goto fail;
1409         }
1410
1411         pool->format     = frame->format;
1412         pool->planes     = planes;
1413         pool->channels   = ch;
1414         pool->samples = frame->nb_samples;
1415         break;
1416         }
1417     default: av_assert0(0);
1418     }
1419     return 0;
1420 fail:
1421     for (i = 0; i < 4; i++)
1422         av_buffer_pool_uninit(&pool->pools[i]);
1423     pool->format = -1;
1424     pool->planes = pool->channels = pool->samples = 0;
1425     pool->width  = pool->height = 0;
1426     return ret;
1427 }
1428
1429 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
1430 {
1431     FramePool *pool = avctx->internal->pool;
1432     int planes = pool->planes;
1433     int i;
1434
1435     frame->linesize[0] = pool->linesize[0];
1436
1437     if (planes > AV_NUM_DATA_POINTERS) {
1438         frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
1439         frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
1440         frame->extended_buf  = av_mallocz_array(frame->nb_extended_buf,
1441                                           sizeof(*frame->extended_buf));
1442         if (!frame->extended_data || !frame->extended_buf) {
1443             av_freep(&frame->extended_data);
1444             av_freep(&frame->extended_buf);
1445             return AVERROR(ENOMEM);
1446         }
1447     } else {
1448         frame->extended_data = frame->data;
1449         av_assert0(frame->nb_extended_buf == 0);
1450     }
1451
1452     for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
1453         frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
1454         if (!frame->buf[i])
1455             goto fail;
1456         frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
1457     }
1458     for (i = 0; i < frame->nb_extended_buf; i++) {
1459         frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
1460         if (!frame->extended_buf[i])
1461             goto fail;
1462         frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
1463     }
1464
1465     if (avctx->debug & FF_DEBUG_BUFFERS)
1466         av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
1467
1468     return 0;
1469 fail:
1470     av_frame_unref(frame);
1471     return AVERROR(ENOMEM);
1472 }
1473
1474 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
1475 {
1476     FramePool *pool = s->internal->pool;
1477     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
1478     int i;
1479
1480     if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
1481         av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
1482         return -1;
1483     }
1484
1485     if (!desc) {
1486         av_log(s, AV_LOG_ERROR,
1487             "Unable to get pixel format descriptor for format %s\n",
1488             av_get_pix_fmt_name(pic->format));
1489         return AVERROR(EINVAL);
1490     }
1491
1492     memset(pic->data, 0, sizeof(pic->data));
1493     pic->extended_data = pic->data;
1494
1495     for (i = 0; i < 4 && pool->pools[i]; i++) {
1496         pic->linesize[i] = pool->linesize[i];
1497
1498         pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
1499         if (!pic->buf[i])
1500             goto fail;
1501
1502         pic->data[i] = pic->buf[i]->data;
1503     }
1504     for (; i < AV_NUM_DATA_POINTERS; i++) {
1505         pic->data[i] = NULL;
1506         pic->linesize[i] = 0;
1507     }
1508     if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
1509         desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)
1510         avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
1511
1512     if (s->debug & FF_DEBUG_BUFFERS)
1513         av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
1514
1515     return 0;
1516 fail:
1517     av_frame_unref(pic);
1518     return AVERROR(ENOMEM);
1519 }
1520
1521 int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
1522 {
1523     int ret;
1524
1525     if (avctx->hw_frames_ctx)
1526         return av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
1527
1528     if ((ret = update_frame_pool(avctx, frame)) < 0)
1529         return ret;
1530
1531     switch (avctx->codec_type) {
1532     case AVMEDIA_TYPE_VIDEO:
1533         return video_get_buffer(avctx, frame);
1534     case AVMEDIA_TYPE_AUDIO:
1535         return audio_get_buffer(avctx, frame);
1536     default:
1537         return -1;
1538     }
1539 }
1540
1541 static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
1542 {
1543     int size;
1544     const uint8_t *side_metadata;
1545
1546     AVDictionary **frame_md = &frame->metadata;
1547
1548     side_metadata = av_packet_get_side_data(avpkt,
1549                                             AV_PKT_DATA_STRINGS_METADATA, &size);
1550     return av_packet_unpack_dictionary(side_metadata, size, frame_md);
1551 }
1552
1553 int ff_init_buffer_info(AVCodecContext *avctx, AVFrame *frame)
1554 {
1555     const AVPacket *pkt = avctx->internal->last_pkt_props;
1556     int i;
1557     static const struct {
1558         enum AVPacketSideDataType packet;
1559         enum AVFrameSideDataType frame;
1560     } sd[] = {
1561         { AV_PKT_DATA_REPLAYGAIN ,                AV_FRAME_DATA_REPLAYGAIN },
1562         { AV_PKT_DATA_DISPLAYMATRIX,              AV_FRAME_DATA_DISPLAYMATRIX },
1563         { AV_PKT_DATA_SPHERICAL,                  AV_FRAME_DATA_SPHERICAL },
1564         { AV_PKT_DATA_STEREO3D,                   AV_FRAME_DATA_STEREO3D },
1565         { AV_PKT_DATA_AUDIO_SERVICE_TYPE,         AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
1566         { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
1567         { AV_PKT_DATA_CONTENT_LIGHT_LEVEL,        AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
1568     };
1569
1570     if (pkt) {
1571         frame->pts = pkt->pts;
1572 #if FF_API_PKT_PTS
1573 FF_DISABLE_DEPRECATION_WARNINGS
1574         frame->pkt_pts = pkt->pts;
1575 FF_ENABLE_DEPRECATION_WARNINGS
1576 #endif
1577         frame->pkt_pos      = pkt->pos;
1578         frame->pkt_duration = pkt->duration;
1579         frame->pkt_size     = pkt->size;
1580
1581         for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
1582             int size;
1583             uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
1584             if (packet_sd) {
1585                 AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
1586                                                                    sd[i].frame,
1587                                                                    size);
1588                 if (!frame_sd)
1589                     return AVERROR(ENOMEM);
1590
1591                 memcpy(frame_sd->data, packet_sd, size);
1592             }
1593         }
1594         add_metadata_from_side_data(pkt, frame);
1595
1596         if (pkt->flags & AV_PKT_FLAG_DISCARD) {
1597             frame->flags |= AV_FRAME_FLAG_DISCARD;
1598         } else {
1599             frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
1600         }
1601     }
1602     frame->reordered_opaque = avctx->reordered_opaque;
1603
1604     if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
1605         frame->color_primaries = avctx->color_primaries;
1606     if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
1607         frame->color_trc = avctx->color_trc;
1608     if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
1609         frame->colorspace = avctx->colorspace;
1610     if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
1611         frame->color_range = avctx->color_range;
1612     if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
1613         frame->chroma_location = avctx->chroma_sample_location;
1614
1615     switch (avctx->codec->type) {
1616     case AVMEDIA_TYPE_VIDEO:
1617         frame->format              = avctx->pix_fmt;
1618         if (!frame->sample_aspect_ratio.num)
1619             frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
1620
1621         if (frame->width && frame->height &&
1622             av_image_check_sar(frame->width, frame->height,
1623                                frame->sample_aspect_ratio) < 0) {
1624             av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
1625                    frame->sample_aspect_ratio.num,
1626                    frame->sample_aspect_ratio.den);
1627             frame->sample_aspect_ratio = (AVRational){ 0, 1 };
1628         }
1629
1630         break;
1631     case AVMEDIA_TYPE_AUDIO:
1632         if (!frame->sample_rate)
1633             frame->sample_rate    = avctx->sample_rate;
1634         if (frame->format < 0)
1635             frame->format         = avctx->sample_fmt;
1636         if (!frame->channel_layout) {
1637             if (avctx->channel_layout) {
1638                  if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
1639                      avctx->channels) {
1640                      av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
1641                             "configuration.\n");
1642                      return AVERROR(EINVAL);
1643                  }
1644
1645                 frame->channel_layout = avctx->channel_layout;
1646             } else {
1647                 if (avctx->channels > FF_SANE_NB_CHANNELS) {
1648                     av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
1649                            avctx->channels);
1650                     return AVERROR(ENOSYS);
1651                 }
1652             }
1653         }
1654         frame->channels = avctx->channels;
1655         break;
1656     }
1657     return 0;
1658 }
1659
1660 int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
1661 {
1662     return ff_init_buffer_info(avctx, frame);
1663 }
1664
1665 static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
1666 {
1667     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1668         int i;
1669         int num_planes = av_pix_fmt_count_planes(frame->format);
1670         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
1671         int flags = desc ? desc->flags : 0;
1672         if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
1673             num_planes = 2;
1674         for (i = 0; i < num_planes; i++) {
1675             av_assert0(frame->data[i]);
1676         }
1677         // For now do not enforce anything for palette of pseudopal formats
1678         if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PSEUDOPAL))
1679             num_planes = 2;
1680         // For formats without data like hwaccel allow unused pointers to be non-NULL.
1681         for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
1682             if (frame->data[i])
1683                 av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
1684             frame->data[i] = NULL;
1685         }
1686     }
1687 }
1688
1689 static int get_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
1690 {
1691     const AVHWAccel *hwaccel = avctx->hwaccel;
1692     int override_dimensions = 1;
1693     int ret;
1694
1695     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
1696         if ((ret = av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) {
1697             av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
1698             return AVERROR(EINVAL);
1699         }
1700
1701         if (frame->width <= 0 || frame->height <= 0) {
1702             frame->width  = FFMAX(avctx->width,  AV_CEIL_RSHIFT(avctx->coded_width,  avctx->lowres));
1703             frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
1704             override_dimensions = 0;
1705         }
1706
1707         if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
1708             av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
1709             return AVERROR(EINVAL);
1710         }
1711     }
1712     ret = ff_decode_frame_props(avctx, frame);
1713     if (ret < 0)
1714         return ret;
1715
1716     if (hwaccel) {
1717         if (hwaccel->alloc_frame) {
1718             ret = hwaccel->alloc_frame(avctx, frame);
1719             goto end;
1720         }
1721     } else
1722         avctx->sw_pix_fmt = avctx->pix_fmt;
1723
1724     ret = avctx->get_buffer2(avctx, frame, flags);
1725     if (ret >= 0)
1726         validate_avframe_allocation(avctx, frame);
1727
1728 end:
1729     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
1730         !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
1731         frame->width  = avctx->width;
1732         frame->height = avctx->height;
1733     }
1734
1735     return ret;
1736 }
1737
1738 int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
1739 {
1740     int ret = get_buffer_internal(avctx, frame, flags);
1741     if (ret < 0) {
1742         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1743         frame->width = frame->height = 0;
1744     }
1745     return ret;
1746 }
1747
1748 static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame)
1749 {
1750     AVFrame *tmp;
1751     int ret;
1752
1753     av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
1754
1755     if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
1756         av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
1757                frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
1758         av_frame_unref(frame);
1759     }
1760
1761     ff_init_buffer_info(avctx, frame);
1762
1763     if (!frame->data[0])
1764         return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1765
1766     if (av_frame_is_writable(frame))
1767         return ff_decode_frame_props(avctx, frame);
1768
1769     tmp = av_frame_alloc();
1770     if (!tmp)
1771         return AVERROR(ENOMEM);
1772
1773     av_frame_move_ref(tmp, frame);
1774
1775     ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
1776     if (ret < 0) {
1777         av_frame_free(&tmp);
1778         return ret;
1779     }
1780
1781     av_frame_copy(frame, tmp);
1782     av_frame_free(&tmp);
1783
1784     return 0;
1785 }
1786
1787 int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
1788 {
1789     int ret = reget_buffer_internal(avctx, frame);
1790     if (ret < 0)
1791         av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
1792     return ret;
1793 }
1794
1795 void avcodec_flush_buffers(AVCodecContext *avctx)
1796 {
1797     avctx->internal->draining      = 0;
1798     avctx->internal->draining_done = 0;
1799     avctx->internal->nb_draining_errors = 0;
1800     av_frame_unref(avctx->internal->buffer_frame);
1801     av_frame_unref(avctx->internal->compat_decode_frame);
1802     av_packet_unref(avctx->internal->buffer_pkt);
1803     avctx->internal->buffer_pkt_valid = 0;
1804
1805     av_packet_unref(avctx->internal->ds.in_pkt);
1806
1807     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1808         ff_thread_flush(avctx);
1809     else if (avctx->codec->flush)
1810         avctx->codec->flush(avctx);
1811
1812     avctx->pts_correction_last_pts =
1813     avctx->pts_correction_last_dts = INT64_MIN;
1814
1815     ff_decode_bsfs_uninit(avctx);
1816
1817     if (!avctx->refcounted_frames)
1818         av_frame_unref(avctx->internal->to_free);
1819 }
1820
1821 void ff_decode_bsfs_uninit(AVCodecContext *avctx)
1822 {
1823     DecodeFilterContext *s = &avctx->internal->filter;
1824     int i;
1825
1826     for (i = 0; i < s->nb_bsfs; i++)
1827         av_bsf_free(&s->bsfs[i]);
1828     av_freep(&s->bsfs);
1829     s->nb_bsfs = 0;
1830 }