]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
285be9b72bb2567fa5d7ec135f2c89d6c30150e7
[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/crc.h"
31 #include "libavutil/mathematics.h"
32 #include "libavutil/pixdesc.h"
33 #include "libavutil/audioconvert.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 "imgconvert.h"
41 #include "thread.h"
42 #include "audioconvert.h"
43 #include "internal.h"
44 #include "bytestream.h"
45 #include <stdlib.h>
46 #include <stdarg.h>
47 #include <limits.h>
48 #include <float.h>
49
50 static int volatile entangled_thread_counter=0;
51 static int (*ff_lockmgr_cb)(void **mutex, enum AVLockOp op);
52 static void *codec_mutex;
53 static void *avformat_mutex;
54
55 void *av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
56 {
57     if(min_size < *size)
58         return ptr;
59
60     min_size= FFMAX(17*min_size/16 + 32, min_size);
61
62     ptr= av_realloc(ptr, min_size);
63     if(!ptr) //we could set this to the unmodified min_size but this is safer if the user lost the ptr and uses NULL now
64         min_size= 0;
65
66     *size= min_size;
67
68     return ptr;
69 }
70
71 void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size)
72 {
73     void **p = ptr;
74     if (min_size < *size)
75         return;
76     min_size= FFMAX(17*min_size/16 + 32, min_size);
77     av_free(*p);
78     *p = av_malloc(min_size);
79     if (!*p) min_size = 0;
80     *size= min_size;
81 }
82
83 void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size)
84 {
85     void **p = ptr;
86     if (min_size > SIZE_MAX - FF_INPUT_BUFFER_PADDING_SIZE) {
87         av_freep(p);
88         *size = 0;
89         return;
90     }
91     av_fast_malloc(p, size, min_size + FF_INPUT_BUFFER_PADDING_SIZE);
92     if (*size)
93         memset((uint8_t *)*p + min_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
94 }
95
96 /* encoder management */
97 static AVCodec *first_avcodec = NULL;
98
99 AVCodec *av_codec_next(AVCodec *c){
100     if(c) return c->next;
101     else  return first_avcodec;
102 }
103
104 static void avcodec_init(void)
105 {
106     static int initialized = 0;
107
108     if (initialized != 0)
109         return;
110     initialized = 1;
111
112     ff_dsputil_static_init();
113 }
114
115 static av_always_inline int codec_is_encoder(AVCodec *codec)
116 {
117     return codec && (codec->encode || codec->encode2);
118 }
119
120 static av_always_inline int codec_is_decoder(AVCodec *codec)
121 {
122     return codec && codec->decode;
123 }
124
125 void avcodec_register(AVCodec *codec)
126 {
127     AVCodec **p;
128     avcodec_init();
129     p = &first_avcodec;
130     while (*p != NULL) p = &(*p)->next;
131     *p = codec;
132     codec->next = NULL;
133
134     if (codec->init_static_data)
135         codec->init_static_data(codec);
136 }
137
138 unsigned avcodec_get_edge_width(void)
139 {
140     return EDGE_WIDTH;
141 }
142
143 void avcodec_set_dimensions(AVCodecContext *s, int width, int height){
144     s->coded_width = width;
145     s->coded_height= height;
146     s->width = -((-width )>>s->lowres);
147     s->height= -((-height)>>s->lowres);
148 }
149
150 #define INTERNAL_BUFFER_SIZE (32+1)
151
152 void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
153                                int linesize_align[AV_NUM_DATA_POINTERS])
154 {
155     int i;
156     int w_align= 1;
157     int h_align= 1;
158
159     switch(s->pix_fmt){
160     case PIX_FMT_YUV420P:
161     case PIX_FMT_YUYV422:
162     case PIX_FMT_UYVY422:
163     case PIX_FMT_YUV422P:
164     case PIX_FMT_YUV440P:
165     case PIX_FMT_YUV444P:
166     case PIX_FMT_GBRP:
167     case PIX_FMT_GRAY8:
168     case PIX_FMT_GRAY16BE:
169     case PIX_FMT_GRAY16LE:
170     case PIX_FMT_YUVJ420P:
171     case PIX_FMT_YUVJ422P:
172     case PIX_FMT_YUVJ440P:
173     case PIX_FMT_YUVJ444P:
174     case PIX_FMT_YUVA420P:
175     case PIX_FMT_YUV420P9LE:
176     case PIX_FMT_YUV420P9BE:
177     case PIX_FMT_YUV420P10LE:
178     case PIX_FMT_YUV420P10BE:
179     case PIX_FMT_YUV422P9LE:
180     case PIX_FMT_YUV422P9BE:
181     case PIX_FMT_YUV422P10LE:
182     case PIX_FMT_YUV422P10BE:
183     case PIX_FMT_YUV444P9LE:
184     case PIX_FMT_YUV444P9BE:
185     case PIX_FMT_YUV444P10LE:
186     case PIX_FMT_YUV444P10BE:
187     case PIX_FMT_GBRP9LE:
188     case PIX_FMT_GBRP9BE:
189     case PIX_FMT_GBRP10LE:
190     case PIX_FMT_GBRP10BE:
191         w_align = 16; //FIXME assume 16 pixel per macroblock
192         h_align = 16 * 2; // interlaced needs 2 macroblocks height
193         break;
194     case PIX_FMT_YUV411P:
195     case PIX_FMT_UYYVYY411:
196         w_align=32;
197         h_align=8;
198         break;
199     case PIX_FMT_YUV410P:
200         if(s->codec_id == CODEC_ID_SVQ1){
201             w_align=64;
202             h_align=64;
203         }
204     case PIX_FMT_RGB555:
205         if(s->codec_id == CODEC_ID_RPZA){
206             w_align=4;
207             h_align=4;
208         }
209     case PIX_FMT_PAL8:
210     case PIX_FMT_BGR8:
211     case PIX_FMT_RGB8:
212         if(s->codec_id == CODEC_ID_SMC){
213             w_align=4;
214             h_align=4;
215         }
216         break;
217     case PIX_FMT_BGR24:
218         if((s->codec_id == CODEC_ID_MSZH) || (s->codec_id == CODEC_ID_ZLIB)){
219             w_align=4;
220             h_align=4;
221         }
222         break;
223     default:
224         w_align= 1;
225         h_align= 1;
226         break;
227     }
228
229     *width = FFALIGN(*width , w_align);
230     *height= FFALIGN(*height, h_align);
231     if(s->codec_id == CODEC_ID_H264 || s->lowres)
232         *height+=2; // some of the optimized chroma MC reads one line too much
233                     // which is also done in mpeg decoders with lowres > 0
234
235     for (i = 0; i < 4; i++)
236         linesize_align[i] = STRIDE_ALIGN;
237 }
238
239 void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height){
240     int chroma_shift = av_pix_fmt_descriptors[s->pix_fmt].log2_chroma_w;
241     int linesize_align[AV_NUM_DATA_POINTERS];
242     int align;
243     avcodec_align_dimensions2(s, width, height, linesize_align);
244     align = FFMAX(linesize_align[0], linesize_align[3]);
245     linesize_align[1] <<= chroma_shift;
246     linesize_align[2] <<= chroma_shift;
247     align = FFMAX3(align, linesize_align[1], linesize_align[2]);
248     *width=FFALIGN(*width, align);
249 }
250
251 int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels,
252                              enum AVSampleFormat sample_fmt, const uint8_t *buf,
253                              int buf_size, int align)
254 {
255     int ch, planar, needed_size, ret = 0;
256
257     needed_size = av_samples_get_buffer_size(NULL, nb_channels,
258                                              frame->nb_samples, sample_fmt,
259                                              align);
260     if (buf_size < needed_size)
261         return AVERROR(EINVAL);
262
263     planar = av_sample_fmt_is_planar(sample_fmt);
264     if (planar && nb_channels > AV_NUM_DATA_POINTERS) {
265         if (!(frame->extended_data = av_mallocz(nb_channels *
266                                                 sizeof(*frame->extended_data))))
267             return AVERROR(ENOMEM);
268     } else {
269         frame->extended_data = frame->data;
270     }
271
272     if ((ret = av_samples_fill_arrays(frame->extended_data, &frame->linesize[0],
273                                       buf, nb_channels, frame->nb_samples,
274                                       sample_fmt, align)) < 0) {
275         if (frame->extended_data != frame->data)
276             av_free(frame->extended_data);
277         return ret;
278     }
279     if (frame->extended_data != frame->data) {
280         for (ch = 0; ch < AV_NUM_DATA_POINTERS; ch++)
281             frame->data[ch] = frame->extended_data[ch];
282     }
283
284     return ret;
285 }
286
287 static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
288 {
289     AVCodecInternal *avci = avctx->internal;
290     InternalBuffer *buf;
291     int buf_size, ret;
292
293     buf_size = av_samples_get_buffer_size(NULL, avctx->channels,
294                                           frame->nb_samples, avctx->sample_fmt,
295                                           32);
296     if (buf_size < 0)
297         return AVERROR(EINVAL);
298
299     /* allocate InternalBuffer if needed */
300     if (!avci->buffer) {
301         avci->buffer = av_mallocz(sizeof(InternalBuffer));
302         if (!avci->buffer)
303             return AVERROR(ENOMEM);
304     }
305     buf = avci->buffer;
306
307     /* if there is a previously-used internal buffer, check its size and
308        channel count to see if we can reuse it */
309     if (buf->extended_data) {
310         /* if current buffer is too small, free it */
311         if (buf->extended_data[0] && buf_size > buf->audio_data_size) {
312             av_free(buf->extended_data[0]);
313             if (buf->extended_data != buf->data)
314                 av_free(&buf->extended_data);
315             buf->extended_data = NULL;
316             buf->data[0] = NULL;
317         }
318         /* if number of channels has changed, reset and/or free extended data
319            pointers but leave data buffer in buf->data[0] for reuse */
320         if (buf->nb_channels != avctx->channels) {
321             if (buf->extended_data != buf->data)
322                 av_free(buf->extended_data);
323             buf->extended_data = NULL;
324         }
325     }
326
327     /* if there is no previous buffer or the previous buffer cannot be used
328        as-is, allocate a new buffer and/or rearrange the channel pointers */
329     if (!buf->extended_data) {
330         if (!buf->data[0]) {
331             if (!(buf->data[0] = av_mallocz(buf_size)))
332                 return AVERROR(ENOMEM);
333             buf->audio_data_size = buf_size;
334         }
335         if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
336                                             avctx->sample_fmt, buf->data[0],
337                                             buf->audio_data_size, 32)))
338             return ret;
339
340         if (frame->extended_data == frame->data)
341             buf->extended_data = buf->data;
342         else
343             buf->extended_data = frame->extended_data;
344         memcpy(buf->data, frame->data, sizeof(frame->data));
345         buf->linesize[0] = frame->linesize[0];
346         buf->nb_channels = avctx->channels;
347     } else {
348         /* copy InternalBuffer info to the AVFrame */
349         frame->extended_data = buf->extended_data;
350         frame->linesize[0]   = buf->linesize[0];
351         memcpy(frame->data, buf->data, sizeof(frame->data));
352     }
353
354     frame->type          = FF_BUFFER_TYPE_INTERNAL;
355
356     if (avctx->pkt) frame->pkt_pts = avctx->pkt->pts;
357     else            frame->pkt_pts = AV_NOPTS_VALUE;
358     frame->reordered_opaque = avctx->reordered_opaque;
359
360     if (avctx->debug & FF_DEBUG_BUFFERS)
361         av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p, "
362                "internal audio buffer used\n", frame);
363
364     return 0;
365 }
366
367 static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
368 {
369     int i;
370     int w= s->width;
371     int h= s->height;
372     InternalBuffer *buf;
373     AVCodecInternal *avci = s->internal;
374
375     if(pic->data[0]!=NULL) {
376         av_log(s, AV_LOG_ERROR, "pic->data[0]!=NULL in avcodec_default_get_buffer\n");
377         return -1;
378     }
379     if(avci->buffer_count >= INTERNAL_BUFFER_SIZE) {
380         av_log(s, AV_LOG_ERROR, "buffer_count overflow (missing release_buffer?)\n");
381         return -1;
382     }
383
384     if(av_image_check_size(w, h, 0, s))
385         return -1;
386
387     if (!avci->buffer) {
388         avci->buffer = av_mallocz((INTERNAL_BUFFER_SIZE+1) *
389                                   sizeof(InternalBuffer));
390     }
391
392     buf = &avci->buffer[avci->buffer_count];
393
394     if(buf->base[0] && (buf->width != w || buf->height != h || buf->pix_fmt != s->pix_fmt)){
395         if(s->active_thread_type&FF_THREAD_FRAME) {
396             av_log_missing_feature(s, "Width/height changing with frame threads is", 0);
397             return -1;
398         }
399
400         for (i = 0; i < AV_NUM_DATA_POINTERS; i++) {
401             av_freep(&buf->base[i]);
402             buf->data[i]= NULL;
403         }
404     }
405
406     if (!buf->base[0]) {
407         int h_chroma_shift, v_chroma_shift;
408         int size[4] = {0};
409         int tmpsize;
410         int unaligned;
411         AVPicture picture;
412         int stride_align[AV_NUM_DATA_POINTERS];
413         const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
414
415         avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
416
417         avcodec_align_dimensions2(s, &w, &h, stride_align);
418
419         if(!(s->flags&CODEC_FLAG_EMU_EDGE)){
420             w+= EDGE_WIDTH*2;
421             h+= EDGE_WIDTH*2;
422         }
423
424         do {
425             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
426             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
427             av_image_fill_linesizes(picture.linesize, s->pix_fmt, w);
428             // increase alignment of w for next try (rhs gives the lowest bit set in w)
429             w += w & ~(w-1);
430
431             unaligned = 0;
432             for (i=0; i<4; i++){
433                 unaligned |= picture.linesize[i] % stride_align[i];
434             }
435         } while (unaligned);
436
437         tmpsize = av_image_fill_pointers(picture.data, s->pix_fmt, h, NULL, picture.linesize);
438         if (tmpsize < 0)
439             return -1;
440
441         for (i=0; i<3 && picture.data[i+1]; i++)
442             size[i] = picture.data[i+1] - picture.data[i];
443         size[i] = tmpsize - (picture.data[i] - picture.data[0]);
444
445         memset(buf->base, 0, sizeof(buf->base));
446         memset(buf->data, 0, sizeof(buf->data));
447
448         for(i=0; i<4 && size[i]; i++){
449             const int h_shift= i==0 ? 0 : h_chroma_shift;
450             const int v_shift= i==0 ? 0 : v_chroma_shift;
451
452             buf->linesize[i]= picture.linesize[i];
453
454             buf->base[i]= av_malloc(size[i]+16); //FIXME 16
455             if(buf->base[i]==NULL) return -1;
456             memset(buf->base[i], 128, size[i]);
457
458             // no edge if EDGE EMU or not planar YUV
459             if((s->flags&CODEC_FLAG_EMU_EDGE) || !size[2])
460                 buf->data[i] = buf->base[i];
461             else
462                 buf->data[i] = buf->base[i] + FFALIGN((buf->linesize[i]*EDGE_WIDTH>>v_shift) + (pixel_size*EDGE_WIDTH>>h_shift), stride_align[i]);
463         }
464         for (; i < AV_NUM_DATA_POINTERS; i++) {
465             buf->base[i] = buf->data[i] = NULL;
466             buf->linesize[i] = 0;
467         }
468         if(size[1] && !size[2])
469             ff_set_systematic_pal2((uint32_t*)buf->data[1], s->pix_fmt);
470         buf->width  = s->width;
471         buf->height = s->height;
472         buf->pix_fmt= s->pix_fmt;
473     }
474     pic->type= FF_BUFFER_TYPE_INTERNAL;
475
476     for (i = 0; i < AV_NUM_DATA_POINTERS; i++) {
477         pic->base[i]= buf->base[i];
478         pic->data[i]= buf->data[i];
479         pic->linesize[i]= buf->linesize[i];
480     }
481     pic->extended_data = pic->data;
482     avci->buffer_count++;
483
484     if(s->pkt) pic->pkt_pts= s->pkt->pts;
485     else       pic->pkt_pts= AV_NOPTS_VALUE;
486     pic->reordered_opaque= s->reordered_opaque;
487
488     if(s->debug&FF_DEBUG_BUFFERS)
489         av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p, %d "
490                "buffers used\n", pic, avci->buffer_count);
491
492     return 0;
493 }
494
495 int avcodec_default_get_buffer(AVCodecContext *avctx, AVFrame *frame)
496 {
497     switch (avctx->codec_type) {
498     case AVMEDIA_TYPE_VIDEO:
499         return video_get_buffer(avctx, frame);
500     case AVMEDIA_TYPE_AUDIO:
501         return audio_get_buffer(avctx, frame);
502     default:
503         return -1;
504     }
505 }
506
507 void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic){
508     int i;
509     InternalBuffer *buf, *last;
510     AVCodecInternal *avci = s->internal;
511
512     assert(s->codec_type == AVMEDIA_TYPE_VIDEO);
513
514     assert(pic->type==FF_BUFFER_TYPE_INTERNAL);
515     assert(avci->buffer_count);
516
517     if (avci->buffer) {
518         buf = NULL; /* avoids warning */
519         for (i = 0; i < avci->buffer_count; i++) { //just 3-5 checks so is not worth to optimize
520             buf = &avci->buffer[i];
521             if (buf->data[0] == pic->data[0])
522                 break;
523         }
524         assert(i < avci->buffer_count);
525         avci->buffer_count--;
526         last = &avci->buffer[avci->buffer_count];
527
528         if (buf != last)
529             FFSWAP(InternalBuffer, *buf, *last);
530     }
531
532     for (i = 0; i < AV_NUM_DATA_POINTERS; i++) {
533         pic->data[i]=NULL;
534 //        pic->base[i]=NULL;
535     }
536 //printf("R%X\n", pic->opaque);
537
538     if(s->debug&FF_DEBUG_BUFFERS)
539         av_log(s, AV_LOG_DEBUG, "default_release_buffer called on pic %p, %d "
540                "buffers used\n", pic, avci->buffer_count);
541 }
542
543 int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic){
544     AVFrame temp_pic;
545     int i;
546
547     assert(s->codec_type == AVMEDIA_TYPE_VIDEO);
548
549     /* If no picture return a new buffer */
550     if(pic->data[0] == NULL) {
551         /* We will copy from buffer, so must be readable */
552         pic->buffer_hints |= FF_BUFFER_HINTS_READABLE;
553         return s->get_buffer(s, pic);
554     }
555
556     assert(s->pix_fmt == pic->pix_fmt);
557
558     /* If internal buffer type return the same buffer */
559     if(pic->type == FF_BUFFER_TYPE_INTERNAL) {
560         if(s->pkt) pic->pkt_pts= s->pkt->pts;
561         else       pic->pkt_pts= AV_NOPTS_VALUE;
562         pic->reordered_opaque= s->reordered_opaque;
563         return 0;
564     }
565
566     /*
567      * Not internal type and reget_buffer not overridden, emulate cr buffer
568      */
569     temp_pic = *pic;
570     for(i = 0; i < AV_NUM_DATA_POINTERS; i++)
571         pic->data[i] = pic->base[i] = NULL;
572     pic->opaque = NULL;
573     /* Allocate new frame */
574     if (s->get_buffer(s, pic))
575         return -1;
576     /* Copy image data from old buffer to new buffer */
577     av_picture_copy((AVPicture*)pic, (AVPicture*)&temp_pic, s->pix_fmt, s->width,
578              s->height);
579     s->release_buffer(s, &temp_pic); // Release old frame
580     return 0;
581 }
582
583 int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2),void *arg, int *ret, int count, int size){
584     int i;
585
586     for(i=0; i<count; i++){
587         int r= func(c, (char*)arg + i*size);
588         if(ret) ret[i]= r;
589     }
590     return 0;
591 }
592
593 int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr),void *arg, int *ret, int count){
594     int i;
595
596     for(i=0; i<count; i++){
597         int r= func(c, arg, i, 0);
598         if(ret) ret[i]= r;
599     }
600     return 0;
601 }
602
603 enum PixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum PixelFormat *fmt){
604     while (*fmt != PIX_FMT_NONE && ff_is_hwaccel_pix_fmt(*fmt))
605         ++fmt;
606     return fmt[0];
607 }
608
609 void avcodec_get_frame_defaults(AVFrame *pic){
610     memset(pic, 0, sizeof(AVFrame));
611
612     pic->pts= AV_NOPTS_VALUE;
613     pic->key_frame= 1;
614     pic->sample_aspect_ratio = (AVRational){0, 1};
615     pic->format = -1;           /* unknown */
616 }
617
618 AVFrame *avcodec_alloc_frame(void){
619     AVFrame *pic= av_malloc(sizeof(AVFrame));
620
621     if(pic==NULL) return NULL;
622
623     avcodec_get_frame_defaults(pic);
624
625     return pic;
626 }
627
628 int attribute_align_arg avcodec_open2(AVCodecContext *avctx, AVCodec *codec, AVDictionary **options)
629 {
630     int ret = 0;
631     AVDictionary *tmp = NULL;
632
633     if (avcodec_is_open(avctx))
634         return 0;
635
636     if ((!codec && !avctx->codec)) {
637         av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2().\n");
638         return AVERROR(EINVAL);
639     }
640     if ((codec && avctx->codec && codec != avctx->codec)) {
641         av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
642                "but %s passed to avcodec_open2().\n", avctx->codec->name, codec->name);
643         return AVERROR(EINVAL);
644     }
645     if (!codec)
646         codec = avctx->codec;
647
648     if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
649         return AVERROR(EINVAL);
650
651     if (options)
652         av_dict_copy(&tmp, *options, 0);
653
654     /* If there is a user-supplied mutex locking routine, call it. */
655     if (ff_lockmgr_cb) {
656         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
657             return -1;
658     }
659
660     entangled_thread_counter++;
661     if(entangled_thread_counter != 1){
662         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
663         ret = -1;
664         goto end;
665     }
666
667     avctx->internal = av_mallocz(sizeof(AVCodecInternal));
668     if (!avctx->internal) {
669         ret = AVERROR(ENOMEM);
670         goto end;
671     }
672
673     if (codec->priv_data_size > 0) {
674       if(!avctx->priv_data){
675         avctx->priv_data = av_mallocz(codec->priv_data_size);
676         if (!avctx->priv_data) {
677             ret = AVERROR(ENOMEM);
678             goto end;
679         }
680         if (codec->priv_class) {
681             *(AVClass**)avctx->priv_data= codec->priv_class;
682             av_opt_set_defaults(avctx->priv_data);
683         }
684       }
685       if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
686           goto free_and_end;
687     } else {
688         avctx->priv_data = NULL;
689     }
690     if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
691         goto free_and_end;
692
693     if(avctx->coded_width && avctx->coded_height)
694         avcodec_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
695     else if(avctx->width && avctx->height)
696         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
697
698     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
699         && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
700            || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {
701         av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");
702         avcodec_set_dimensions(avctx, 0, 0);
703     }
704
705     /* if the decoder init function was already called previously,
706        free the already allocated subtitle_header before overwriting it */
707     if (codec_is_decoder(codec))
708         av_freep(&avctx->subtitle_header);
709
710 #define SANE_NB_CHANNELS 128U
711     if (avctx->channels > SANE_NB_CHANNELS) {
712         ret = AVERROR(EINVAL);
713         goto free_and_end;
714     }
715
716     avctx->codec = codec;
717     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
718         avctx->codec_id == CODEC_ID_NONE) {
719         avctx->codec_type = codec->type;
720         avctx->codec_id   = codec->id;
721     }
722     if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
723                            && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
724         av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");
725         ret = AVERROR(EINVAL);
726         goto free_and_end;
727     }
728     avctx->frame_number = 0;
729
730     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
731         (!avctx->time_base.num || !avctx->time_base.den)) {
732         avctx->time_base.num = 1;
733         avctx->time_base.den = avctx->sample_rate;
734     }
735
736     if (HAVE_THREADS && !avctx->thread_opaque) {
737         ret = ff_thread_init(avctx);
738         if (ret < 0) {
739             goto free_and_end;
740         }
741     }
742     if (!HAVE_THREADS && !(codec->capabilities & CODEC_CAP_AUTO_THREADS))
743         avctx->thread_count = 1;
744
745     if (avctx->codec->max_lowres < avctx->lowres) {
746         av_log(avctx, AV_LOG_ERROR, "The maximum value for lowres supported by the decoder is %d\n",
747                avctx->codec->max_lowres);
748         ret = AVERROR(EINVAL);
749         goto free_and_end;
750     }
751     if (codec_is_encoder(avctx->codec)) {
752         int i;
753         if (avctx->codec->sample_fmts) {
754             for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++)
755                 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
756                     break;
757             if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
758                 av_log(avctx, AV_LOG_ERROR, "Specified sample_fmt is not supported.\n");
759                 ret = AVERROR(EINVAL);
760                 goto free_and_end;
761             }
762         }
763         if (avctx->codec->pix_fmts) {
764             for (i = 0; avctx->codec->pix_fmts[i] != PIX_FMT_NONE; i++)
765                 if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
766                     break;
767             if (avctx->codec->pix_fmts[i] == PIX_FMT_NONE) {
768                 av_log(avctx, AV_LOG_ERROR, "Specified pix_fmt is not supported\n");
769                 ret = AVERROR(EINVAL);
770                 goto free_and_end;
771             }
772         }
773         if (avctx->codec->supported_samplerates) {
774             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
775                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
776                     break;
777             if (avctx->codec->supported_samplerates[i] == 0) {
778                 av_log(avctx, AV_LOG_ERROR, "Specified sample_rate is not supported\n");
779                 ret = AVERROR(EINVAL);
780                 goto free_and_end;
781             }
782         }
783         if (avctx->codec->channel_layouts) {
784             if (!avctx->channel_layout) {
785                 av_log(avctx, AV_LOG_WARNING, "channel_layout not specified\n");
786             } else {
787                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
788                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])
789                         break;
790                 if (avctx->codec->channel_layouts[i] == 0) {
791                     av_log(avctx, AV_LOG_ERROR, "Specified channel_layout is not supported\n");
792                     ret = AVERROR(EINVAL);
793                     goto free_and_end;
794                 }
795             }
796         }
797         if (avctx->channel_layout && avctx->channels) {
798             if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {
799                 av_log(avctx, AV_LOG_ERROR, "channel layout does not match number of channels\n");
800                 ret = AVERROR(EINVAL);
801                 goto free_and_end;
802             }
803         } else if (avctx->channel_layout) {
804             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
805         }
806     }
807
808     if(avctx->codec->init && !(avctx->active_thread_type&FF_THREAD_FRAME)){
809         ret = avctx->codec->init(avctx);
810         if (ret < 0) {
811             goto free_and_end;
812         }
813     }
814 end:
815     entangled_thread_counter--;
816
817     /* Release any user-supplied mutex. */
818     if (ff_lockmgr_cb) {
819         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
820     }
821     if (options) {
822         av_dict_free(options);
823         *options = tmp;
824     }
825
826     return ret;
827 free_and_end:
828     av_dict_free(&tmp);
829     av_freep(&avctx->priv_data);
830     av_freep(&avctx->internal);
831     avctx->codec= NULL;
832     goto end;
833 }
834
835 int ff_alloc_packet(AVPacket *avpkt, int size)
836 {
837     if (size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE)
838         return AVERROR(EINVAL);
839
840     if (avpkt->data) {
841         uint8_t *pkt_data;
842
843         if (avpkt->size < size)
844             return AVERROR(EINVAL);
845
846         pkt_data = avpkt->data;
847         av_init_packet(avpkt);
848         avpkt->data = pkt_data;
849         avpkt->size = size;
850         return 0;
851     } else {
852         return av_new_packet(avpkt, size);
853     }
854 }
855
856 int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
857                                               AVPacket *avpkt,
858                                               const AVFrame *frame,
859                                               int *got_packet_ptr)
860 {
861     int ret;
862     int user_packet = !!avpkt->data;
863     int nb_samples;
864
865     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
866         av_init_packet(avpkt);
867         avpkt->size = 0;
868         return 0;
869     }
870
871     /* check for valid frame size */
872     if (frame) {
873         nb_samples = frame->nb_samples;
874         if (avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
875             if (nb_samples > avctx->frame_size)
876                 return AVERROR(EINVAL);
877         } else if (!(avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
878             if (nb_samples != avctx->frame_size)
879                 return AVERROR(EINVAL);
880         }
881     } else {
882         nb_samples = avctx->frame_size;
883     }
884
885     if (avctx->codec->encode2) {
886         *got_packet_ptr = 0;
887         ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
888         if (!ret && *got_packet_ptr) {
889             if (!(avctx->codec->capabilities & CODEC_CAP_DELAY)) {
890                 if (avpkt->pts == AV_NOPTS_VALUE)
891                     avpkt->pts = frame->pts;
892                 if (!avpkt->duration)
893                     avpkt->duration = ff_samples_to_time_base(avctx,
894                                                               frame->nb_samples);
895             }
896             avpkt->dts = avpkt->pts;
897         } else {
898             avpkt->size = 0;
899         }
900     } else {
901         /* for compatibility with encoders not supporting encode2(), we need to
902            allocate a packet buffer if the user has not provided one or check
903            the size otherwise */
904         int fs_tmp   = 0;
905         int buf_size = avpkt->size;
906         if (!user_packet) {
907             if (avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE) {
908                 av_assert0(av_get_bits_per_sample(avctx->codec_id) != 0);
909                 buf_size = nb_samples * avctx->channels *
910                            av_get_bits_per_sample(avctx->codec_id) / 8;
911             } else {
912                 /* this is a guess as to the required size.
913                    if an encoder needs more than this, it should probably
914                    implement encode2() */
915                 buf_size = 2 * avctx->frame_size * avctx->channels *
916                            av_get_bytes_per_sample(avctx->sample_fmt);
917                 buf_size += FF_MIN_BUFFER_SIZE;
918             }
919         }
920         if ((ret = ff_alloc_packet(avpkt, buf_size)))
921             return ret;
922
923         /* Encoders using AVCodec.encode() that support
924            CODEC_CAP_SMALL_LAST_FRAME require avctx->frame_size to be set to
925            the smaller size when encoding the last frame.
926            This code can be removed once all encoders supporting
927            CODEC_CAP_SMALL_LAST_FRAME use encode2() */
928         if ((avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) &&
929             nb_samples < avctx->frame_size) {
930             fs_tmp = avctx->frame_size;
931             avctx->frame_size = nb_samples;
932         }
933
934         /* encode the frame */
935         ret = avctx->codec->encode(avctx, avpkt->data, avpkt->size,
936                                    frame ? frame->data[0] : NULL);
937         if (ret >= 0) {
938             if (!ret) {
939                 /* no output. if the packet data was allocated by libavcodec,
940                    free it */
941                 if (!user_packet)
942                     av_freep(&avpkt->data);
943             } else {
944                 if (avctx->coded_frame)
945                     avpkt->pts = avpkt->dts = avctx->coded_frame->pts;
946                 /* Set duration for final small packet. This can be removed
947                    once all encoders supporting CODEC_CAP_SMALL_LAST_FRAME use
948                    encode2() */
949                 if (fs_tmp) {
950                     avpkt->duration = ff_samples_to_time_base(avctx,
951                                                               avctx->frame_size);
952                 }
953             }
954             avpkt->size = ret;
955             *got_packet_ptr = (ret > 0);
956             ret = 0;
957         }
958
959         if (fs_tmp)
960             avctx->frame_size = fs_tmp;
961     }
962     if (!ret)
963         avctx->frame_number++;
964
965     /* NOTE: if we add any audio encoders which output non-keyframe packets,
966              this needs to be moved to the encoders, but for now we can do it
967              here to simplify things */
968     avpkt->flags |= AV_PKT_FLAG_KEY;
969
970     return ret;
971 }
972
973 #if FF_API_OLD_DECODE_AUDIO
974 int attribute_align_arg avcodec_encode_audio(AVCodecContext *avctx,
975                                              uint8_t *buf, int buf_size,
976                                              const short *samples)
977 {
978     AVPacket pkt;
979     AVFrame frame0;
980     AVFrame *frame;
981     int ret, samples_size, got_packet;
982
983     av_init_packet(&pkt);
984     pkt.data = buf;
985     pkt.size = buf_size;
986
987     if (samples) {
988         frame = &frame0;
989         avcodec_get_frame_defaults(frame);
990
991         if (avctx->frame_size) {
992             frame->nb_samples = avctx->frame_size;
993         } else {
994             /* if frame_size is not set, the number of samples must be
995                calculated from the buffer size */
996             int64_t nb_samples;
997             if (!av_get_bits_per_sample(avctx->codec_id)) {
998                 av_log(avctx, AV_LOG_ERROR, "avcodec_encode_audio() does not "
999                        "support this codec\n");
1000                 return AVERROR(EINVAL);
1001             }
1002             nb_samples = (int64_t)buf_size * 8 /
1003                          (av_get_bits_per_sample(avctx->codec_id) *
1004                          avctx->channels);
1005             if (nb_samples >= INT_MAX)
1006                 return AVERROR(EINVAL);
1007             frame->nb_samples = nb_samples;
1008         }
1009
1010         /* it is assumed that the samples buffer is large enough based on the
1011            relevant parameters */
1012         samples_size = av_samples_get_buffer_size(NULL, avctx->channels,
1013                                                   frame->nb_samples,
1014                                                   avctx->sample_fmt, 1);
1015         if ((ret = avcodec_fill_audio_frame(frame, avctx->channels,
1016                                             avctx->sample_fmt,
1017                                             samples, samples_size, 1)))
1018             return ret;
1019
1020         /* fabricate frame pts from sample count.
1021            this is needed because the avcodec_encode_audio() API does not have
1022            a way for the user to provide pts */
1023         frame->pts = ff_samples_to_time_base(avctx,
1024                                              avctx->internal->sample_count);
1025         avctx->internal->sample_count += frame->nb_samples;
1026     } else {
1027         frame = NULL;
1028     }
1029
1030     got_packet = 0;
1031     ret = avcodec_encode_audio2(avctx, &pkt, frame, &got_packet);
1032     if (!ret && got_packet && avctx->coded_frame) {
1033         avctx->coded_frame->pts       = pkt.pts;
1034         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1035     }
1036     /* free any side data since we cannot return it */
1037     if (pkt.side_data_elems > 0) {
1038         int i;
1039         for (i = 0; i < pkt.side_data_elems; i++)
1040             av_free(pkt.side_data[i].data);
1041         av_freep(&pkt.side_data);
1042         pkt.side_data_elems = 0;
1043     }
1044
1045     if (frame && frame->extended_data != frame->data)
1046         av_free(frame->extended_data);
1047
1048     return ret ? ret : pkt.size;
1049 }
1050 #endif
1051
1052 #if FF_API_OLD_ENCODE_VIDEO
1053 int attribute_align_arg avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1054                          const AVFrame *pict)
1055 {
1056     AVPacket pkt;
1057     int ret, got_packet = 0;
1058
1059     if(buf_size < FF_MIN_BUFFER_SIZE){
1060         av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
1061         return -1;
1062     }
1063
1064     av_init_packet(&pkt);
1065     pkt.data = buf;
1066     pkt.size = buf_size;
1067
1068     ret = avcodec_encode_video2(avctx, &pkt, pict, &got_packet);
1069     if (!ret && got_packet && avctx->coded_frame) {
1070         avctx->coded_frame->pts       = pkt.pts;
1071         avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);
1072     }
1073
1074     /* free any side data since we cannot return it */
1075     if (pkt.side_data_elems > 0) {
1076         int i;
1077         for (i = 0; i < pkt.side_data_elems; i++)
1078             av_free(pkt.side_data[i].data);
1079         av_freep(&pkt.side_data);
1080         pkt.side_data_elems = 0;
1081     }
1082
1083     return ret ? ret : pkt.size;
1084 }
1085 #endif
1086
1087 int attribute_align_arg avcodec_encode_video2(AVCodecContext *avctx,
1088                                               AVPacket *avpkt,
1089                                               const AVFrame *frame,
1090                                               int *got_packet_ptr)
1091 {
1092     int ret;
1093     int user_packet = !!avpkt->data;
1094
1095     if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {
1096         av_init_packet(avpkt);
1097         avpkt->size     = 0;
1098         *got_packet_ptr = 0;
1099         return 0;
1100     }
1101
1102     if (av_image_check_size(avctx->width, avctx->height, 0, avctx))
1103         return AVERROR(EINVAL);
1104
1105     av_assert0(avctx->codec->encode2);
1106
1107     *got_packet_ptr = 0;
1108     ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
1109     if (!ret) {
1110         if (!*got_packet_ptr)
1111             avpkt->size = 0;
1112         else if (!(avctx->codec->capabilities & CODEC_CAP_DELAY))
1113             avpkt->pts = avpkt->dts = frame->pts;
1114     }
1115
1116     if (!ret)
1117         avctx->frame_number++;
1118
1119     emms_c();
1120     return ret;
1121 }
1122
1123 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
1124                             const AVSubtitle *sub)
1125 {
1126     int ret;
1127     if(sub->start_display_time) {
1128         av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
1129         return -1;
1130     }
1131     if(sub->num_rects == 0 || !sub->rects)
1132         return -1;
1133     ret = avctx->codec->encode(avctx, buf, buf_size, sub);
1134     avctx->frame_number++;
1135     return ret;
1136 }
1137
1138 static void apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
1139 {
1140     int size = 0;
1141     const uint8_t *data;
1142     uint32_t flags;
1143
1144     if (!(avctx->codec->capabilities & CODEC_CAP_PARAM_CHANGE))
1145         return;
1146
1147     data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
1148     if (!data || size < 4)
1149         return;
1150     flags = bytestream_get_le32(&data);
1151     size -= 4;
1152     if (size < 4) /* Required for any of the changes */
1153         return;
1154     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
1155         avctx->channels = bytestream_get_le32(&data);
1156         size -= 4;
1157     }
1158     if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
1159         if (size < 8)
1160             return;
1161         avctx->channel_layout = bytestream_get_le64(&data);
1162         size -= 8;
1163     }
1164     if (size < 4)
1165         return;
1166     if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
1167         avctx->sample_rate = bytestream_get_le32(&data);
1168         size -= 4;
1169     }
1170     if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
1171         if (size < 8)
1172             return;
1173         avctx->width  = bytestream_get_le32(&data);
1174         avctx->height = bytestream_get_le32(&data);
1175         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
1176         size -= 8;
1177     }
1178 }
1179
1180 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
1181                          int *got_picture_ptr,
1182                          AVPacket *avpkt)
1183 {
1184     int ret;
1185
1186     *got_picture_ptr= 0;
1187     if((avctx->coded_width||avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
1188         return -1;
1189
1190     avctx->pkt = avpkt;
1191     apply_param_change(avctx, avpkt);
1192
1193     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type&FF_THREAD_FRAME)){
1194         if (HAVE_THREADS && avctx->active_thread_type&FF_THREAD_FRAME)
1195              ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
1196                                           avpkt);
1197         else {
1198             ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
1199                               avpkt);
1200             picture->pkt_dts= avpkt->dts;
1201             picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
1202             picture->width  = avctx->width;
1203             picture->height = avctx->height;
1204             picture->format = avctx->pix_fmt;
1205         }
1206
1207         emms_c(); //needed to avoid an emms_c() call before every return;
1208
1209         if (*got_picture_ptr)
1210             avctx->frame_number++;
1211     }else
1212         ret= 0;
1213
1214     return ret;
1215 }
1216
1217 #if FF_API_OLD_DECODE_AUDIO
1218 int attribute_align_arg avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples,
1219                          int *frame_size_ptr,
1220                          AVPacket *avpkt)
1221 {
1222     AVFrame frame;
1223     int ret, got_frame = 0;
1224
1225     if (avctx->get_buffer != avcodec_default_get_buffer) {
1226         av_log(avctx, AV_LOG_ERROR, "Custom get_buffer() for use with"
1227                "avcodec_decode_audio3() detected. Overriding with avcodec_default_get_buffer\n");
1228         av_log(avctx, AV_LOG_ERROR, "Please port your application to "
1229                "avcodec_decode_audio4()\n");
1230         avctx->get_buffer = avcodec_default_get_buffer;
1231     }
1232
1233     ret = avcodec_decode_audio4(avctx, &frame, &got_frame, avpkt);
1234
1235     if (ret >= 0 && got_frame) {
1236         int ch, plane_size;
1237         int planar = av_sample_fmt_is_planar(avctx->sample_fmt);
1238         int data_size = av_samples_get_buffer_size(&plane_size, avctx->channels,
1239                                                    frame.nb_samples,
1240                                                    avctx->sample_fmt, 1);
1241         if (*frame_size_ptr < data_size) {
1242             av_log(avctx, AV_LOG_ERROR, "output buffer size is too small for "
1243                    "the current frame (%d < %d)\n", *frame_size_ptr, data_size);
1244             return AVERROR(EINVAL);
1245         }
1246
1247         memcpy(samples, frame.extended_data[0], plane_size);
1248
1249         if (planar && avctx->channels > 1) {
1250             uint8_t *out = ((uint8_t *)samples) + plane_size;
1251             for (ch = 1; ch < avctx->channels; ch++) {
1252                 memcpy(out, frame.extended_data[ch], plane_size);
1253                 out += plane_size;
1254             }
1255         }
1256         *frame_size_ptr = data_size;
1257     } else {
1258         *frame_size_ptr = 0;
1259     }
1260     return ret;
1261 }
1262 #endif
1263
1264 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
1265                                               AVFrame *frame,
1266                                               int *got_frame_ptr,
1267                                               AVPacket *avpkt)
1268 {
1269     int ret = 0;
1270
1271     *got_frame_ptr = 0;
1272
1273     avctx->pkt = avpkt;
1274
1275     if (!avpkt->data && avpkt->size) {
1276         av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
1277         return AVERROR(EINVAL);
1278     }
1279
1280     apply_param_change(avctx, avpkt);
1281
1282     if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
1283         ret = avctx->codec->decode(avctx, frame, got_frame_ptr, avpkt);
1284         if (ret >= 0 && *got_frame_ptr) {
1285             avctx->frame_number++;
1286             frame->pkt_dts = avpkt->dts;
1287             if (frame->format == AV_SAMPLE_FMT_NONE)
1288                 frame->format = avctx->sample_fmt;
1289         }
1290     }
1291     return ret;
1292 }
1293
1294 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
1295                             int *got_sub_ptr,
1296                             AVPacket *avpkt)
1297 {
1298     int ret;
1299
1300     avctx->pkt = avpkt;
1301     *got_sub_ptr = 0;
1302     ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
1303     if (*got_sub_ptr)
1304         avctx->frame_number++;
1305     return ret;
1306 }
1307
1308 void avsubtitle_free(AVSubtitle *sub)
1309 {
1310     int i;
1311
1312     for (i = 0; i < sub->num_rects; i++)
1313     {
1314         av_freep(&sub->rects[i]->pict.data[0]);
1315         av_freep(&sub->rects[i]->pict.data[1]);
1316         av_freep(&sub->rects[i]->pict.data[2]);
1317         av_freep(&sub->rects[i]->pict.data[3]);
1318         av_freep(&sub->rects[i]->text);
1319         av_freep(&sub->rects[i]->ass);
1320         av_freep(&sub->rects[i]);
1321     }
1322
1323     av_freep(&sub->rects);
1324
1325     memset(sub, 0, sizeof(AVSubtitle));
1326 }
1327
1328 av_cold int avcodec_close(AVCodecContext *avctx)
1329 {
1330     /* If there is a user-supplied mutex locking routine, call it. */
1331     if (ff_lockmgr_cb) {
1332         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
1333             return -1;
1334     }
1335
1336     entangled_thread_counter++;
1337     if(entangled_thread_counter != 1){
1338         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
1339         entangled_thread_counter--;
1340         return -1;
1341     }
1342
1343     if (avcodec_is_open(avctx)) {
1344         if (HAVE_THREADS && avctx->thread_opaque)
1345             ff_thread_free(avctx);
1346         if (avctx->codec && avctx->codec->close)
1347             avctx->codec->close(avctx);
1348         avcodec_default_free_buffers(avctx);
1349         avctx->coded_frame = NULL;
1350         av_freep(&avctx->internal);
1351     }
1352
1353     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
1354         av_opt_free(avctx->priv_data);
1355     av_opt_free(avctx);
1356     av_freep(&avctx->priv_data);
1357     if (codec_is_encoder(avctx->codec))
1358         av_freep(&avctx->extradata);
1359     avctx->codec = NULL;
1360     avctx->active_thread_type = 0;
1361     entangled_thread_counter--;
1362
1363     /* Release any user-supplied mutex. */
1364     if (ff_lockmgr_cb) {
1365         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
1366     }
1367     return 0;
1368 }
1369
1370 AVCodec *avcodec_find_encoder(enum CodecID id)
1371 {
1372     AVCodec *p, *experimental=NULL;
1373     p = first_avcodec;
1374     while (p) {
1375         if (codec_is_encoder(p) && p->id == id) {
1376             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
1377                 experimental = p;
1378             } else
1379                 return p;
1380         }
1381         p = p->next;
1382     }
1383     return experimental;
1384 }
1385
1386 AVCodec *avcodec_find_encoder_by_name(const char *name)
1387 {
1388     AVCodec *p;
1389     if (!name)
1390         return NULL;
1391     p = first_avcodec;
1392     while (p) {
1393         if (codec_is_encoder(p) && strcmp(name,p->name) == 0)
1394             return p;
1395         p = p->next;
1396     }
1397     return NULL;
1398 }
1399
1400 AVCodec *avcodec_find_decoder(enum CodecID id)
1401 {
1402     AVCodec *p;
1403     p = first_avcodec;
1404     while (p) {
1405         if (codec_is_decoder(p) && p->id == id)
1406             return p;
1407         p = p->next;
1408     }
1409     return NULL;
1410 }
1411
1412 AVCodec *avcodec_find_decoder_by_name(const char *name)
1413 {
1414     AVCodec *p;
1415     if (!name)
1416         return NULL;
1417     p = first_avcodec;
1418     while (p) {
1419         if (codec_is_decoder(p) && strcmp(name,p->name) == 0)
1420             return p;
1421         p = p->next;
1422     }
1423     return NULL;
1424 }
1425
1426 static int get_bit_rate(AVCodecContext *ctx)
1427 {
1428     int bit_rate;
1429     int bits_per_sample;
1430
1431     switch(ctx->codec_type) {
1432     case AVMEDIA_TYPE_VIDEO:
1433     case AVMEDIA_TYPE_DATA:
1434     case AVMEDIA_TYPE_SUBTITLE:
1435     case AVMEDIA_TYPE_ATTACHMENT:
1436         bit_rate = ctx->bit_rate;
1437         break;
1438     case AVMEDIA_TYPE_AUDIO:
1439         bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
1440         bit_rate = bits_per_sample ? ctx->sample_rate * ctx->channels * bits_per_sample : ctx->bit_rate;
1441         break;
1442     default:
1443         bit_rate = 0;
1444         break;
1445     }
1446     return bit_rate;
1447 }
1448
1449 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
1450 {
1451     int i, len, ret = 0;
1452
1453     for (i = 0; i < 4; i++) {
1454         len = snprintf(buf, buf_size,
1455                        isprint(codec_tag&0xFF) ? "%c" : "[%d]", codec_tag&0xFF);
1456         buf      += len;
1457         buf_size  = buf_size > len ? buf_size - len : 0;
1458         ret      += len;
1459         codec_tag>>=8;
1460     }
1461     return ret;
1462 }
1463
1464 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
1465 {
1466     const char *codec_name;
1467     const char *profile = NULL;
1468     AVCodec *p;
1469     char buf1[32];
1470     int bitrate;
1471     AVRational display_aspect_ratio;
1472
1473     if (encode)
1474         p = avcodec_find_encoder(enc->codec_id);
1475     else
1476         p = avcodec_find_decoder(enc->codec_id);
1477
1478     if (p) {
1479         codec_name = p->name;
1480         profile = av_get_profile_name(p, enc->profile);
1481     } else if (enc->codec_id == CODEC_ID_MPEG2TS) {
1482         /* fake mpeg2 transport stream codec (currently not
1483            registered) */
1484         codec_name = "mpeg2ts";
1485     } else if (enc->codec_name[0] != '\0') {
1486         codec_name = enc->codec_name;
1487     } else {
1488         /* output avi tags */
1489         char tag_buf[32];
1490         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
1491         snprintf(buf1, sizeof(buf1), "%s / 0x%04X", tag_buf, enc->codec_tag);
1492         codec_name = buf1;
1493     }
1494
1495     switch(enc->codec_type) {
1496     case AVMEDIA_TYPE_VIDEO:
1497         snprintf(buf, buf_size,
1498                  "Video: %s%s",
1499                  codec_name, enc->mb_decision ? " (hq)" : "");
1500         if (profile)
1501             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1502                      " (%s)", profile);
1503         if (enc->pix_fmt != PIX_FMT_NONE) {
1504             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1505                      ", %s",
1506                      av_get_pix_fmt_name(enc->pix_fmt));
1507         }
1508         if (enc->width) {
1509             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1510                      ", %dx%d",
1511                      enc->width, enc->height);
1512             if (enc->sample_aspect_ratio.num) {
1513                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1514                           enc->width*enc->sample_aspect_ratio.num,
1515                           enc->height*enc->sample_aspect_ratio.den,
1516                           1024*1024);
1517                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1518                          " [PAR %d:%d DAR %d:%d]",
1519                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
1520                          display_aspect_ratio.num, display_aspect_ratio.den);
1521             }
1522             if(av_log_get_level() >= AV_LOG_DEBUG){
1523                 int g= av_gcd(enc->time_base.num, enc->time_base.den);
1524                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
1525                      ", %d/%d",
1526                      enc->time_base.num/g, enc->time_base.den/g);
1527             }
1528         }
1529         if (encode) {
1530             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1531                      ", q=%d-%d", enc->qmin, enc->qmax);
1532         }
1533         break;
1534     case AVMEDIA_TYPE_AUDIO:
1535         snprintf(buf, buf_size,
1536                  "Audio: %s",
1537                  codec_name);
1538         if (profile)
1539             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1540                      " (%s)", profile);
1541         if (enc->sample_rate) {
1542             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1543                      ", %d Hz", enc->sample_rate);
1544         }
1545         av_strlcat(buf, ", ", buf_size);
1546         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
1547         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
1548             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1549                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
1550         }
1551         break;
1552     case AVMEDIA_TYPE_DATA:
1553         snprintf(buf, buf_size, "Data: %s", codec_name);
1554         break;
1555     case AVMEDIA_TYPE_SUBTITLE:
1556         snprintf(buf, buf_size, "Subtitle: %s", codec_name);
1557         break;
1558     case AVMEDIA_TYPE_ATTACHMENT:
1559         snprintf(buf, buf_size, "Attachment: %s", codec_name);
1560         break;
1561     default:
1562         snprintf(buf, buf_size, "Invalid Codec type %d", enc->codec_type);
1563         return;
1564     }
1565     if (encode) {
1566         if (enc->flags & CODEC_FLAG_PASS1)
1567             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1568                      ", pass 1");
1569         if (enc->flags & CODEC_FLAG_PASS2)
1570             snprintf(buf + strlen(buf), buf_size - strlen(buf),
1571                      ", pass 2");
1572     }
1573     bitrate = get_bit_rate(enc);
1574     if (bitrate != 0) {
1575         snprintf(buf + strlen(buf), buf_size - strlen(buf),
1576                  ", %d kb/s", bitrate / 1000);
1577     }
1578 }
1579
1580 const char *av_get_profile_name(const AVCodec *codec, int profile)
1581 {
1582     const AVProfile *p;
1583     if (profile == FF_PROFILE_UNKNOWN || !codec->profiles)
1584         return NULL;
1585
1586     for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++)
1587         if (p->profile == profile)
1588             return p->name;
1589
1590     return NULL;
1591 }
1592
1593 unsigned avcodec_version( void )
1594 {
1595   return LIBAVCODEC_VERSION_INT;
1596 }
1597
1598 const char *avcodec_configuration(void)
1599 {
1600     return LIBAV_CONFIGURATION;
1601 }
1602
1603 const char *avcodec_license(void)
1604 {
1605 #define LICENSE_PREFIX "libavcodec license: "
1606     return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
1607 }
1608
1609 void avcodec_flush_buffers(AVCodecContext *avctx)
1610 {
1611     if(HAVE_THREADS && avctx->active_thread_type&FF_THREAD_FRAME)
1612         ff_thread_flush(avctx);
1613     else if(avctx->codec->flush)
1614         avctx->codec->flush(avctx);
1615 }
1616
1617 static void video_free_buffers(AVCodecContext *s)
1618 {
1619     AVCodecInternal *avci = s->internal;
1620     int i, j;
1621
1622     if (!avci->buffer)
1623         return;
1624
1625     if (avci->buffer_count)
1626         av_log(s, AV_LOG_WARNING, "Found %i unreleased buffers!\n",
1627                avci->buffer_count);
1628     for(i=0; i<INTERNAL_BUFFER_SIZE; i++){
1629         InternalBuffer *buf = &avci->buffer[i];
1630         for(j=0; j<4; j++){
1631             av_freep(&buf->base[j]);
1632             buf->data[j]= NULL;
1633         }
1634     }
1635     av_freep(&avci->buffer);
1636
1637     avci->buffer_count=0;
1638 }
1639
1640 static void audio_free_buffers(AVCodecContext *avctx)
1641 {
1642     AVCodecInternal *avci = avctx->internal;
1643     InternalBuffer *buf;
1644
1645     if (!avci->buffer)
1646         return;
1647     buf = avci->buffer;
1648
1649     if (buf->extended_data) {
1650         av_free(buf->extended_data[0]);
1651         if (buf->extended_data != buf->data)
1652             av_free(buf->extended_data);
1653     }
1654     av_freep(&avci->buffer);
1655 }
1656
1657 void avcodec_default_free_buffers(AVCodecContext *avctx)
1658 {
1659     switch (avctx->codec_type) {
1660     case AVMEDIA_TYPE_VIDEO:
1661         video_free_buffers(avctx);
1662         break;
1663     case AVMEDIA_TYPE_AUDIO:
1664         audio_free_buffers(avctx);
1665         break;
1666     default:
1667         break;
1668     }
1669 }
1670
1671 int av_get_bits_per_sample(enum CodecID codec_id){
1672     switch(codec_id){
1673     case CODEC_ID_ADPCM_SBPRO_2:
1674         return 2;
1675     case CODEC_ID_ADPCM_SBPRO_3:
1676         return 3;
1677     case CODEC_ID_ADPCM_SBPRO_4:
1678     case CODEC_ID_ADPCM_CT:
1679     case CODEC_ID_ADPCM_IMA_APC:
1680     case CODEC_ID_ADPCM_IMA_WAV:
1681     case CODEC_ID_ADPCM_IMA_QT:
1682     case CODEC_ID_ADPCM_SWF:
1683     case CODEC_ID_ADPCM_MS:
1684     case CODEC_ID_ADPCM_YAMAHA:
1685     case CODEC_ID_ADPCM_G722:
1686         return 4;
1687     case CODEC_ID_PCM_ALAW:
1688     case CODEC_ID_PCM_MULAW:
1689     case CODEC_ID_PCM_S8:
1690     case CODEC_ID_PCM_U8:
1691     case CODEC_ID_PCM_ZORK:
1692         return 8;
1693     case CODEC_ID_PCM_S16BE:
1694     case CODEC_ID_PCM_S16LE:
1695     case CODEC_ID_PCM_S16LE_PLANAR:
1696     case CODEC_ID_PCM_U16BE:
1697     case CODEC_ID_PCM_U16LE:
1698         return 16;
1699     case CODEC_ID_PCM_S24DAUD:
1700     case CODEC_ID_PCM_S24BE:
1701     case CODEC_ID_PCM_S24LE:
1702     case CODEC_ID_PCM_U24BE:
1703     case CODEC_ID_PCM_U24LE:
1704         return 24;
1705     case CODEC_ID_PCM_S32BE:
1706     case CODEC_ID_PCM_S32LE:
1707     case CODEC_ID_PCM_U32BE:
1708     case CODEC_ID_PCM_U32LE:
1709     case CODEC_ID_PCM_F32BE:
1710     case CODEC_ID_PCM_F32LE:
1711         return 32;
1712     case CODEC_ID_PCM_F64BE:
1713     case CODEC_ID_PCM_F64LE:
1714         return 64;
1715     default:
1716         return 0;
1717     }
1718 }
1719
1720 #if !HAVE_THREADS
1721 int ff_thread_init(AVCodecContext *s){
1722     return -1;
1723 }
1724 #endif
1725
1726 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
1727 {
1728     unsigned int n = 0;
1729
1730     while(v >= 0xff) {
1731         *s++ = 0xff;
1732         v -= 0xff;
1733         n++;
1734     }
1735     *s = v;
1736     n++;
1737     return n;
1738 }
1739
1740 int ff_match_2uint16(const uint16_t (*tab)[2], int size, int a, int b){
1741     int i;
1742     for(i=0; i<size && !(tab[i][0]==a && tab[i][1]==b); i++);
1743     return i;
1744 }
1745
1746 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
1747 {
1748     av_log(avc, AV_LOG_WARNING, "%s not implemented. Update your Libav "
1749             "version to the newest one from Git. If the problem still "
1750             "occurs, it means that your file has a feature which has not "
1751             "been implemented.\n", feature);
1752     if(want_sample)
1753         av_log_ask_for_sample(avc, NULL);
1754 }
1755
1756 void av_log_ask_for_sample(void *avc, const char *msg, ...)
1757 {
1758     va_list argument_list;
1759
1760     va_start(argument_list, msg);
1761
1762     if (msg)
1763         av_vlog(avc, AV_LOG_WARNING, msg, argument_list);
1764     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
1765             "of this file to ftp://upload.libav.org/incoming/ "
1766             "and contact the libav-devel mailing list.\n");
1767
1768     va_end(argument_list);
1769 }
1770
1771 static AVHWAccel *first_hwaccel = NULL;
1772
1773 void av_register_hwaccel(AVHWAccel *hwaccel)
1774 {
1775     AVHWAccel **p = &first_hwaccel;
1776     while (*p)
1777         p = &(*p)->next;
1778     *p = hwaccel;
1779     hwaccel->next = NULL;
1780 }
1781
1782 AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel)
1783 {
1784     return hwaccel ? hwaccel->next : first_hwaccel;
1785 }
1786
1787 AVHWAccel *ff_find_hwaccel(enum CodecID codec_id, enum PixelFormat pix_fmt)
1788 {
1789     AVHWAccel *hwaccel=NULL;
1790
1791     while((hwaccel= av_hwaccel_next(hwaccel))){
1792         if (   hwaccel->id      == codec_id
1793             && hwaccel->pix_fmt == pix_fmt)
1794             return hwaccel;
1795     }
1796     return NULL;
1797 }
1798
1799 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
1800 {
1801     if (ff_lockmgr_cb) {
1802         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_DESTROY))
1803             return -1;
1804         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY))
1805             return -1;
1806     }
1807
1808     ff_lockmgr_cb = cb;
1809
1810     if (ff_lockmgr_cb) {
1811         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_CREATE))
1812             return -1;
1813         if (ff_lockmgr_cb(&avformat_mutex, AV_LOCK_CREATE))
1814             return -1;
1815     }
1816     return 0;
1817 }
1818
1819 int avpriv_lock_avformat(void)
1820 {
1821     if (ff_lockmgr_cb) {
1822         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN))
1823             return -1;
1824     }
1825     return 0;
1826 }
1827
1828 int avpriv_unlock_avformat(void)
1829 {
1830     if (ff_lockmgr_cb) {
1831         if ((*ff_lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))
1832             return -1;
1833     }
1834     return 0;
1835 }
1836
1837 unsigned int avpriv_toupper4(unsigned int x)
1838 {
1839     return     toupper( x     &0xFF)
1840             + (toupper((x>>8 )&0xFF)<<8 )
1841             + (toupper((x>>16)&0xFF)<<16)
1842             + (toupper((x>>24)&0xFF)<<24);
1843 }
1844
1845 #if !HAVE_THREADS
1846
1847 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
1848 {
1849     f->owner = avctx;
1850     return avctx->get_buffer(avctx, f);
1851 }
1852
1853 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
1854 {
1855     f->owner->release_buffer(f->owner, f);
1856 }
1857
1858 void ff_thread_finish_setup(AVCodecContext *avctx)
1859 {
1860 }
1861
1862 void ff_thread_report_progress(AVFrame *f, int progress, int field)
1863 {
1864 }
1865
1866 void ff_thread_await_progress(AVFrame *f, int progress, int field)
1867 {
1868 }
1869
1870 #endif
1871
1872 enum AVMediaType avcodec_get_type(enum CodecID codec_id)
1873 {
1874     if (codec_id <= CODEC_ID_NONE)
1875         return AVMEDIA_TYPE_UNKNOWN;
1876     else if (codec_id < CODEC_ID_FIRST_AUDIO)
1877         return AVMEDIA_TYPE_VIDEO;
1878     else if (codec_id < CODEC_ID_FIRST_SUBTITLE)
1879         return AVMEDIA_TYPE_AUDIO;
1880     else if (codec_id < CODEC_ID_FIRST_UNKNOWN)
1881         return AVMEDIA_TYPE_SUBTITLE;
1882
1883     return AVMEDIA_TYPE_UNKNOWN;
1884 }
1885
1886 int avcodec_is_open(AVCodecContext *s)
1887 {
1888     return !!s->internal;
1889 }