]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
h264: Fix parameters to ff_er_add_slice() call
[ffmpeg] / libavcodec / utils.c
1 /*
2  * utils for libavcodec
3  * Copyright (c) 2001 Fabrice Bellard
4  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * This file is part of Libav.
7  *
8  * Libav is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * Libav is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * utils.
26  */
27
28 #include "libavutil/avassert.h"
29 #include "libavutil/avstring.h"
30 #include "libavutil/channel_layout.h"
31 #include "libavutil/crc.h"
32 #include "libavutil/mathematics.h"
33 #include "libavutil/pixdesc.h"
34 #include "libavutil/imgutils.h"
35 #include "libavutil/samplefmt.h"
36 #include "libavutil/dict.h"
37 #include "avcodec.h"
38 #include "dsputil.h"
39 #include "libavutil/opt.h"
40 #include "thread.h"
41 #include "internal.h"
42 #include "bytestream.h"
43 #include <stdlib.h>
44 #include <stdarg.h>
45 #include <limits.h>
46 #include <float.h>
47
48 static int volatile entangled_thread_counter = 0;
49 static int (*ff_lockmgr_cb)(void **mutex, enum AVLockOp op);
50 static void *codec_mutex;
51 static void *avformat_mutex;
52
53 void *av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
54 {
55     if (min_size < *size)
56         return ptr;
57
58     min_size = FFMAX(17 * min_size / 16 + 32, min_size);
59
60     ptr = av_realloc(ptr, min_size);
61     /* we could set this to the unmodified min_size but this is safer
62      * if the user lost the ptr and uses NULL now
63      */
64     if (!ptr)
65         min_size = 0;
66
67     *size = min_size;
68
69     return ptr;
70 }
71
72 void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size)
73 {
74     void **p = ptr;
75     if (min_size < *size)
76         return;
77     min_size = FFMAX(17 * min_size / 16 + 32, min_size);
78     av_free(*p);
79     *p = av_malloc(min_size);
80     if (!*p)
81         min_size = 0;
82     *size = min_size;
83 }
84
85 void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size)
86 {
87     void **p = ptr;
88     if (min_size > SIZE_MAX - FF_INPUT_BUFFER_PADDING_SIZE) {
89         av_freep(p);
90         *size = 0;
91         return;
92     }
93     av_fast_malloc(p, size, min_size + FF_INPUT_BUFFER_PADDING_SIZE);
94     if (*size)
95         memset((uint8_t *)*p + min_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
96 }
97
98 /* encoder management */
99 static AVCodec *first_avcodec = NULL;
100
101 AVCodec *av_codec_next(const AVCodec *c)
102 {
103     if (c)
104         return c->next;
105     else
106         return first_avcodec;
107 }
108
109 static void avcodec_init(void)
110 {
111     static int initialized = 0;
112
113     if (initialized != 0)
114         return;
115     initialized = 1;
116
117     ff_dsputil_static_init();
118 }
119
120 int av_codec_is_encoder(const AVCodec *codec)
121 {
122     return codec && (codec->encode_sub || codec->encode2);
123 }
124
125 int av_codec_is_decoder(const AVCodec *codec)
126 {
127     return codec && codec->decode;
128 }
129
130 void avcodec_register(AVCodec *codec)
131 {
132     AVCodec **p;
133     avcodec_init();
134     p = &first_avcodec;
135     while (*p != NULL)
136         p = &(*p)->next;
137     *p          = codec;
138     codec->next = NULL;
139
140     if (codec->init_static_data)
141         codec->init_static_data(codec);
142 }
143
144 unsigned avcodec_get_edge_width(void)
145 {
146     return EDGE_WIDTH;
147 }
148
149 void avcodec_set_dimensions(AVCodecContext *s, int width, int height)
150 {
151     s->coded_width  = width;
152     s->coded_height = height;
153     s->width        = width;
154     s->height       = height;
155 }
156
157 #define INTERNAL_BUFFER_SIZE (32 + 1)
158
159 void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
160                                int linesize_align[AV_NUM_DATA_POINTERS])
161 {
162     int i;
163     int w_align = 1;
164     int h_align = 1;
165
166     switch (s->pix_fmt) {
167     case AV_PIX_FMT_YUV420P:
168     case AV_PIX_FMT_YUYV422:
169     case AV_PIX_FMT_UYVY422:
170     case AV_PIX_FMT_YUV422P:
171     case AV_PIX_FMT_YUV440P:
172     case AV_PIX_FMT_YUV444P:
173     case AV_PIX_FMT_GBRP:
174     case AV_PIX_FMT_GRAY8:
175     case AV_PIX_FMT_GRAY16BE:
176     case AV_PIX_FMT_GRAY16LE:
177     case AV_PIX_FMT_YUVJ420P:
178     case AV_PIX_FMT_YUVJ422P:
179     case AV_PIX_FMT_YUVJ440P:
180     case AV_PIX_FMT_YUVJ444P:
181     case AV_PIX_FMT_YUVA420P:
182     case AV_PIX_FMT_YUVA422P:
183     case AV_PIX_FMT_YUVA444P:
184     case AV_PIX_FMT_YUV420P9LE:
185     case AV_PIX_FMT_YUV420P9BE:
186     case AV_PIX_FMT_YUV420P10LE:
187     case AV_PIX_FMT_YUV420P10BE:
188     case AV_PIX_FMT_YUV422P9LE:
189     case AV_PIX_FMT_YUV422P9BE:
190     case AV_PIX_FMT_YUV422P10LE:
191     case AV_PIX_FMT_YUV422P10BE:
192     case AV_PIX_FMT_YUV444P9LE:
193     case AV_PIX_FMT_YUV444P9BE:
194     case AV_PIX_FMT_YUV444P10LE:
195     case AV_PIX_FMT_YUV444P10BE:
196     case AV_PIX_FMT_GBRP9LE:
197     case AV_PIX_FMT_GBRP9BE:
198     case AV_PIX_FMT_GBRP10LE:
199     case AV_PIX_FMT_GBRP10BE:
200         w_align = 16; //FIXME assume 16 pixel per macroblock
201         h_align = 16 * 2; // interlaced needs 2 macroblocks height
202         break;
203     case AV_PIX_FMT_YUV411P:
204     case AV_PIX_FMT_UYYVYY411:
205         w_align = 32;
206         h_align = 8;
207         break;
208     case AV_PIX_FMT_YUV410P:
209         if (s->codec_id == AV_CODEC_ID_SVQ1) {
210             w_align = 64;
211             h_align = 64;
212         }
213     case AV_PIX_FMT_RGB555:
214         if (s->codec_id == AV_CODEC_ID_RPZA) {
215             w_align = 4;
216             h_align = 4;
217         }
218     case AV_PIX_FMT_PAL8:
219     case AV_PIX_FMT_BGR8:
220     case AV_PIX_FMT_RGB8:
221         if (s->codec_id == AV_CODEC_ID_SMC) {
222             w_align = 4;
223             h_align = 4;
224         }
225         break;
226     case AV_PIX_FMT_BGR24:
227         if ((s->codec_id == AV_CODEC_ID_MSZH) ||
228             (s->codec_id == AV_CODEC_ID_ZLIB)) {
229             w_align = 4;
230             h_align = 4;
231         }
232         break;
233     default:
234         w_align = 1;
235         h_align = 1;
236         break;
237     }
238
239     *width  = FFALIGN(*width, w_align);
240     *height = FFALIGN(*height, h_align);
241     if (s->codec_id == AV_CODEC_ID_H264)
242         // some of the optimized chroma MC reads one line too much
243         *height += 2;
244
245     for (i = 0; i < 4; i++)
246         linesize_align[i] = STRIDE_ALIGN;
247 }
248
249 void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height)
250 {
251     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
252     int chroma_shift = desc->log2_chroma_w;
253     int linesize_align[AV_NUM_DATA_POINTERS];
254     int align;
255
256     avcodec_align_dimensions2(s, width, height, linesize_align);
257     align               = FFMAX(linesize_align[0], linesize_align[3]);
258     linesize_align[1] <<= chroma_shift;
259     linesize_align[2] <<= chroma_shift;
260     align               = FFMAX3(align, linesize_align[1], linesize_align[2]);
261     *width              = FFALIGN(*width, align);
262 }
263
264 int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels,
265                              enum AVSampleFormat sample_fmt, const uint8_t *buf,
266                              int buf_size, int align)
267 {
268     int ch, planar, needed_size, ret = 0;
269
270     needed_size = av_samples_get_buffer_size(NULL, nb_channels,
271                                              frame->nb_samples, sample_fmt,
272                                              align);
273     if (buf_size < needed_size)
274         return AVERROR(EINVAL);
275
276     planar = av_sample_fmt_is_planar(sample_fmt);
277     if (planar && nb_channels > AV_NUM_DATA_POINTERS) {
278         if (!(frame->extended_data = av_mallocz(nb_channels *
279                                                 sizeof(*frame->extended_data))))
280             return AVERROR(ENOMEM);
281     } else {
282         frame->extended_data = frame->data;
283     }
284
285     if ((ret = av_samples_fill_arrays(frame->extended_data, &frame->linesize[0],
286                                       buf, nb_channels, frame->nb_samples,
287                                       sample_fmt, align)) < 0) {
288         if (frame->extended_data != frame->data)
289             av_free(frame->extended_data);
290         return ret;
291     }
292     if (frame->extended_data != frame->data) {
293         for (ch = 0; ch < AV_NUM_DATA_POINTERS; ch++)
294             frame->data[ch] = frame->extended_data[ch];
295     }
296
297     return ret;
298 }
299
300 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
301 {
302     AVCodecInternal *avci = avctx->internal;
303     InternalBuffer *buf;
304     int buf_size, ret;
305
306     buf_size = av_samples_get_buffer_size(NULL, avctx->channels,
307                                           frame->nb_samples, avctx->sample_fmt,
308                                           0);
309     if (buf_size < 0)
310         return AVERROR(EINVAL);
311
312     /* allocate InternalBuffer if needed */
313     if (!avci->buffer) {
314         avci->buffer = av_mallocz(sizeof(InternalBuffer));
315         if (!avci->buffer)
316             return AVERROR(ENOMEM);
317     }
318     buf = avci->buffer;
319
320     /* if there is a previously-used internal buffer, check its size and
321      * channel count to see if we can reuse it */
322     if (buf->extended_data) {
323         /* if current buffer is too small, free it */
324         if (buf->extended_data[0] && buf_size > buf->audio_data_size) {
325             av_free(buf->extended_data[0]);
326             if (buf->extended_data != buf->data)
327                 av_free(buf->extended_data);
328             buf->extended_data = NULL;
329             buf->data[0]       = NULL;
330         }
331         /* if number of channels has changed, reset and/or free extended data
332          * pointers but leave data buffer in buf->data[0] for reuse */
333         if (buf->nb_channels != avctx->channels) {
334             if (buf->extended_data != buf->data)
335                 av_free(buf->extended_data);
336             buf->extended_data = NULL;
337         }
338     }
339
340     /* if there is no previous buffer or the previous buffer cannot be used
341      * as-is, allocate a new buffer and/or rearrange the channel pointers */
342     if (!buf->extended_data) {
343         if (!buf->data[0]) {
344             if (!(buf->data[0] = av_mallocz(buf_size)))
345                 return AVERROR(ENOMEM);
346             buf->audio_data_size = buf_size;
347         }
348         if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
349                                             avctx->sample_fmt, buf->data[0],
350                                             buf->audio_data_size, 0)))
351             return ret;
352
353         if (frame->extended_data == frame->data)
354             buf->extended_data = buf->data;
355         else
356             buf->extended_data = frame->extended_data;
357         memcpy(buf->data, frame->data, sizeof(frame->data));
358         buf->linesize[0] = frame->linesize[0];
359         buf->nb_channels = avctx->channels;
360     } else {
361         /* copy InternalBuffer info to the AVFrame */
362         frame->extended_data = buf->extended_data;
363         frame->linesize[0]   = buf->linesize[0];
364         memcpy(frame->data, buf->data, sizeof(frame->data));
365     }
366
367     frame->type = FF_BUFFER_TYPE_INTERNAL;
368
369     if (avctx->pkt)
370         frame->pkt_pts = avctx->pkt->pts;
371     else
372         frame->pkt_pts = AV_NOPTS_VALUE;
373     frame->reordered_opaque = avctx->reordered_opaque;
374
375     frame->sample_rate    = avctx->sample_rate;
376     frame->format         = avctx->sample_fmt;
377     frame->channel_layout = avctx->channel_layout;
378
379     if (avctx->debug & FF_DEBUG_BUFFERS)
380         av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p, "
381                                     "internal audio buffer used\n", frame);
382
383     return 0;
384 }
385
386 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
387 {
388     int i;
389     int w = s->width;
390     int h = s->height;
391     InternalBuffer *buf;
392     AVCodecInternal *avci = s->internal;
393
394     if (pic->data[0] != NULL) {
395         av_log(s, AV_LOG_ERROR, "pic->data[0]!=NULL in avcodec_default_get_buffer\n");
396         return -1;
397     }
398     if (avci->buffer_count >= INTERNAL_BUFFER_SIZE) {
399         av_log(s, AV_LOG_ERROR, "buffer_count overflow (missing release_buffer?)\n");
400         return -1;
401     }
402
403     if (av_image_check_size(w, h, 0, s))
404         return -1;
405
406     if (!avci->buffer) {
407         avci->buffer = av_mallocz((INTERNAL_BUFFER_SIZE + 1) *
408                                   sizeof(InternalBuffer));
409     }
410
411     buf = &avci->buffer[avci->buffer_count];
412
413     if (buf->base[0] && (buf->width != w || buf->height != h || buf->pix_fmt != s->pix_fmt)) {
414         for (i = 0; i < AV_NUM_DATA_POINTERS; i++) {
415             av_freep(&buf->base[i]);
416             buf->data[i] = NULL;
417         }
418     }
419
420     if (!buf->base[0]) {
421         int h_chroma_shift, v_chroma_shift;
422         int size[4] = { 0 };
423         int tmpsize;
424         int unaligned;
425         AVPicture picture;
426         int stride_align[AV_NUM_DATA_POINTERS];
427         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
428         const int pixel_size = desc->comp[0].step_minus1 + 1;
429
430         av_pix_fmt_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift,
431                                          &v_chroma_shift);
432
433         avcodec_align_dimensions2(s, &w, &h, stride_align);
434
435         if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
436             w += EDGE_WIDTH * 2;
437             h += EDGE_WIDTH * 2;
438         }
439
440         do {
441             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
442             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
443             av_image_fill_linesizes(picture.linesize, s->pix_fmt, w);
444             // increase alignment of w for next try (rhs gives the lowest bit set in w)
445             w += w & ~(w - 1);
446
447             unaligned = 0;
448             for (i = 0; i < 4; i++)
449                 unaligned |= picture.linesize[i] % stride_align[i];
450         } while (unaligned);
451
452         tmpsize = av_image_fill_pointers(picture.data, s->pix_fmt, h, NULL, picture.linesize);
453         if (tmpsize < 0)
454             return -1;
455
456         for (i = 0; i < 3 && picture.data[i + 1]; i++)
457             size[i] = picture.data[i + 1] - picture.data[i];
458         size[i] = tmpsize - (picture.data[i] - picture.data[0]);
459
460         memset(buf->base, 0, sizeof(buf->base));
461         memset(buf->data, 0, sizeof(buf->data));
462
463         for (i = 0; i < 4 && size[i]; i++) {
464             const int h_shift = i == 0 ? 0 : h_chroma_shift;
465             const int v_shift = i == 0 ? 0 : v_chroma_shift;
466
467             buf->linesize[i] = picture.linesize[i];
468
469             buf->base[i] = av_malloc(size[i] + 16); //FIXME 16
470             if (buf->base[i] == NULL)
471                 return -1;
472             memset(buf->base[i], 128, size[i]);
473
474             // no edge if EDGE EMU or not planar YUV
475             if ((s->flags & CODEC_FLAG_EMU_EDGE) || !size[2])
476                 buf->data[i] = buf->base[i];
477             else
478                 buf->data[i] = buf->base[i] + FFALIGN((buf->linesize[i] * EDGE_WIDTH >> v_shift) + (pixel_size * EDGE_WIDTH >> h_shift), stride_align[i]);
479         }
480         for (; i < AV_NUM_DATA_POINTERS; i++) {
481             buf->base[i]     = buf->data[i] = NULL;
482             buf->linesize[i] = 0;
483         }
484         if (size[1] && !size[2])
485             avpriv_set_systematic_pal2((uint32_t *)buf->data[1], s->pix_fmt);
486         buf->width   = s->width;
487         buf->height  = s->height;
488         buf->pix_fmt = s->pix_fmt;
489     }
490     pic->type = FF_BUFFER_TYPE_INTERNAL;
491
492     for (i = 0; i < AV_NUM_DATA_POINTERS; i++) {
493         pic->base[i]     = buf->base[i];
494         pic->data[i]     = buf->data[i];
495         pic->linesize[i] = buf->linesize[i];
496     }
497     pic->extended_data = pic->data;
498     avci->buffer_count++;
499     pic->width               = buf->width;
500     pic->height              = buf->height;
501     pic->format              = buf->pix_fmt;
502     pic->sample_aspect_ratio = s->sample_aspect_ratio;
503
504     if (s->pkt)
505         pic->pkt_pts = s->pkt->pts;
506     else
507         pic->pkt_pts = AV_NOPTS_VALUE;
508     pic->reordered_opaque = s->reordered_opaque;
509
510     if (s->debug & FF_DEBUG_BUFFERS)
511         av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p, %d "
512                                 "buffers used\n", pic, avci->buffer_count);
513
514     return 0;
515 }
516
517 int avcodec_default_get_buffer(AVCodecContext *avctx, AVFrame *frame)
518 {
519     switch (avctx->codec_type) {
520     case AVMEDIA_TYPE_VIDEO:
521         return video_get_buffer(avctx, frame);
522     case AVMEDIA_TYPE_AUDIO:
523         return audio_get_buffer(avctx, frame);
524     default:
525         return -1;
526     }
527 }
528
529 void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic)
530 {
531     int i;
532     InternalBuffer *buf, *last;
533     AVCodecInternal *avci = s->internal;
534
535     assert(s->codec_type == AVMEDIA_TYPE_VIDEO);
536
537     assert(pic->type == FF_BUFFER_TYPE_INTERNAL);
538     assert(avci->buffer_count);
539
540     if (avci->buffer) {
541         buf = NULL; /* avoids warning */
542         for (i = 0; i < avci->buffer_count; i++) { //just 3-5 checks so is not worth to optimize
543             buf = &avci->buffer[i];
544             if (buf->data[0] == pic->data[0])
545                 break;
546         }
547         assert(i < avci->buffer_count);
548         avci->buffer_count--;
549         last = &avci->buffer[avci->buffer_count];
550
551         if (buf != last)
552             FFSWAP(InternalBuffer, *buf, *last);
553     }
554
555     for (i = 0; i < AV_NUM_DATA_POINTERS; i++)
556         pic->data[i] = NULL;
557 //        pic->base[i]=NULL;
558
559     if (s->debug & FF_DEBUG_BUFFERS)
560         av_log(s, AV_LOG_DEBUG, "default_release_buffer called on pic %p, %d "
561                                 "buffers used\n", pic, avci->buffer_count);
562 }
563
564 int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic)
565 {
566     AVFrame temp_pic;
567     int i;
568
569     assert(s->codec_type == AVMEDIA_TYPE_VIDEO);
570
571     /* If no picture return a new buffer */
572     if (pic->data[0] == NULL) {
573         /* We will copy from buffer, so must be readable */
574         pic->buffer_hints |= FF_BUFFER_HINTS_READABLE;
575         return s->get_buffer(s, pic);
576     }
577
578     assert(s->pix_fmt == pic->format);
579
580     /* If internal buffer type return the same buffer */
581     if (pic->type == FF_BUFFER_TYPE_INTERNAL) {
582         if (s->pkt)
583             pic->pkt_pts = s->pkt->pts;
584         else
585             pic->pkt_pts = AV_NOPTS_VALUE;
586         pic->reordered_opaque = s->reordered_opaque;
587         return 0;
588     }
589
590     /*
591      * Not internal type and reget_buffer not overridden, emulate cr buffer
592      */
593     temp_pic = *pic;
594     for (i = 0; i < AV_NUM_DATA_POINTERS; i++)
595         pic->data[i] = pic->base[i] = NULL;
596     pic->opaque = NULL;
597     /* Allocate new frame */
598     if (s->get_buffer(s, pic))
599         return -1;
600     /* Copy image data from old buffer to new buffer */
601     av_picture_copy((AVPicture *)pic, (AVPicture *)&temp_pic, s->pix_fmt, s->width,
602                     s->height);
603     s->release_buffer(s, &temp_pic); // Release old frame
604     return 0;
605 }
606
607 int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2), void *arg, int *ret, int count, int size)
608 {
609     int i;
610
611     for (i = 0; i < count; i++) {
612         int r = func(c, (char *)arg + i * size);
613         if (ret)
614             ret[i] = r;
615     }
616     return 0;
617 }
618
619 int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr), void *arg, int *ret, int count)
620 {
621     int i;
622
623     for (i = 0; i < count; i++) {
624         int r = func(c, arg, i, 0);
625         if (ret)
626             ret[i] = r;
627     }
628     return 0;
629 }
630
631 static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
632 {
633     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
634     return desc->flags & PIX_FMT_HWACCEL;
635 }
636
637 enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
638 {
639     while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
640         ++fmt;
641     return fmt[0];
642 }
643
644 void avcodec_get_frame_defaults(AVFrame *frame)
645 {
646     if (frame->extended_data != frame->data)
647         av_freep(&frame->extended_data);
648
649     memset(frame, 0, sizeof(AVFrame));
650
651     frame->pts                 = AV_NOPTS_VALUE;
652     frame->key_frame           = 1;
653     frame->sample_aspect_ratio = (AVRational) {0, 1 };
654     frame->format              = -1; /* unknown */
655     frame->extended_data       = frame->data;
656 }
657
658 AVFrame *avcodec_alloc_frame(void)
659 {
660     AVFrame *frame = av_mallocz(sizeof(AVFrame));
661
662     if (frame == NULL)
663         return NULL;
664
665     avcodec_get_frame_defaults(frame);
666
667     return frame;
668 }
669
670 void avcodec_free_frame(AVFrame **frame)
671 {
672     AVFrame *f;
673
674     if (!frame || !*frame)
675         return;
676
677     f = *frame;
678
679     if (f->extended_data != f->data)
680         av_freep(&f->extended_data);
681
682     av_freep(frame);
683 }
684
685 int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
686 {
687     int ret = 0;
688     AVDictionary *tmp = NULL;
689
690     if (avcodec_is_open(avctx))
691         return 0;
692
693     if ((!codec && !avctx->codec)) {
694         av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2().\n");
695         return AVERROR(EINVAL);
696     }
697     if ((codec && avctx->codec && codec != avctx->codec)) {
698         av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
699                                     "but %s passed to avcodec_open2().\n", avctx->codec->name, codec->name);
700         return AVERROR(EINVAL);
701     }
702     if (!codec)
703         codec = avctx->codec;
704
705     if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
706         return AVERROR(EINVAL);
707
708     if (options)
709         av_dict_copy(&tmp, *options, 0);
710
711     /* If there is a user-supplied mutex locking routine, call it. */
712     if (ff_lockmgr_cb) {
713         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
714             return -1;
715     }
716
717     entangled_thread_counter++;
718     if (entangled_thread_counter != 1) {
719         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
720         ret = -1;
721         goto end;
722     }
723
724     avctx->internal = av_mallocz(sizeof(AVCodecInternal));
725     if (!avctx->internal) {
726         ret = AVERROR(ENOMEM);
727         goto end;
728     }
729
730     if (codec->priv_data_size > 0) {
731         if (!avctx->priv_data) {
732             avctx->priv_data = av_mallocz(codec->priv_data_size);
733             if (!avctx->priv_data) {
734                 ret = AVERROR(ENOMEM);
735                 goto end;
736             }
737             if (codec->priv_class) {
738                 *(const AVClass **)avctx->priv_data = codec->priv_class;
739                 av_opt_set_defaults(avctx->priv_data);
740             }
741         }
742         if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
743             goto free_and_end;
744     } else {
745         avctx->priv_data = NULL;
746     }
747     if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
748         goto free_and_end;
749
750     if (avctx->coded_width && avctx->coded_height)
751         avcodec_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
752     else if (avctx->width && avctx->height)
753         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
754
755     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
756         && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
757            || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {
758         av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");
759         avcodec_set_dimensions(avctx, 0, 0);
760     }
761
762     /* if the decoder init function was already called previously,
763      * free the already allocated subtitle_header before overwriting it */
764     if (av_codec_is_decoder(codec))
765         av_freep(&avctx->subtitle_header);
766
767     if (avctx->channels > FF_SANE_NB_CHANNELS) {
768         ret = AVERROR(EINVAL);
769         goto free_and_end;
770     }
771
772     avctx->codec = codec;
773     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
774         avctx->codec_id == AV_CODEC_ID_NONE) {
775         avctx->codec_type = codec->type;
776         avctx->codec_id   = codec->id;
777     }
778     if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
779                                          && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
780         av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");
781         ret = AVERROR(EINVAL);
782         goto free_and_end;
783     }
784     avctx->frame_number = 0;
785
786     if (avctx->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
787         avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
788         ret = AVERROR_EXPERIMENTAL;
789         goto free_and_end;
790     }
791
792     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
793         (!avctx->time_base.num || !avctx->time_base.den)) {
794         avctx->time_base.num = 1;
795         avctx->time_base.den = avctx->sample_rate;
796     }
797
798     if (HAVE_THREADS && !avctx->thread_opaque) {
799         ret = ff_thread_init(avctx);
800         if (ret < 0) {
801             goto free_and_end;
802         }
803     }
804     if (!HAVE_THREADS && !(codec->capabilities & CODEC_CAP_AUTO_THREADS))
805         avctx->thread_count = 1;
806
807     if (av_codec_is_encoder(avctx->codec)) {
808         int i;
809         if (avctx->codec->sample_fmts) {
810             for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
811                 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
812                     break;
813                 if (avctx->channels == 1 &&
814                     av_get_planar_sample_fmt(avctx->sample_fmt) ==
815                     av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) {
816                     avctx->sample_fmt = avctx->codec->sample_fmts[i];
817                     break;
818                 }
819             }
820             if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
821                 av_log(avctx, AV_LOG_ERROR, "Specified sample_fmt is not supported.\n");
822                 ret = AVERROR(EINVAL);
823                 goto free_and_end;
824             }
825         }
826         if (avctx->codec->pix_fmts) {
827             for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++)
828                 if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
829                     break;
830             if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE) {
831                 av_log(avctx, AV_LOG_ERROR, "Specified pix_fmt is not supported\n");
832                 ret = AVERROR(EINVAL);
833                 goto free_and_end;
834             }
835         }
836         if (avctx->codec->supported_samplerates) {
837             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
838                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
839                     break;
840             if (avctx->codec->supported_samplerates[i] == 0) {
841                 av_log(avctx, AV_LOG_ERROR, "Specified sample_rate is not supported\n");
842                 ret = AVERROR(EINVAL);
843                 goto free_and_end;
844             }
845         }
846         if (avctx->codec->channel_layouts) {
847             if (!avctx->channel_layout) {
848                 av_log(avctx, AV_LOG_WARNING, "channel_layout not specified\n");
849             } else {
850                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
851                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
852                         break;
853                 if (avctx->codec->channel_layouts[i] == 0) {
854                     av_log(avctx, AV_LOG_ERROR, "Specified channel_layout is not supported\n");
855                     ret = AVERROR(EINVAL);
856                     goto free_and_end;
857                 }
858             }
859         }
860         if (avctx->channel_layout && avctx->channels) {
861             if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {
862                 av_log(avctx, AV_LOG_ERROR, "channel layout does not match number of channels\n");
863                 ret = AVERROR(EINVAL);
864                 goto free_and_end;
865             }
866         } else if (avctx->channel_layout) {
867             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
868         }
869     }
870
871     if (avctx->codec->init && !(avctx->active_thread_type & FF_THREAD_FRAME)) {
872         ret = avctx->codec->init(avctx);
873         if (ret < 0) {
874             goto free_and_end;
875         }
876     }
877
878     if (av_codec_is_decoder(avctx->codec)) {
879         /* validate channel layout from the decoder */
880         if (avctx->channel_layout) {
881             int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
882             if (!avctx->channels)
883                 avctx->channels = channels;
884             else if (channels != avctx->channels) {
885                 av_log(avctx, AV_LOG_WARNING,
886                        "channel layout does not match number of channels\n");
887                 avctx->channel_layout = 0;
888             }
889         }
890         if (avctx->channels && avctx->channels < 0 ||
891             avctx->channels > FF_SANE_NB_CHANNELS) {
892             ret = AVERROR(EINVAL);
893             goto free_and_end;
894         }
895     }
896 end:
897     entangled_thread_counter--;
898
899     /* Release any user-supplied mutex. */
900     if (ff_lockmgr_cb) {
901         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
902     }
903     if (options) {
904         av_dict_free(options);
905         *options = tmp;
906     }
907
908     return ret;
909 free_and_end:
910     av_dict_free(&tmp);
911     av_freep(&avctx->priv_data);
912     av_freep(&avctx->internal);
913     avctx->codec = NULL;
914     goto end;
915 }
916
917 int ff_alloc_packet(AVPacket *avpkt, int size)
918 {
919     if (size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE)
920         return AVERROR(EINVAL);
921
922     if (avpkt->data) {
923         void *destruct = avpkt->destruct;
924
925         if (avpkt->size < size)
926             return AVERROR(EINVAL);
927
928         av_init_packet(avpkt);
929         avpkt->destruct = destruct;
930         avpkt->size     = size;
931         return 0;
932     } else {
933         return av_new_packet(avpkt, size);
934     }
935 }
936
937 /**
938  * Pad last frame with silence.
939  */
940 static int pad_last_frame(AVCodecContext *s, AVFrame **dst, const AVFrame *src)
941 {
942     AVFrame *frame = NULL;
943     uint8_t *buf   = NULL;
944     int ret;
945
946     if (!(frame = avcodec_alloc_frame()))
947         return AVERROR(ENOMEM);
948     *frame = *src;
949
950     if ((ret = av_samples_get_buffer_size(&frame->linesize[0], s->channels,
951                                           s->frame_size, s->sample_fmt, 0)) < 0)
952         goto fail;
953
954     if (!(buf = av_malloc(ret))) {
955         ret = AVERROR(ENOMEM);
956         goto fail;
957     }
958
959     frame->nb_samples = s->frame_size;
960     if ((ret = avcodec_fill_audio_frame(frame, s->channels, s->sample_fmt,
961                                         buf, ret, 0)) < 0)
962         goto fail;
963     if ((ret = av_samples_copy(frame->extended_data, src->extended_data, 0, 0,
964                                src->nb_samples, s->channels, s->sample_fmt)) < 0)
965         goto fail;
966     if ((ret = av_samples_set_silence(frame->extended_data, src->nb_samples,
967                                       frame->nb_samples - src->nb_samples,
968                                       s->channels, s->sample_fmt)) < 0)
969         goto fail;
970
971     *dst = frame;
972
973     return 0;
974
975 fail:
976     if (frame->extended_data != frame->data)
977         av_freep(&frame->extended_data);
978     av_freep(&buf);
979     av_freep(&frame);
980     return ret;
981 }
982
983 int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
984                                               AVPacket *avpkt,
985                                               const AVFrame *frame,
986                                               int *got_packet_ptr)
987 {
988     AVFrame tmp;
989     AVFrame *padded_frame = NULL;
990     int ret;
991     int user_packet = !!avpkt->data;
992
993     *got_packet_ptr = 0;
994
995     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
996         av_free_packet(avpkt);
997         av_init_packet(avpkt);
998         return 0;
999     }
1000
1001     /* ensure that extended_data is properly set */
1002     if (frame && !frame->extended_data) {
1003         if (av_sample_fmt_is_planar(avctx->sample_fmt) &&
1004             avctx->channels > AV_NUM_DATA_POINTERS) {
1005             av_log(avctx, AV_LOG_ERROR, "Encoding to a planar sample format, "
1006                                         "with more than %d channels, but extended_data is not set.\n",
1007                    AV_NUM_DATA_POINTERS);
1008             return AVERROR(EINVAL);
1009         }
1010         av_log(avctx, AV_LOG_WARNING, "extended_data is not set.\n");
1011
1012         tmp = *frame;
1013         tmp.extended_data = tmp.data;
1014         frame = &tmp;
1015     }
1016
1017     /* check for valid frame size */
1018     if (frame) {
1019         if (avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1020             if (frame->nb_samples > avctx->frame_size)
1021                 return AVERROR(EINVAL);
1022         } else if (!(avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
1023             if (frame->nb_samples < avctx->frame_size &&
1024                 !avctx->internal->last_audio_frame) {
1025                 ret = pad_last_frame(avctx, &padded_frame, frame);
1026                 if (ret < 0)
1027                     return ret;
1028
1029                 frame = padded_frame;
1030                 avctx->internal->last_audio_frame = 1;
1031             }
1032
1033             if (frame->nb_samples != avctx->frame_size) {
1034                 ret = AVERROR(EINVAL);
1035                 goto end;
1036             }
1037         }
1038     }
1039
1040     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1041     if (!ret) {
1042         if (*got_packet_ptr) {
1043             if (!(avctx->codec->capabilities & CODEC_CAP_DELAY)) {
1044                 if (avpkt->pts == AV_NOPTS_VALUE)
1045                     avpkt->pts = frame->pts;
1046                 if (!avpkt->duration)
1047                     avpkt->duration = ff_samples_to_time_base(avctx,
1048                                                               frame->nb_samples);
1049             }
1050             avpkt->dts = avpkt->pts;
1051         } else {
1052             avpkt->size = 0;
1053         }
1054
1055         if (!user_packet && avpkt->size) {
1056             uint8_t *new_data = av_realloc(avpkt->data, avpkt->size);
1057             if (new_data)
1058                 avpkt->data = new_data;
1059         }
1060
1061         avctx->frame_number++;
1062     }
1063
1064     if (ret < 0 || !*got_packet_ptr) {
1065         av_free_packet(avpkt);
1066         av_init_packet(avpkt);
1067         goto end;
1068     }
1069
1070     /* NOTE: if we add any audio encoders which output non-keyframe packets,
1071      *       this needs to be moved to the encoders, but for now we can do it
1072      *       here to simplify things */
1073     avpkt->flags |= AV_PKT_FLAG_KEY;
1074
1075 end:
1076     if (padded_frame) {
1077         av_freep(&padded_frame->data[0]);
1078         if (padded_frame->extended_data != padded_frame->data)
1079             av_freep(&padded_frame->extended_data);
1080         av_freep(&padded_frame);
1081     }
1082
1083     return ret;
1084 }
1085
1086 #if FF_API_OLD_ENCODE_AUDIO
1087 int attribute_align_arg avcodec_encode_audio(AVCodecContext *avctx,
1088                                              uint8_t *buf, int buf_size,
1089                                              const short *samples)
1090 {
1091     AVPacket pkt;
1092     AVFrame frame0 = { 0 };
1093     AVFrame *frame;
1094     int ret, samples_size, got_packet;
1095
1096     av_init_packet(&pkt);
1097     pkt.data = buf;
1098     pkt.size = buf_size;
1099
1100     if (samples) {
1101         frame = &frame0;
1102         avcodec_get_frame_defaults(frame);
1103
1104         if (avctx->frame_size) {
1105             frame->nb_samples = avctx->frame_size;
1106         } else {
1107             /* if frame_size is not set, the number of samples must be
1108              * calculated from the buffer size */
1109             int64_t nb_samples;
1110             if (!av_get_bits_per_sample(avctx->codec_id)) {
1111                 av_log(avctx, AV_LOG_ERROR, "avcodec_encode_audio() does not "
1112                                             "support this codec\n");
1113                 return AVERROR(EINVAL);
1114             }
1115             nb_samples = (int64_t)buf_size * 8 /
1116                          (av_get_bits_per_sample(avctx->codec_id) *
1117                           avctx->channels);
1118             if (nb_samples >= INT_MAX)
1119                 return AVERROR(EINVAL);
1120             frame->nb_samples = nb_samples;
1121         }
1122
1123         /* it is assumed that the samples buffer is large enough based on the
1124          * relevant parameters */
1125         samples_size = av_samples_get_buffer_size(NULL, avctx->channels,
1126                                                   frame->nb_samples,
1127                                                   avctx->sample_fmt, 1);
1128         if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
1129                                             avctx->sample_fmt,
1130                                             (const uint8_t *)samples,
1131                                             samples_size, 1)))
1132             return ret;
1133
1134         /* fabricate frame pts from sample count.
1135          * this is needed because the avcodec_encode_audio() API does not have
1136          * a way for the user to provide pts */
1137         frame->pts = ff_samples_to_time_base(avctx,
1138                                              avctx->internal->sample_count);
1139         avctx->internal->sample_count += frame->nb_samples;
1140     } else {
1141         frame = NULL;
1142     }
1143
1144     got_packet = 0;
1145     ret = avcodec_encode_audio2(avctx, &pkt, frame, &got_packet);
1146     if (!ret && got_packet && avctx->coded_frame) {
1147         avctx->coded_frame->pts       = pkt.pts;
1148         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1149     }
1150     /* free any side data since we cannot return it */
1151     if (pkt.side_data_elems > 0) {
1152         int i;
1153         for (i = 0; i < pkt.side_data_elems; i++)
1154             av_free(pkt.side_data[i].data);
1155         av_freep(&pkt.side_data);
1156         pkt.side_data_elems = 0;
1157     }
1158
1159     if (frame && frame->extended_data != frame->data)
1160         av_free(frame->extended_data);
1161
1162     return ret ? ret : pkt.size;
1163 }
1164
1165 #endif
1166
1167 #if FF_API_OLD_ENCODE_VIDEO
1168 int attribute_align_arg avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1169                                              const AVFrame *pict)
1170 {
1171     AVPacket pkt;
1172     int ret, got_packet = 0;
1173
1174     if (buf_size < FF_MIN_BUFFER_SIZE) {
1175         av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
1176         return -1;
1177     }
1178
1179     av_init_packet(&pkt);
1180     pkt.data = buf;
1181     pkt.size = buf_size;
1182
1183     ret = avcodec_encode_video2(avctx, &pkt, pict, &got_packet);
1184     if (!ret && got_packet && avctx->coded_frame) {
1185         avctx->coded_frame->pts       = pkt.pts;
1186         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1187     }
1188
1189     /* free any side data since we cannot return it */
1190     if (pkt.side_data_elems > 0) {
1191         int i;
1192         for (i = 0; i < pkt.side_data_elems; i++)
1193             av_free(pkt.side_data[i].data);
1194         av_freep(&pkt.side_data);
1195         pkt.side_data_elems = 0;
1196     }
1197
1198     return ret ? ret : pkt.size;
1199 }
1200
1201 #endif
1202
1203 int attribute_align_arg avcodec_encode_video2(AVCodecContext *avctx,
1204                                               AVPacket *avpkt,
1205                                               const AVFrame *frame,
1206                                               int *got_packet_ptr)
1207 {
1208     int ret;
1209     int user_packet = !!avpkt->data;
1210
1211     *got_packet_ptr = 0;
1212
1213     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1214         av_free_packet(avpkt);
1215         av_init_packet(avpkt);
1216         avpkt->size = 0;
1217         return 0;
1218     }
1219
1220     if (av_image_check_size(avctx->width, avctx->height, 0, avctx))
1221         return AVERROR(EINVAL);
1222
1223     av_assert0(avctx->codec->encode2);
1224
1225     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1226     if (!ret) {
1227         if (!*got_packet_ptr)
1228             avpkt->size = 0;
1229         else if (!(avctx->codec->capabilities & CODEC_CAP_DELAY))
1230             avpkt->pts = avpkt->dts = frame->pts;
1231
1232         if (!user_packet && avpkt->size) {
1233             uint8_t *new_data = av_realloc(avpkt->data, avpkt->size);
1234             if (new_data)
1235                 avpkt->data = new_data;
1236         }
1237
1238         avctx->frame_number++;
1239     }
1240
1241     if (ret < 0 || !*got_packet_ptr)
1242         av_free_packet(avpkt);
1243
1244     emms_c();
1245     return ret;
1246 }
1247
1248 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1249                             const AVSubtitle *sub)
1250 {
1251     int ret;
1252     if (sub->start_display_time) {
1253         av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
1254         return -1;
1255     }
1256     if (sub->num_rects == 0 || !sub->rects)
1257         return -1;
1258     ret = avctx->codec->encode_sub(avctx, buf, buf_size, sub);
1259     avctx->frame_number++;
1260     return ret;
1261 }
1262
1263 static void apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
1264 {
1265     int size = 0;
1266     const uint8_t *data;
1267     uint32_t flags;
1268
1269     if (!(avctx->codec->capabilities & CODEC_CAP_PARAM_CHANGE))
1270         return;
1271
1272     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
1273     if (!data || size < 4)
1274         return;
1275     flags = bytestream_get_le32(&data);
1276     size -= 4;
1277     if (size < 4) /* Required for any of the changes */
1278         return;
1279     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
1280         avctx->channels = bytestream_get_le32(&data);
1281         size -= 4;
1282     }
1283     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
1284         if (size < 8)
1285             return;
1286         avctx->channel_layout = bytestream_get_le64(&data);
1287         size -= 8;
1288     }
1289     if (size < 4)
1290         return;
1291     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
1292         avctx->sample_rate = bytestream_get_le32(&data);
1293         size -= 4;
1294     }
1295     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
1296         if (size < 8)
1297             return;
1298         avctx->width  = bytestream_get_le32(&data);
1299         avctx->height = bytestream_get_le32(&data);
1300         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
1301         size -= 8;
1302     }
1303 }
1304
1305 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
1306                                               int *got_picture_ptr,
1307                                               AVPacket *avpkt)
1308 {
1309     int ret;
1310
1311     *got_picture_ptr = 0;
1312     if ((avctx->coded_width || avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
1313         return -1;
1314
1315     avctx->pkt = avpkt;
1316     apply_param_change(avctx, avpkt);
1317
1318     avcodec_get_frame_defaults(picture);
1319
1320     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
1321         if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1322             ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
1323                                          avpkt);
1324         else {
1325             ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
1326                                        avpkt);
1327             picture->pkt_dts             = avpkt->dts;
1328             picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
1329             picture->width               = avctx->width;
1330             picture->height              = avctx->height;
1331             picture->format              = avctx->pix_fmt;
1332         }
1333
1334         emms_c(); //needed to avoid an emms_c() call before every return;
1335
1336         if (*got_picture_ptr)
1337             avctx->frame_number++;
1338     } else
1339         ret = 0;
1340
1341     /* many decoders assign whole AVFrames, thus overwriting extended_data;
1342      * make sure it's set correctly */
1343     picture->extended_data = picture->data;
1344
1345     return ret;
1346 }
1347
1348 #if FF_API_OLD_DECODE_AUDIO
1349 int attribute_align_arg avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples,
1350                                               int *frame_size_ptr,
1351                                               AVPacket *avpkt)
1352 {
1353     AVFrame frame = {0};
1354     int ret, got_frame = 0;
1355
1356     if (avctx->get_buffer != avcodec_default_get_buffer) {
1357         av_log(avctx, AV_LOG_ERROR, "Custom get_buffer() for use with"
1358                                     "avcodec_decode_audio3() detected. Overriding with avcodec_default_get_buffer\n");
1359         av_log(avctx, AV_LOG_ERROR, "Please port your application to "
1360                                     "avcodec_decode_audio4()\n");
1361         avctx->get_buffer = avcodec_default_get_buffer;
1362     }
1363
1364     ret = avcodec_decode_audio4(avctx, &frame, &got_frame, avpkt);
1365
1366     if (ret >= 0 && got_frame) {
1367         int ch, plane_size;
1368         int planar    = av_sample_fmt_is_planar(avctx->sample_fmt);
1369         int data_size = av_samples_get_buffer_size(&plane_size, avctx->channels,
1370                                                    frame.nb_samples,
1371                                                    avctx->sample_fmt, 1);
1372         if (*frame_size_ptr < data_size) {
1373             av_log(avctx, AV_LOG_ERROR, "output buffer size is too small for "
1374                                         "the current frame (%d < %d)\n", *frame_size_ptr, data_size);
1375             return AVERROR(EINVAL);
1376         }
1377
1378         memcpy(samples, frame.extended_data[0], plane_size);
1379
1380         if (planar && avctx->channels > 1) {
1381             uint8_t *out = ((uint8_t *)samples) + plane_size;
1382             for (ch = 1; ch < avctx->channels; ch++) {
1383                 memcpy(out, frame.extended_data[ch], plane_size);
1384                 out += plane_size;
1385             }
1386         }
1387         *frame_size_ptr = data_size;
1388     } else {
1389         *frame_size_ptr = 0;
1390     }
1391     return ret;
1392 }
1393
1394 #endif
1395
1396 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
1397                                               AVFrame *frame,
1398                                               int *got_frame_ptr,
1399                                               AVPacket *avpkt)
1400 {
1401     int planar, channels;
1402     int ret = 0;
1403
1404     *got_frame_ptr = 0;
1405
1406     avctx->pkt = avpkt;
1407
1408     if (!avpkt->data && avpkt->size) {
1409         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1410         return AVERROR(EINVAL);
1411     }
1412
1413     apply_param_change(avctx, avpkt);
1414
1415     avcodec_get_frame_defaults(frame);
1416
1417     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
1418         ret = avctx->codec->decode(avctx, frame, got_frame_ptr, avpkt);
1419         if (ret >= 0 && *got_frame_ptr) {
1420             avctx->frame_number++;
1421             frame->pkt_dts = avpkt->dts;
1422             if (frame->format == AV_SAMPLE_FMT_NONE)
1423                 frame->format = avctx->sample_fmt;
1424         }
1425     }
1426
1427     /* many decoders assign whole AVFrames, thus overwriting extended_data;
1428      * make sure it's set correctly; assume decoders that actually use
1429      * extended_data are doing it correctly */
1430     planar   = av_sample_fmt_is_planar(frame->format);
1431     channels = av_get_channel_layout_nb_channels(frame->channel_layout);
1432     if (!(planar && channels > AV_NUM_DATA_POINTERS))
1433         frame->extended_data = frame->data;
1434
1435     return ret;
1436 }
1437
1438 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1439                              int *got_sub_ptr,
1440                              AVPacket *avpkt)
1441 {
1442     int ret;
1443
1444     avctx->pkt = avpkt;
1445     *got_sub_ptr = 0;
1446     ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
1447     if (*got_sub_ptr)
1448         avctx->frame_number++;
1449     return ret;
1450 }
1451
1452 void avsubtitle_free(AVSubtitle *sub)
1453 {
1454     int i;
1455
1456     for (i = 0; i < sub->num_rects; i++) {
1457         av_freep(&sub->rects[i]->pict.data[0]);
1458         av_freep(&sub->rects[i]->pict.data[1]);
1459         av_freep(&sub->rects[i]->pict.data[2]);
1460         av_freep(&sub->rects[i]->pict.data[3]);
1461         av_freep(&sub->rects[i]->text);
1462         av_freep(&sub->rects[i]->ass);
1463         av_freep(&sub->rects[i]);
1464     }
1465
1466     av_freep(&sub->rects);
1467
1468     memset(sub, 0, sizeof(AVSubtitle));
1469 }
1470
1471 av_cold int avcodec_close(AVCodecContext *avctx)
1472 {
1473     /* If there is a user-supplied mutex locking routine, call it. */
1474     if (ff_lockmgr_cb) {
1475         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
1476             return -1;
1477     }
1478
1479     entangled_thread_counter++;
1480     if (entangled_thread_counter != 1) {
1481         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
1482         entangled_thread_counter--;
1483         return -1;
1484     }
1485
1486     if (avcodec_is_open(avctx)) {
1487         if (HAVE_THREADS && avctx->thread_opaque)
1488             ff_thread_free(avctx);
1489         if (avctx->codec && avctx->codec->close)
1490             avctx->codec->close(avctx);
1491         avcodec_default_free_buffers(avctx);
1492         avctx->coded_frame = NULL;
1493         av_freep(&avctx->internal);
1494     }
1495
1496     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
1497         av_opt_free(avctx->priv_data);
1498     av_opt_free(avctx);
1499     av_freep(&avctx->priv_data);
1500     if (av_codec_is_encoder(avctx->codec))
1501         av_freep(&avctx->extradata);
1502     avctx->codec = NULL;
1503     avctx->active_thread_type = 0;
1504     entangled_thread_counter--;
1505
1506     /* Release any user-supplied mutex. */
1507     if (ff_lockmgr_cb) {
1508         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
1509     }
1510     return 0;
1511 }
1512
1513 static AVCodec *find_encdec(enum AVCodecID id, int encoder)
1514 {
1515     AVCodec *p, *experimental = NULL;
1516     p = first_avcodec;
1517     while (p) {
1518         if ((encoder ? av_codec_is_encoder(p) : av_codec_is_decoder(p)) &&
1519             p->id == id) {
1520             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
1521                 experimental = p;
1522             } else
1523                 return p;
1524         }
1525         p = p->next;
1526     }
1527     return experimental;
1528 }
1529
1530 AVCodec *avcodec_find_encoder(enum AVCodecID id)
1531 {
1532     return find_encdec(id, 1);
1533 }
1534
1535 AVCodec *avcodec_find_encoder_by_name(const char *name)
1536 {
1537     AVCodec *p;
1538     if (!name)
1539         return NULL;
1540     p = first_avcodec;
1541     while (p) {
1542         if (av_codec_is_encoder(p) && strcmp(name, p->name) == 0)
1543             return p;
1544         p = p->next;
1545     }
1546     return NULL;
1547 }
1548
1549 AVCodec *avcodec_find_decoder(enum AVCodecID id)
1550 {
1551     return find_encdec(id, 0);
1552 }
1553
1554 AVCodec *avcodec_find_decoder_by_name(const char *name)
1555 {
1556     AVCodec *p;
1557     if (!name)
1558         return NULL;
1559     p = first_avcodec;
1560     while (p) {
1561         if (av_codec_is_decoder(p) && strcmp(name, p->name) == 0)
1562             return p;
1563         p = p->next;
1564     }
1565     return NULL;
1566 }
1567
1568 static int get_bit_rate(AVCodecContext *ctx)
1569 {
1570     int bit_rate;
1571     int bits_per_sample;
1572
1573     switch (ctx->codec_type) {
1574     case AVMEDIA_TYPE_VIDEO:
1575     case AVMEDIA_TYPE_DATA:
1576     case AVMEDIA_TYPE_SUBTITLE:
1577     case AVMEDIA_TYPE_ATTACHMENT:
1578         bit_rate = ctx->bit_rate;
1579         break;
1580     case AVMEDIA_TYPE_AUDIO:
1581         bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
1582         bit_rate = bits_per_sample ? ctx->sample_rate * ctx->channels * bits_per_sample : ctx->bit_rate;
1583         break;
1584     default:
1585         bit_rate = 0;
1586         break;
1587     }
1588     return bit_rate;
1589 }
1590
1591 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
1592 {
1593     int i, len, ret = 0;
1594
1595     for (i = 0; i < 4; i++) {
1596         len = snprintf(buf, buf_size,
1597                        isprint(codec_tag & 0xFF) ? "%c" : "[%d]", codec_tag & 0xFF);
1598         buf        += len;
1599         buf_size    = buf_size > len ? buf_size - len : 0;
1600         ret        += len;
1601         codec_tag >>= 8;
1602     }
1603     return ret;
1604 }
1605
1606 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
1607 {
1608     const char *codec_name;
1609     const char *profile = NULL;
1610     const AVCodec *p;
1611     char buf1[32];
1612     int bitrate;
1613     AVRational display_aspect_ratio;
1614
1615     if (enc->codec)
1616         p = enc->codec;
1617     else if (encode)
1618         p = avcodec_find_encoder(enc->codec_id);
1619     else
1620         p = avcodec_find_decoder(enc->codec_id);
1621
1622     if (p) {
1623         codec_name = p->name;
1624         profile = av_get_profile_name(p, enc->profile);
1625     } else if (enc->codec_id == AV_CODEC_ID_MPEG2TS) {
1626         /* fake mpeg2 transport stream codec (currently not
1627          * registered) */
1628         codec_name = "mpeg2ts";
1629     } else if (enc->codec_name[0] != '\0') {
1630         codec_name = enc->codec_name;
1631     } else {
1632         /* output avi tags */
1633         char tag_buf[32];
1634         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
1635         snprintf(buf1, sizeof(buf1), "%s / 0x%04X", tag_buf, enc->codec_tag);
1636         codec_name = buf1;
1637     }
1638
1639     switch (enc->codec_type) {
1640     case AVMEDIA_TYPE_VIDEO:
1641         snprintf(buf, buf_size,
1642                  "Video: %s%s",
1643                  codec_name, enc->mb_decision ? " (hq)" : "");
1644         if (profile)
1645             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1646                      " (%s)", profile);
1647         if (enc->pix_fmt != AV_PIX_FMT_NONE) {
1648             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1649                      ", %s",
1650                      av_get_pix_fmt_name(enc->pix_fmt));
1651         }
1652         if (enc->width) {
1653             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1654                      ", %dx%d",
1655                      enc->width, enc->height);
1656             if (enc->sample_aspect_ratio.num) {
1657                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1658                           enc->width * enc->sample_aspect_ratio.num,
1659                           enc->height * enc->sample_aspect_ratio.den,
1660                           1024 * 1024);
1661                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1662                          " [PAR %d:%d DAR %d:%d]",
1663                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
1664                          display_aspect_ratio.num, display_aspect_ratio.den);
1665             }
1666             if (av_log_get_level() >= AV_LOG_DEBUG) {
1667                 int g = av_gcd(enc->time_base.num, enc->time_base.den);
1668                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1669                          ", %d/%d",
1670                          enc->time_base.num / g, enc->time_base.den / g);
1671             }
1672         }
1673         if (encode) {
1674             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1675                      ", q=%d-%d", enc->qmin, enc->qmax);
1676         }
1677         break;
1678     case AVMEDIA_TYPE_AUDIO:
1679         snprintf(buf, buf_size,
1680                  "Audio: %s",
1681                  codec_name);
1682         if (profile)
1683             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1684                      " (%s)", profile);
1685         if (enc->sample_rate) {
1686             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1687                      ", %d Hz", enc->sample_rate);
1688         }
1689         av_strlcat(buf, ", ", buf_size);
1690         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
1691         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
1692             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1693                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
1694         }
1695         break;
1696     case AVMEDIA_TYPE_DATA:
1697         snprintf(buf, buf_size, "Data: %s", codec_name);
1698         break;
1699     case AVMEDIA_TYPE_SUBTITLE:
1700         snprintf(buf, buf_size, "Subtitle: %s", codec_name);
1701         break;
1702     case AVMEDIA_TYPE_ATTACHMENT:
1703         snprintf(buf, buf_size, "Attachment: %s", codec_name);
1704         break;
1705     default:
1706         snprintf(buf, buf_size, "Invalid Codec type %d", enc->codec_type);
1707         return;
1708     }
1709     if (encode) {
1710         if (enc->flags & CODEC_FLAG_PASS1)
1711             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1712                      ", pass 1");
1713         if (enc->flags & CODEC_FLAG_PASS2)
1714             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1715                      ", pass 2");
1716     }
1717     bitrate = get_bit_rate(enc);
1718     if (bitrate != 0) {
1719         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1720                  ", %d kb/s", bitrate / 1000);
1721     }
1722 }
1723
1724 const char *av_get_profile_name(const AVCodec *codec, int profile)
1725 {
1726     const AVProfile *p;
1727     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
1728         return NULL;
1729
1730     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
1731         if (p->profile == profile)
1732             return p->name;
1733
1734     return NULL;
1735 }
1736
1737 unsigned avcodec_version(void)
1738 {
1739     return LIBAVCODEC_VERSION_INT;
1740 }
1741
1742 const char *avcodec_configuration(void)
1743 {
1744     return LIBAV_CONFIGURATION;
1745 }
1746
1747 const char *avcodec_license(void)
1748 {
1749 #define LICENSE_PREFIX "libavcodec license: "
1750     return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
1751 }
1752
1753 void avcodec_flush_buffers(AVCodecContext *avctx)
1754 {
1755     if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
1756         ff_thread_flush(avctx);
1757     else if (avctx->codec->flush)
1758         avctx->codec->flush(avctx);
1759 }
1760
1761 static void video_free_buffers(AVCodecContext *s)
1762 {
1763     AVCodecInternal *avci = s->internal;
1764     int i, j;
1765
1766     if (!avci->buffer)
1767         return;
1768
1769     if (avci->buffer_count)
1770         av_log(s, AV_LOG_WARNING, "Found %i unreleased buffers!\n",
1771                avci->buffer_count);
1772     for (i = 0; i < INTERNAL_BUFFER_SIZE; i++) {
1773         InternalBuffer *buf = &avci->buffer[i];
1774         for (j = 0; j < 4; j++) {
1775             av_freep(&buf->base[j]);
1776             buf->data[j] = NULL;
1777         }
1778     }
1779     av_freep(&avci->buffer);
1780
1781     avci->buffer_count = 0;
1782 }
1783
1784 static void audio_free_buffers(AVCodecContext *avctx)
1785 {
1786     AVCodecInternal *avci = avctx->internal;
1787     InternalBuffer *buf;
1788
1789     if (!avci->buffer)
1790         return;
1791     buf = avci->buffer;
1792
1793     if (buf->extended_data) {
1794         av_free(buf->extended_data[0]);
1795         if (buf->extended_data != buf->data)
1796             av_free(buf->extended_data);
1797     }
1798     av_freep(&avci->buffer);
1799 }
1800
1801 void avcodec_default_free_buffers(AVCodecContext *avctx)
1802 {
1803     switch (avctx->codec_type) {
1804     case AVMEDIA_TYPE_VIDEO:
1805         video_free_buffers(avctx);
1806         break;
1807     case AVMEDIA_TYPE_AUDIO:
1808         audio_free_buffers(avctx);
1809         break;
1810     default:
1811         break;
1812     }
1813 }
1814
1815 int av_get_exact_bits_per_sample(enum AVCodecID codec_id)
1816 {
1817     switch (codec_id) {
1818     case AV_CODEC_ID_ADPCM_CT:
1819     case AV_CODEC_ID_ADPCM_IMA_APC:
1820     case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
1821     case AV_CODEC_ID_ADPCM_IMA_WS:
1822     case AV_CODEC_ID_ADPCM_G722:
1823     case AV_CODEC_ID_ADPCM_YAMAHA:
1824         return 4;
1825     case AV_CODEC_ID_PCM_ALAW:
1826     case AV_CODEC_ID_PCM_MULAW:
1827     case AV_CODEC_ID_PCM_S8:
1828     case AV_CODEC_ID_PCM_U8:
1829     case AV_CODEC_ID_PCM_ZORK:
1830         return 8;
1831     case AV_CODEC_ID_PCM_S16BE:
1832     case AV_CODEC_ID_PCM_S16LE:
1833     case AV_CODEC_ID_PCM_S16LE_PLANAR:
1834     case AV_CODEC_ID_PCM_U16BE:
1835     case AV_CODEC_ID_PCM_U16LE:
1836         return 16;
1837     case AV_CODEC_ID_PCM_S24DAUD:
1838     case AV_CODEC_ID_PCM_S24BE:
1839     case AV_CODEC_ID_PCM_S24LE:
1840     case AV_CODEC_ID_PCM_U24BE:
1841     case AV_CODEC_ID_PCM_U24LE:
1842         return 24;
1843     case AV_CODEC_ID_PCM_S32BE:
1844     case AV_CODEC_ID_PCM_S32LE:
1845     case AV_CODEC_ID_PCM_U32BE:
1846     case AV_CODEC_ID_PCM_U32LE:
1847     case AV_CODEC_ID_PCM_F32BE:
1848     case AV_CODEC_ID_PCM_F32LE:
1849         return 32;
1850     case AV_CODEC_ID_PCM_F64BE:
1851     case AV_CODEC_ID_PCM_F64LE:
1852         return 64;
1853     default:
1854         return 0;
1855     }
1856 }
1857
1858 int av_get_bits_per_sample(enum AVCodecID codec_id)
1859 {
1860     switch (codec_id) {
1861     case AV_CODEC_ID_ADPCM_SBPRO_2:
1862         return 2;
1863     case AV_CODEC_ID_ADPCM_SBPRO_3:
1864         return 3;
1865     case AV_CODEC_ID_ADPCM_SBPRO_4:
1866     case AV_CODEC_ID_ADPCM_IMA_WAV:
1867     case AV_CODEC_ID_ADPCM_IMA_QT:
1868     case AV_CODEC_ID_ADPCM_SWF:
1869     case AV_CODEC_ID_ADPCM_MS:
1870         return 4;
1871     default:
1872         return av_get_exact_bits_per_sample(codec_id);
1873     }
1874 }
1875
1876 int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
1877 {
1878     int id, sr, ch, ba, tag, bps;
1879
1880     id  = avctx->codec_id;
1881     sr  = avctx->sample_rate;
1882     ch  = avctx->channels;
1883     ba  = avctx->block_align;
1884     tag = avctx->codec_tag;
1885     bps = av_get_exact_bits_per_sample(avctx->codec_id);
1886
1887     /* codecs with an exact constant bits per sample */
1888     if (bps > 0 && ch > 0 && frame_bytes > 0)
1889         return (frame_bytes * 8) / (bps * ch);
1890     bps = avctx->bits_per_coded_sample;
1891
1892     /* codecs with a fixed packet duration */
1893     switch (id) {
1894     case AV_CODEC_ID_ADPCM_ADX:    return   32;
1895     case AV_CODEC_ID_ADPCM_IMA_QT: return   64;
1896     case AV_CODEC_ID_ADPCM_EA_XAS: return  128;
1897     case AV_CODEC_ID_AMR_NB:
1898     case AV_CODEC_ID_GSM:
1899     case AV_CODEC_ID_QCELP:
1900     case AV_CODEC_ID_RA_144:
1901     case AV_CODEC_ID_RA_288:       return  160;
1902     case AV_CODEC_ID_IMC:          return  256;
1903     case AV_CODEC_ID_AMR_WB:
1904     case AV_CODEC_ID_GSM_MS:       return  320;
1905     case AV_CODEC_ID_MP1:          return  384;
1906     case AV_CODEC_ID_ATRAC1:       return  512;
1907     case AV_CODEC_ID_ATRAC3:       return 1024;
1908     case AV_CODEC_ID_MP2:
1909     case AV_CODEC_ID_MUSEPACK7:    return 1152;
1910     case AV_CODEC_ID_AC3:          return 1536;
1911     }
1912
1913     if (sr > 0) {
1914         /* calc from sample rate */
1915         if (id == AV_CODEC_ID_TTA)
1916             return 256 * sr / 245;
1917
1918         if (ch > 0) {
1919             /* calc from sample rate and channels */
1920             if (id == AV_CODEC_ID_BINKAUDIO_DCT)
1921                 return (480 << (sr / 22050)) / ch;
1922         }
1923     }
1924
1925     if (ba > 0) {
1926         /* calc from block_align */
1927         if (id == AV_CODEC_ID_SIPR) {
1928             switch (ba) {
1929             case 20: return 160;
1930             case 19: return 144;
1931             case 29: return 288;
1932             case 37: return 480;
1933             }
1934         } else if (id == AV_CODEC_ID_ILBC) {
1935             switch (ba) {
1936             case 38: return 160;
1937             case 50: return 240;
1938             }
1939         }
1940     }
1941
1942     if (frame_bytes > 0) {
1943         /* calc from frame_bytes only */
1944         if (id == AV_CODEC_ID_TRUESPEECH)
1945             return 240 * (frame_bytes / 32);
1946         if (id == AV_CODEC_ID_NELLYMOSER)
1947             return 256 * (frame_bytes / 64);
1948
1949         if (bps > 0) {
1950             /* calc from frame_bytes and bits_per_coded_sample */
1951             if (id == AV_CODEC_ID_ADPCM_G726)
1952                 return frame_bytes * 8 / bps;
1953         }
1954
1955         if (ch > 0) {
1956             /* calc from frame_bytes and channels */
1957             switch (id) {
1958             case AV_CODEC_ID_ADPCM_4XM:
1959             case AV_CODEC_ID_ADPCM_IMA_ISS:
1960                 return (frame_bytes - 4 * ch) * 2 / ch;
1961             case AV_CODEC_ID_ADPCM_IMA_SMJPEG:
1962                 return (frame_bytes - 4) * 2 / ch;
1963             case AV_CODEC_ID_ADPCM_IMA_AMV:
1964                 return (frame_bytes - 8) * 2 / ch;
1965             case AV_CODEC_ID_ADPCM_XA:
1966                 return (frame_bytes / 128) * 224 / ch;
1967             case AV_CODEC_ID_INTERPLAY_DPCM:
1968                 return (frame_bytes - 6 - ch) / ch;
1969             case AV_CODEC_ID_ROQ_DPCM:
1970                 return (frame_bytes - 8) / ch;
1971             case AV_CODEC_ID_XAN_DPCM:
1972                 return (frame_bytes - 2 * ch) / ch;
1973             case AV_CODEC_ID_MACE3:
1974                 return 3 * frame_bytes / ch;
1975             case AV_CODEC_ID_MACE6:
1976                 return 6 * frame_bytes / ch;
1977             case AV_CODEC_ID_PCM_LXF:
1978                 return 2 * (frame_bytes / (5 * ch));
1979             }
1980
1981             if (tag) {
1982                 /* calc from frame_bytes, channels, and codec_tag */
1983                 if (id == AV_CODEC_ID_SOL_DPCM) {
1984                     if (tag == 3)
1985                         return frame_bytes / ch;
1986                     else
1987                         return frame_bytes * 2 / ch;
1988                 }
1989             }
1990
1991             if (ba > 0) {
1992                 /* calc from frame_bytes, channels, and block_align */
1993                 int blocks = frame_bytes / ba;
1994                 switch (avctx->codec_id) {
1995                 case AV_CODEC_ID_ADPCM_IMA_WAV:
1996                     return blocks * (1 + (ba - 4 * ch) / (4 * ch) * 8);
1997                 case AV_CODEC_ID_ADPCM_IMA_DK3:
1998                     return blocks * (((ba - 16) * 2 / 3 * 4) / ch);
1999                 case AV_CODEC_ID_ADPCM_IMA_DK4:
2000                     return blocks * (1 + (ba - 4 * ch) * 2 / ch);
2001                 case AV_CODEC_ID_ADPCM_MS:
2002                     return blocks * (2 + (ba - 7 * ch) * 2 / ch);
2003                 }
2004             }
2005
2006             if (bps > 0) {
2007                 /* calc from frame_bytes, channels, and bits_per_coded_sample */
2008                 switch (avctx->codec_id) {
2009                 case AV_CODEC_ID_PCM_DVD:
2010                     return 2 * (frame_bytes / ((bps * 2 / 8) * ch));
2011                 case AV_CODEC_ID_PCM_BLURAY:
2012                     return frame_bytes / ((FFALIGN(ch, 2) * bps) / 8);
2013                 case AV_CODEC_ID_S302M:
2014                     return 2 * (frame_bytes / ((bps + 4) / 4)) / ch;
2015                 }
2016             }
2017         }
2018     }
2019
2020     return 0;
2021 }
2022
2023 #if !HAVE_THREADS
2024 int ff_thread_init(AVCodecContext *s)
2025 {
2026     return -1;
2027 }
2028
2029 #endif
2030
2031 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
2032 {
2033     unsigned int n = 0;
2034
2035     while (v >= 0xff) {
2036         *s++ = 0xff;
2037         v -= 0xff;
2038         n++;
2039     }
2040     *s = v;
2041     n++;
2042     return n;
2043 }
2044
2045 int ff_match_2uint16(const uint16_t(*tab)[2], int size, int a, int b)
2046 {
2047     int i;
2048     for (i = 0; i < size && !(tab[i][0] == a && tab[i][1] == b); i++) ;
2049     return i;
2050 }
2051
2052 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
2053 {
2054     av_log(avc, AV_LOG_WARNING, "%s is not implemented. Update your Libav "
2055             "version to the newest one from Git. If the problem still "
2056             "occurs, it means that your file has a feature which has not "
2057             "been implemented.\n", feature);
2058     if(want_sample)
2059         av_log_ask_for_sample(avc, NULL);
2060 }
2061
2062 void av_log_ask_for_sample(void *avc, const char *msg, ...)
2063 {
2064     va_list argument_list;
2065
2066     va_start(argument_list, msg);
2067
2068     if (msg)
2069         av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
2070     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
2071             "of this file to ftp://upload.libav.org/incoming/ "
2072             "and contact the libav-devel mailing list.\n");
2073
2074     va_end(argument_list);
2075 }
2076
2077 static AVHWAccel *first_hwaccel = NULL;
2078
2079 void av_register_hwaccel(AVHWAccel *hwaccel)
2080 {
2081     AVHWAccel **p = &first_hwaccel;
2082     while (*p)
2083         p = &(*p)->next;
2084     *p = hwaccel;
2085     hwaccel->next = NULL;
2086 }
2087
2088 AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel)
2089 {
2090     return hwaccel ? hwaccel->next : first_hwaccel;
2091 }
2092
2093 AVHWAccel *ff_find_hwaccel(enum AVCodecID codec_id, enum AVPixelFormat pix_fmt)
2094 {
2095     AVHWAccel *hwaccel = NULL;
2096
2097     while ((hwaccel = av_hwaccel_next(hwaccel)))
2098         if (hwaccel->id == codec_id
2099             && hwaccel->pix_fmt == pix_fmt)
2100             return hwaccel;
2101     return NULL;
2102 }
2103
2104 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
2105 {
2106     if (ff_lockmgr_cb) {
2107         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_DESTROY))
2108             return -1;
2109         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY))
2110             return -1;
2111     }
2112
2113     ff_lockmgr_cb = cb;
2114
2115     if (ff_lockmgr_cb) {
2116         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_CREATE))
2117             return -1;
2118         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_CREATE))
2119             return -1;
2120     }
2121     return 0;
2122 }
2123
2124 int avpriv_lock_avformat(void)
2125 {
2126     if (ff_lockmgr_cb) {
2127         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
2128             return -1;
2129     }
2130     return 0;
2131 }
2132
2133 int avpriv_unlock_avformat(void)
2134 {
2135     if (ff_lockmgr_cb) {
2136         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
2137             return -1;
2138     }
2139     return 0;
2140 }
2141
2142 unsigned int avpriv_toupper4(unsigned int x)
2143 {
2144     return toupper(x & 0xFF)
2145            + (toupper((x >> 8) & 0xFF) << 8)
2146            + (toupper((x >> 16) & 0xFF) << 16)
2147            + (toupper((x >> 24) & 0xFF) << 24);
2148 }
2149
2150 #if !HAVE_THREADS
2151
2152 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
2153 {
2154     f->owner = avctx;
2155     return avctx->get_buffer(avctx, f);
2156 }
2157
2158 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
2159 {
2160     f->owner->release_buffer(f->owner, f);
2161 }
2162
2163 void ff_thread_finish_setup(AVCodecContext *avctx)
2164 {
2165 }
2166
2167 void ff_thread_report_progress(AVFrame *f, int progress, int field)
2168 {
2169 }
2170
2171 void ff_thread_await_progress(AVFrame *f, int progress, int field)
2172 {
2173 }
2174
2175 #endif
2176
2177 enum AVMediaType avcodec_get_type(enum AVCodecID codec_id)
2178 {
2179     if (codec_id <= AV_CODEC_ID_NONE)
2180         return AVMEDIA_TYPE_UNKNOWN;
2181     else if (codec_id < AV_CODEC_ID_FIRST_AUDIO)
2182         return AVMEDIA_TYPE_VIDEO;
2183     else if (codec_id < AV_CODEC_ID_FIRST_SUBTITLE)
2184         return AVMEDIA_TYPE_AUDIO;
2185     else if (codec_id < AV_CODEC_ID_FIRST_UNKNOWN)
2186         return AVMEDIA_TYPE_SUBTITLE;
2187
2188     return AVMEDIA_TYPE_UNKNOWN;
2189 }
2190
2191 int avcodec_is_open(AVCodecContext *s)
2192 {
2193     return !!s->internal;
2194 }