]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
Separate most of the per-block arrays into a separate per-block struct.
[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 FFmpeg.
7  *
8  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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/avstring.h"
29 #include "libavutil/integer.h"
30 #include "libavutil/crc.h"
31 #include "libavutil/pixdesc.h"
32 #include "libavcore/audioconvert.h"
33 #include "libavcore/imgutils.h"
34 #include "libavcore/internal.h"
35 #include "libavcore/samplefmt.h"
36 #include "avcodec.h"
37 #include "dsputil.h"
38 #include "libavutil/opt.h"
39 #include "imgconvert.h"
40 #include "audioconvert.h"
41 #include "internal.h"
42 #include <stdlib.h>
43 #include <stdarg.h>
44 #include <limits.h>
45 #include <float.h>
46
47 static int volatile entangled_thread_counter=0;
48 int (*ff_lockmgr_cb)(void **mutex, enum AVLockOp op);
49 static void *codec_mutex;
50
51 void *av_fast_realloc(void *ptr, unsigned int *size, FF_INTERNALC_MEM_TYPE min_size)
52 {
53     if(min_size < *size)
54         return ptr;
55
56     min_size= FFMAX(17*min_size/16 + 32, min_size);
57
58     ptr= av_realloc(ptr, min_size);
59     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
60         min_size= 0;
61
62     *size= min_size;
63
64     return ptr;
65 }
66
67 void av_fast_malloc(void *ptr, unsigned int *size, FF_INTERNALC_MEM_TYPE min_size)
68 {
69     void **p = ptr;
70     if (min_size < *size)
71         return;
72     min_size= FFMAX(17*min_size/16 + 32, min_size);
73     av_free(*p);
74     *p = av_malloc(min_size);
75     if (!*p) min_size = 0;
76     *size= min_size;
77 }
78
79 /* encoder management */
80 static AVCodec *first_avcodec = NULL;
81
82 AVCodec *av_codec_next(AVCodec *c){
83     if(c) return c->next;
84     else  return first_avcodec;
85 }
86
87 void avcodec_register(AVCodec *codec)
88 {
89     AVCodec **p;
90     avcodec_init();
91     p = &first_avcodec;
92     while (*p != NULL) p = &(*p)->next;
93     *p = codec;
94     codec->next = NULL;
95 }
96
97 #if LIBAVCODEC_VERSION_MAJOR < 53
98 void register_avcodec(AVCodec *codec)
99 {
100     avcodec_register(codec);
101 }
102 #endif
103
104 unsigned avcodec_get_edge_width(void)
105 {
106     return EDGE_WIDTH;
107 }
108
109 void avcodec_set_dimensions(AVCodecContext *s, int width, int height){
110     s->coded_width = width;
111     s->coded_height= height;
112     s->width = -((-width )>>s->lowres);
113     s->height= -((-height)>>s->lowres);
114 }
115
116 typedef struct InternalBuffer{
117     int last_pic_num;
118     uint8_t *base[4];
119     uint8_t *data[4];
120     int linesize[4];
121     int width, height;
122     enum PixelFormat pix_fmt;
123 }InternalBuffer;
124
125 #define INTERNAL_BUFFER_SIZE 32
126
127 void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height, int linesize_align[4]){
128     int w_align= 1;
129     int h_align= 1;
130
131     switch(s->pix_fmt){
132     case PIX_FMT_YUV420P:
133     case PIX_FMT_YUYV422:
134     case PIX_FMT_UYVY422:
135     case PIX_FMT_YUV422P:
136     case PIX_FMT_YUV440P:
137     case PIX_FMT_YUV444P:
138     case PIX_FMT_GRAY8:
139     case PIX_FMT_GRAY16BE:
140     case PIX_FMT_GRAY16LE:
141     case PIX_FMT_YUVJ420P:
142     case PIX_FMT_YUVJ422P:
143     case PIX_FMT_YUVJ440P:
144     case PIX_FMT_YUVJ444P:
145     case PIX_FMT_YUVA420P:
146         w_align= 16; //FIXME check for non mpeg style codecs and use less alignment
147         h_align= 16;
148         if(s->codec_id == CODEC_ID_MPEG2VIDEO || s->codec_id == CODEC_ID_MJPEG || s->codec_id == CODEC_ID_AMV || s->codec_id == CODEC_ID_THP || s->codec_id == CODEC_ID_H264)
149             h_align= 32; // interlaced is rounded up to 2 MBs
150         break;
151     case PIX_FMT_YUV411P:
152     case PIX_FMT_UYYVYY411:
153         w_align=32;
154         h_align=8;
155         break;
156     case PIX_FMT_YUV410P:
157         if(s->codec_id == CODEC_ID_SVQ1){
158             w_align=64;
159             h_align=64;
160         }
161     case PIX_FMT_RGB555:
162         if(s->codec_id == CODEC_ID_RPZA){
163             w_align=4;
164             h_align=4;
165         }
166     case PIX_FMT_PAL8:
167     case PIX_FMT_BGR8:
168     case PIX_FMT_RGB8:
169         if(s->codec_id == CODEC_ID_SMC){
170             w_align=4;
171             h_align=4;
172         }
173         break;
174     case PIX_FMT_BGR24:
175         if((s->codec_id == CODEC_ID_MSZH) || (s->codec_id == CODEC_ID_ZLIB)){
176             w_align=4;
177             h_align=4;
178         }
179         break;
180     default:
181         w_align= 1;
182         h_align= 1;
183         break;
184     }
185
186     *width = FFALIGN(*width , w_align);
187     *height= FFALIGN(*height, h_align);
188     if(s->codec_id == CODEC_ID_H264)
189         *height+=2; // some of the optimized chroma MC reads one line too much
190
191     linesize_align[0] =
192     linesize_align[1] =
193     linesize_align[2] =
194     linesize_align[3] = STRIDE_ALIGN;
195 //STRIDE_ALIGN is 8 for SSE* but this does not work for SVQ1 chroma planes
196 //we could change STRIDE_ALIGN to 16 for x86/sse but it would increase the
197 //picture size unneccessarily in some cases. The solution here is not
198 //pretty and better ideas are welcome!
199 #if HAVE_MMX
200     if(s->codec_id == CODEC_ID_SVQ1 || s->codec_id == CODEC_ID_VP5 ||
201        s->codec_id == CODEC_ID_VP6 || s->codec_id == CODEC_ID_VP6F ||
202        s->codec_id == CODEC_ID_VP6A) {
203         linesize_align[0] =
204         linesize_align[1] =
205         linesize_align[2] = 16;
206     }
207 #endif
208 }
209
210 void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height){
211     int chroma_shift = av_pix_fmt_descriptors[s->pix_fmt].log2_chroma_w;
212     int linesize_align[4];
213     int align;
214     avcodec_align_dimensions2(s, width, height, linesize_align);
215     align = FFMAX(linesize_align[0], linesize_align[3]);
216     linesize_align[1] <<= chroma_shift;
217     linesize_align[2] <<= chroma_shift;
218     align = FFMAX3(align, linesize_align[1], linesize_align[2]);
219     *width=FFALIGN(*width, align);
220 }
221
222 #if LIBAVCODEC_VERSION_MAJOR < 53
223 int avcodec_check_dimensions(void *av_log_ctx, unsigned int w, unsigned int h){
224     return av_image_check_size(w, h, 0, av_log_ctx);
225 }
226 #endif
227
228 int avcodec_default_get_buffer(AVCodecContext *s, AVFrame *pic){
229     int i;
230     int w= s->width;
231     int h= s->height;
232     InternalBuffer *buf;
233     int *picture_number;
234
235     if(pic->data[0]!=NULL) {
236         av_log(s, AV_LOG_ERROR, "pic->data[0]!=NULL in avcodec_default_get_buffer\n");
237         return -1;
238     }
239     if(s->internal_buffer_count >= INTERNAL_BUFFER_SIZE) {
240         av_log(s, AV_LOG_ERROR, "internal_buffer_count overflow (missing release_buffer?)\n");
241         return -1;
242     }
243
244     if(av_image_check_size(w, h, 0, s))
245         return -1;
246
247     if(s->internal_buffer==NULL){
248         s->internal_buffer= av_mallocz((INTERNAL_BUFFER_SIZE+1)*sizeof(InternalBuffer));
249     }
250 #if 0
251     s->internal_buffer= av_fast_realloc(
252         s->internal_buffer,
253         &s->internal_buffer_size,
254         sizeof(InternalBuffer)*FFMAX(99,  s->internal_buffer_count+1)/*FIXME*/
255         );
256 #endif
257
258     buf= &((InternalBuffer*)s->internal_buffer)[s->internal_buffer_count];
259     picture_number= &(((InternalBuffer*)s->internal_buffer)[INTERNAL_BUFFER_SIZE]).last_pic_num; //FIXME ugly hack
260     (*picture_number)++;
261
262     if(buf->base[0] && (buf->width != w || buf->height != h || buf->pix_fmt != s->pix_fmt)){
263         for(i=0; i<4; i++){
264             av_freep(&buf->base[i]);
265             buf->data[i]= NULL;
266         }
267     }
268
269     if(buf->base[0]){
270         pic->age= *picture_number - buf->last_pic_num;
271         buf->last_pic_num= *picture_number;
272     }else{
273         int h_chroma_shift, v_chroma_shift;
274         int size[4] = {0};
275         int tmpsize;
276         int unaligned;
277         AVPicture picture;
278         int stride_align[4];
279
280         avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
281
282         avcodec_align_dimensions2(s, &w, &h, stride_align);
283
284         if(!(s->flags&CODEC_FLAG_EMU_EDGE)){
285             w+= EDGE_WIDTH*2;
286             h+= EDGE_WIDTH*2;
287         }
288
289         do {
290             // NOTE: do not align linesizes individually, this breaks e.g. assumptions
291             // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
292             av_image_fill_linesizes(picture.linesize, s->pix_fmt, w);
293             // increase alignment of w for next try (rhs gives the lowest bit set in w)
294             w += w & ~(w-1);
295
296             unaligned = 0;
297             for (i=0; i<4; i++){
298                 unaligned |= picture.linesize[i] % stride_align[i];
299             }
300         } while (unaligned);
301
302         tmpsize = av_image_fill_pointers(picture.data, s->pix_fmt, h, NULL, picture.linesize);
303         if (tmpsize < 0)
304             return -1;
305
306         for (i=0; i<3 && picture.data[i+1]; i++)
307             size[i] = picture.data[i+1] - picture.data[i];
308         size[i] = tmpsize - (picture.data[i] - picture.data[0]);
309
310         buf->last_pic_num= -256*256*256*64;
311         memset(buf->base, 0, sizeof(buf->base));
312         memset(buf->data, 0, sizeof(buf->data));
313
314         for(i=0; i<4 && size[i]; i++){
315             const int h_shift= i==0 ? 0 : h_chroma_shift;
316             const int v_shift= i==0 ? 0 : v_chroma_shift;
317
318             buf->linesize[i]= picture.linesize[i];
319
320             buf->base[i]= av_malloc(size[i]+16); //FIXME 16
321             if(buf->base[i]==NULL) return -1;
322             memset(buf->base[i], 128, size[i]);
323
324             // no edge if EDGE EMU or not planar YUV
325             if((s->flags&CODEC_FLAG_EMU_EDGE) || !size[2])
326                 buf->data[i] = buf->base[i];
327             else
328                 buf->data[i] = buf->base[i] + FFALIGN((buf->linesize[i]*EDGE_WIDTH>>v_shift) + (EDGE_WIDTH>>h_shift), stride_align[i]);
329         }
330         if(size[1] && !size[2])
331             ff_set_systematic_pal2((uint32_t*)buf->data[1], s->pix_fmt);
332         buf->width  = s->width;
333         buf->height = s->height;
334         buf->pix_fmt= s->pix_fmt;
335         pic->age= 256*256*256*64;
336     }
337     pic->type= FF_BUFFER_TYPE_INTERNAL;
338
339     for(i=0; i<4; i++){
340         pic->base[i]= buf->base[i];
341         pic->data[i]= buf->data[i];
342         pic->linesize[i]= buf->linesize[i];
343     }
344     s->internal_buffer_count++;
345
346     pic->reordered_opaque= s->reordered_opaque;
347
348     if(s->debug&FF_DEBUG_BUFFERS)
349         av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p, %d buffers used\n", pic, s->internal_buffer_count);
350
351     return 0;
352 }
353
354 void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic){
355     int i;
356     InternalBuffer *buf, *last;
357
358     assert(pic->type==FF_BUFFER_TYPE_INTERNAL);
359     assert(s->internal_buffer_count);
360
361     buf = NULL; /* avoids warning */
362     for(i=0; i<s->internal_buffer_count; i++){ //just 3-5 checks so is not worth to optimize
363         buf= &((InternalBuffer*)s->internal_buffer)[i];
364         if(buf->data[0] == pic->data[0])
365             break;
366     }
367     assert(i < s->internal_buffer_count);
368     s->internal_buffer_count--;
369     last = &((InternalBuffer*)s->internal_buffer)[s->internal_buffer_count];
370
371     FFSWAP(InternalBuffer, *buf, *last);
372
373     for(i=0; i<4; i++){
374         pic->data[i]=NULL;
375 //        pic->base[i]=NULL;
376     }
377 //printf("R%X\n", pic->opaque);
378
379     if(s->debug&FF_DEBUG_BUFFERS)
380         av_log(s, AV_LOG_DEBUG, "default_release_buffer called on pic %p, %d buffers used\n", pic, s->internal_buffer_count);
381 }
382
383 int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic){
384     AVFrame temp_pic;
385     int i;
386
387     /* If no picture return a new buffer */
388     if(pic->data[0] == NULL) {
389         /* We will copy from buffer, so must be readable */
390         pic->buffer_hints |= FF_BUFFER_HINTS_READABLE;
391         return s->get_buffer(s, pic);
392     }
393
394     /* If internal buffer type return the same buffer */
395     if(pic->type == FF_BUFFER_TYPE_INTERNAL) {
396         pic->reordered_opaque= s->reordered_opaque;
397         return 0;
398     }
399
400     /*
401      * Not internal type and reget_buffer not overridden, emulate cr buffer
402      */
403     temp_pic = *pic;
404     for(i = 0; i < 4; i++)
405         pic->data[i] = pic->base[i] = NULL;
406     pic->opaque = NULL;
407     /* Allocate new frame */
408     if (s->get_buffer(s, pic))
409         return -1;
410     /* Copy image data from old buffer to new buffer */
411     av_picture_copy((AVPicture*)pic, (AVPicture*)&temp_pic, s->pix_fmt, s->width,
412              s->height);
413     s->release_buffer(s, &temp_pic); // Release old frame
414     return 0;
415 }
416
417 int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2),void *arg, int *ret, int count, int size){
418     int i;
419
420     for(i=0; i<count; i++){
421         int r= func(c, (char*)arg + i*size);
422         if(ret) ret[i]= r;
423     }
424     return 0;
425 }
426
427 int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr),void *arg, int *ret, int count){
428     int i;
429
430     for(i=0; i<count; i++){
431         int r= func(c, arg, i, 0);
432         if(ret) ret[i]= r;
433     }
434     return 0;
435 }
436
437 enum PixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum PixelFormat *fmt){
438     while (*fmt != PIX_FMT_NONE && ff_is_hwaccel_pix_fmt(*fmt))
439         ++fmt;
440     return fmt[0];
441 }
442
443 void avcodec_get_frame_defaults(AVFrame *pic){
444     memset(pic, 0, sizeof(AVFrame));
445
446     pic->pts= AV_NOPTS_VALUE;
447     pic->key_frame= 1;
448 }
449
450 AVFrame *avcodec_alloc_frame(void){
451     AVFrame *pic= av_malloc(sizeof(AVFrame));
452
453     if(pic==NULL) return NULL;
454
455     avcodec_get_frame_defaults(pic);
456
457     return pic;
458 }
459
460 int attribute_align_arg avcodec_open(AVCodecContext *avctx, AVCodec *codec)
461 {
462     int ret= -1;
463
464     /* If there is a user-supplied mutex locking routine, call it. */
465     if (ff_lockmgr_cb) {
466         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
467             return -1;
468     }
469
470     entangled_thread_counter++;
471     if(entangled_thread_counter != 1){
472         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
473         goto end;
474     }
475
476     if(avctx->codec || !codec)
477         goto end;
478
479     if (codec->priv_data_size > 0) {
480       if(!avctx->priv_data){
481         avctx->priv_data = av_mallocz(codec->priv_data_size);
482         if (!avctx->priv_data) {
483             ret = AVERROR(ENOMEM);
484             goto end;
485         }
486         if(codec->priv_class){ //this can be droped once all user apps use   avcodec_get_context_defaults3()
487             *(AVClass**)avctx->priv_data= codec->priv_class;
488             av_opt_set_defaults(avctx->priv_data);
489         }
490       }
491     } else {
492         avctx->priv_data = NULL;
493     }
494
495     if(avctx->coded_width && avctx->coded_height)
496         avcodec_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
497     else if(avctx->width && avctx->height)
498         avcodec_set_dimensions(avctx, avctx->width, avctx->height);
499
500     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
501         && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
502            || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {
503         av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");
504         avcodec_set_dimensions(avctx, 0, 0);
505     }
506
507 #define SANE_NB_CHANNELS 128U
508     if (avctx->channels > SANE_NB_CHANNELS) {
509         ret = AVERROR(EINVAL);
510         goto free_and_end;
511     }
512
513     avctx->codec = codec;
514     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
515         avctx->codec_id == CODEC_ID_NONE) {
516         avctx->codec_type = codec->type;
517         avctx->codec_id   = codec->id;
518     }
519     if(avctx->codec_id != codec->id || avctx->codec_type != codec->type){
520         av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");
521         goto free_and_end;
522     }
523     avctx->frame_number = 0;
524     if (avctx->codec->max_lowres < avctx->lowres) {
525         av_log(avctx, AV_LOG_ERROR, "The maximum value for lowres supported by the decoder is %d\n",
526                avctx->codec->max_lowres);
527         goto free_and_end;
528     }
529
530     if(avctx->codec->init){
531         ret = avctx->codec->init(avctx);
532         if (ret < 0) {
533             goto free_and_end;
534         }
535     }
536     ret=0;
537 end:
538     entangled_thread_counter--;
539
540     /* Release any user-supplied mutex. */
541     if (ff_lockmgr_cb) {
542         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
543     }
544     return ret;
545 free_and_end:
546     av_freep(&avctx->priv_data);
547     avctx->codec= NULL;
548     goto end;
549 }
550
551 int attribute_align_arg avcodec_encode_audio(AVCodecContext *avctx, uint8_t *buf, int buf_size,
552                          const short *samples)
553 {
554     if(buf_size < FF_MIN_BUFFER_SIZE && 0){
555         av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
556         return -1;
557     }
558     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || samples){
559         int ret = avctx->codec->encode(avctx, buf, buf_size, samples);
560         avctx->frame_number++;
561         return ret;
562     }else
563         return 0;
564 }
565
566 int attribute_align_arg avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,
567                          const AVFrame *pict)
568 {
569     if(buf_size < FF_MIN_BUFFER_SIZE){
570         av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
571         return -1;
572     }
573     if(av_image_check_size(avctx->width, avctx->height, 0, avctx))
574         return -1;
575     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || pict){
576         int ret = avctx->codec->encode(avctx, buf, buf_size, pict);
577         avctx->frame_number++;
578         emms_c(); //needed to avoid an emms_c() call before every return;
579
580         return ret;
581     }else
582         return 0;
583 }
584
585 int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
586                             const AVSubtitle *sub)
587 {
588     int ret;
589     if(sub->start_display_time) {
590         av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
591         return -1;
592     }
593     if(sub->num_rects == 0 || !sub->rects)
594         return -1;
595     ret = avctx->codec->encode(avctx, buf, buf_size, sub);
596     avctx->frame_number++;
597     return ret;
598 }
599
600 #if FF_API_VIDEO_OLD
601 int attribute_align_arg avcodec_decode_video(AVCodecContext *avctx, AVFrame *picture,
602                          int *got_picture_ptr,
603                          const uint8_t *buf, int buf_size)
604 {
605     AVPacket avpkt;
606     av_init_packet(&avpkt);
607     avpkt.data = buf;
608     avpkt.size = buf_size;
609     // HACK for CorePNG to decode as normal PNG by default
610     avpkt.flags = AV_PKT_FLAG_KEY;
611
612     return avcodec_decode_video2(avctx, picture, got_picture_ptr, &avpkt);
613 }
614 #endif
615
616 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
617                          int *got_picture_ptr,
618                          AVPacket *avpkt)
619 {
620     int ret;
621
622     *got_picture_ptr= 0;
623     if((avctx->coded_width||avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
624         return -1;
625     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size){
626         ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
627                                 avpkt);
628
629         emms_c(); //needed to avoid an emms_c() call before every return;
630
631         if (*got_picture_ptr)
632             avctx->frame_number++;
633     }else
634         ret= 0;
635
636     return ret;
637 }
638
639 #if FF_API_AUDIO_OLD
640 int attribute_align_arg avcodec_decode_audio2(AVCodecContext *avctx, int16_t *samples,
641                          int *frame_size_ptr,
642                          const uint8_t *buf, int buf_size)
643 {
644     AVPacket avpkt;
645     av_init_packet(&avpkt);
646     avpkt.data = buf;
647     avpkt.size = buf_size;
648
649     return avcodec_decode_audio3(avctx, samples, frame_size_ptr, &avpkt);
650 }
651 #endif
652
653 int attribute_align_arg avcodec_decode_audio3(AVCodecContext *avctx, int16_t *samples,
654                          int *frame_size_ptr,
655                          AVPacket *avpkt)
656 {
657     int ret;
658
659     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size){
660         //FIXME remove the check below _after_ ensuring that all audio check that the available space is enough
661         if(*frame_size_ptr < AVCODEC_MAX_AUDIO_FRAME_SIZE){
662             av_log(avctx, AV_LOG_ERROR, "buffer smaller than AVCODEC_MAX_AUDIO_FRAME_SIZE\n");
663             return -1;
664         }
665         if(*frame_size_ptr < FF_MIN_BUFFER_SIZE ||
666         *frame_size_ptr < avctx->channels * avctx->frame_size * sizeof(int16_t)){
667             av_log(avctx, AV_LOG_ERROR, "buffer %d too small\n", *frame_size_ptr);
668             return -1;
669         }
670
671         ret = avctx->codec->decode(avctx, samples, frame_size_ptr, avpkt);
672         avctx->frame_number++;
673     }else{
674         ret= 0;
675         *frame_size_ptr=0;
676     }
677     return ret;
678 }
679
680 #if FF_API_SUBTITLE_OLD
681 int avcodec_decode_subtitle(AVCodecContext *avctx, AVSubtitle *sub,
682                             int *got_sub_ptr,
683                             const uint8_t *buf, int buf_size)
684 {
685     AVPacket avpkt;
686     av_init_packet(&avpkt);
687     avpkt.data = buf;
688     avpkt.size = buf_size;
689
690     return avcodec_decode_subtitle2(avctx, sub, got_sub_ptr, &avpkt);
691 }
692 #endif
693
694 int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
695                             int *got_sub_ptr,
696                             AVPacket *avpkt)
697 {
698     int ret;
699
700     *got_sub_ptr = 0;
701     ret = avctx->codec->decode(avctx, sub, got_sub_ptr, avpkt);
702     if (*got_sub_ptr)
703         avctx->frame_number++;
704     return ret;
705 }
706
707 void avsubtitle_free(AVSubtitle *sub)
708 {
709     int i;
710
711     for (i = 0; i < sub->num_rects; i++)
712     {
713         av_freep(&sub->rects[i]->pict.data[0]);
714         av_freep(&sub->rects[i]->pict.data[1]);
715         av_freep(&sub->rects[i]->pict.data[2]);
716         av_freep(&sub->rects[i]->pict.data[3]);
717         av_freep(&sub->rects[i]->text);
718         av_freep(&sub->rects[i]->ass);
719         av_freep(&sub->rects[i]);
720     }
721
722     av_freep(&sub->rects);
723
724     memset(sub, 0, sizeof(AVSubtitle));
725 }
726
727 av_cold int avcodec_close(AVCodecContext *avctx)
728 {
729     /* If there is a user-supplied mutex locking routine, call it. */
730     if (ff_lockmgr_cb) {
731         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
732             return -1;
733     }
734
735     entangled_thread_counter++;
736     if(entangled_thread_counter != 1){
737         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
738         entangled_thread_counter--;
739         return -1;
740     }
741
742     if (HAVE_THREADS && avctx->thread_opaque)
743         avcodec_thread_free(avctx);
744     if (avctx->codec && avctx->codec->close)
745         avctx->codec->close(avctx);
746     avcodec_default_free_buffers(avctx);
747     avctx->coded_frame = NULL;
748     av_freep(&avctx->priv_data);
749     if(avctx->codec && avctx->codec->encode)
750         av_freep(&avctx->extradata);
751     avctx->codec = NULL;
752     entangled_thread_counter--;
753
754     /* Release any user-supplied mutex. */
755     if (ff_lockmgr_cb) {
756         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
757     }
758     return 0;
759 }
760
761 AVCodec *avcodec_find_encoder(enum CodecID id)
762 {
763     AVCodec *p, *experimental=NULL;
764     p = first_avcodec;
765     while (p) {
766         if (p->encode != NULL && p->id == id) {
767             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {
768                 experimental = p;
769             } else
770                 return p;
771         }
772         p = p->next;
773     }
774     return experimental;
775 }
776
777 AVCodec *avcodec_find_encoder_by_name(const char *name)
778 {
779     AVCodec *p;
780     if (!name)
781         return NULL;
782     p = first_avcodec;
783     while (p) {
784         if (p->encode != NULL && strcmp(name,p->name) == 0)
785             return p;
786         p = p->next;
787     }
788     return NULL;
789 }
790
791 AVCodec *avcodec_find_decoder(enum CodecID id)
792 {
793     AVCodec *p;
794     p = first_avcodec;
795     while (p) {
796         if (p->decode != NULL && p->id == id)
797             return p;
798         p = p->next;
799     }
800     return NULL;
801 }
802
803 AVCodec *avcodec_find_decoder_by_name(const char *name)
804 {
805     AVCodec *p;
806     if (!name)
807         return NULL;
808     p = first_avcodec;
809     while (p) {
810         if (p->decode != NULL && strcmp(name,p->name) == 0)
811             return p;
812         p = p->next;
813     }
814     return NULL;
815 }
816
817 static int get_bit_rate(AVCodecContext *ctx)
818 {
819     int bit_rate;
820     int bits_per_sample;
821
822     switch(ctx->codec_type) {
823     case AVMEDIA_TYPE_VIDEO:
824     case AVMEDIA_TYPE_DATA:
825     case AVMEDIA_TYPE_SUBTITLE:
826     case AVMEDIA_TYPE_ATTACHMENT:
827         bit_rate = ctx->bit_rate;
828         break;
829     case AVMEDIA_TYPE_AUDIO:
830         bits_per_sample = av_get_bits_per_sample(ctx->codec_id);
831         bit_rate = bits_per_sample ? ctx->sample_rate * ctx->channels * bits_per_sample : ctx->bit_rate;
832         break;
833     default:
834         bit_rate = 0;
835         break;
836     }
837     return bit_rate;
838 }
839
840 size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag)
841 {
842     int i, len, ret = 0;
843
844     for (i = 0; i < 4; i++) {
845         len = snprintf(buf, buf_size,
846                        isprint(codec_tag&0xFF) ? "%c" : "[%d]", codec_tag&0xFF);
847         buf      += len;
848         buf_size  = buf_size > len ? buf_size - len : 0;
849         ret      += len;
850         codec_tag>>=8;
851     }
852     return ret;
853 }
854
855 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
856 {
857     const char *codec_name;
858     AVCodec *p;
859     char buf1[32];
860     int bitrate;
861     AVRational display_aspect_ratio;
862
863     if (encode)
864         p = avcodec_find_encoder(enc->codec_id);
865     else
866         p = avcodec_find_decoder(enc->codec_id);
867
868     if (p) {
869         codec_name = p->name;
870     } else if (enc->codec_id == CODEC_ID_MPEG2TS) {
871         /* fake mpeg2 transport stream codec (currently not
872            registered) */
873         codec_name = "mpeg2ts";
874     } else if (enc->codec_name[0] != '\0') {
875         codec_name = enc->codec_name;
876     } else {
877         /* output avi tags */
878         char tag_buf[32];
879         av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
880         snprintf(buf1, sizeof(buf1), "%s / 0x%04X", tag_buf, enc->codec_tag);
881         codec_name = buf1;
882     }
883
884     switch(enc->codec_type) {
885     case AVMEDIA_TYPE_VIDEO:
886         snprintf(buf, buf_size,
887                  "Video: %s%s",
888                  codec_name, enc->mb_decision ? " (hq)" : "");
889         if (enc->pix_fmt != PIX_FMT_NONE) {
890             snprintf(buf + strlen(buf), buf_size - strlen(buf),
891                      ", %s",
892                      avcodec_get_pix_fmt_name(enc->pix_fmt));
893         }
894         if (enc->width) {
895             snprintf(buf + strlen(buf), buf_size - strlen(buf),
896                      ", %dx%d",
897                      enc->width, enc->height);
898             if (enc->sample_aspect_ratio.num) {
899                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
900                           enc->width*enc->sample_aspect_ratio.num,
901                           enc->height*enc->sample_aspect_ratio.den,
902                           1024*1024);
903                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
904                          " [PAR %d:%d DAR %d:%d]",
905                          enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
906                          display_aspect_ratio.num, display_aspect_ratio.den);
907             }
908             if(av_log_get_level() >= AV_LOG_DEBUG){
909                 int g= av_gcd(enc->time_base.num, enc->time_base.den);
910                 snprintf(buf + strlen(buf), buf_size - strlen(buf),
911                      ", %d/%d",
912                      enc->time_base.num/g, enc->time_base.den/g);
913             }
914         }
915         if (encode) {
916             snprintf(buf + strlen(buf), buf_size - strlen(buf),
917                      ", q=%d-%d", enc->qmin, enc->qmax);
918         }
919         break;
920     case AVMEDIA_TYPE_AUDIO:
921         snprintf(buf, buf_size,
922                  "Audio: %s",
923                  codec_name);
924         if (enc->sample_rate) {
925             snprintf(buf + strlen(buf), buf_size - strlen(buf),
926                      ", %d Hz", enc->sample_rate);
927         }
928         av_strlcat(buf, ", ", buf_size);
929         av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
930         if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) {
931             snprintf(buf + strlen(buf), buf_size - strlen(buf),
932                      ", %s", av_get_sample_fmt_name(enc->sample_fmt));
933         }
934         break;
935     case AVMEDIA_TYPE_DATA:
936         snprintf(buf, buf_size, "Data: %s", codec_name);
937         break;
938     case AVMEDIA_TYPE_SUBTITLE:
939         snprintf(buf, buf_size, "Subtitle: %s", codec_name);
940         break;
941     case AVMEDIA_TYPE_ATTACHMENT:
942         snprintf(buf, buf_size, "Attachment: %s", codec_name);
943         break;
944     default:
945         snprintf(buf, buf_size, "Invalid Codec type %d", enc->codec_type);
946         return;
947     }
948     if (encode) {
949         if (enc->flags & CODEC_FLAG_PASS1)
950             snprintf(buf + strlen(buf), buf_size - strlen(buf),
951                      ", pass 1");
952         if (enc->flags & CODEC_FLAG_PASS2)
953             snprintf(buf + strlen(buf), buf_size - strlen(buf),
954                      ", pass 2");
955     }
956     bitrate = get_bit_rate(enc);
957     if (bitrate != 0) {
958         snprintf(buf + strlen(buf), buf_size - strlen(buf),
959                  ", %d kb/s", bitrate / 1000);
960     }
961 }
962
963 unsigned avcodec_version( void )
964 {
965   return LIBAVCODEC_VERSION_INT;
966 }
967
968 const char *avcodec_configuration(void)
969 {
970     return FFMPEG_CONFIGURATION;
971 }
972
973 const char *avcodec_license(void)
974 {
975 #define LICENSE_PREFIX "libavcodec license: "
976     return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
977 }
978
979 void avcodec_init(void)
980 {
981     static int initialized = 0;
982
983     if (initialized != 0)
984         return;
985     initialized = 1;
986
987     dsputil_static_init();
988 }
989
990 void avcodec_flush_buffers(AVCodecContext *avctx)
991 {
992     if(avctx->codec->flush)
993         avctx->codec->flush(avctx);
994 }
995
996 void avcodec_default_free_buffers(AVCodecContext *s){
997     int i, j;
998
999     if(s->internal_buffer==NULL) return;
1000
1001     if (s->internal_buffer_count)
1002         av_log(s, AV_LOG_WARNING, "Found %i unreleased buffers!\n", s->internal_buffer_count);
1003     for(i=0; i<INTERNAL_BUFFER_SIZE; i++){
1004         InternalBuffer *buf= &((InternalBuffer*)s->internal_buffer)[i];
1005         for(j=0; j<4; j++){
1006             av_freep(&buf->base[j]);
1007             buf->data[j]= NULL;
1008         }
1009     }
1010     av_freep(&s->internal_buffer);
1011
1012     s->internal_buffer_count=0;
1013 }
1014
1015 char av_get_pict_type_char(int pict_type){
1016     switch(pict_type){
1017     case FF_I_TYPE: return 'I';
1018     case FF_P_TYPE: return 'P';
1019     case FF_B_TYPE: return 'B';
1020     case FF_S_TYPE: return 'S';
1021     case FF_SI_TYPE:return 'i';
1022     case FF_SP_TYPE:return 'p';
1023     case FF_BI_TYPE:return 'b';
1024     default:        return '?';
1025     }
1026 }
1027
1028 int av_get_bits_per_sample(enum CodecID codec_id){
1029     switch(codec_id){
1030     case CODEC_ID_ADPCM_SBPRO_2:
1031         return 2;
1032     case CODEC_ID_ADPCM_SBPRO_3:
1033         return 3;
1034     case CODEC_ID_ADPCM_SBPRO_4:
1035     case CODEC_ID_ADPCM_CT:
1036     case CODEC_ID_ADPCM_IMA_WAV:
1037     case CODEC_ID_ADPCM_MS:
1038     case CODEC_ID_ADPCM_YAMAHA:
1039         return 4;
1040     case CODEC_ID_PCM_ALAW:
1041     case CODEC_ID_PCM_MULAW:
1042     case CODEC_ID_PCM_S8:
1043     case CODEC_ID_PCM_U8:
1044     case CODEC_ID_PCM_ZORK:
1045         return 8;
1046     case CODEC_ID_PCM_S16BE:
1047     case CODEC_ID_PCM_S16LE:
1048     case CODEC_ID_PCM_S16LE_PLANAR:
1049     case CODEC_ID_PCM_U16BE:
1050     case CODEC_ID_PCM_U16LE:
1051         return 16;
1052     case CODEC_ID_PCM_S24DAUD:
1053     case CODEC_ID_PCM_S24BE:
1054     case CODEC_ID_PCM_S24LE:
1055     case CODEC_ID_PCM_U24BE:
1056     case CODEC_ID_PCM_U24LE:
1057         return 24;
1058     case CODEC_ID_PCM_S32BE:
1059     case CODEC_ID_PCM_S32LE:
1060     case CODEC_ID_PCM_U32BE:
1061     case CODEC_ID_PCM_U32LE:
1062     case CODEC_ID_PCM_F32BE:
1063     case CODEC_ID_PCM_F32LE:
1064         return 32;
1065     case CODEC_ID_PCM_F64BE:
1066     case CODEC_ID_PCM_F64LE:
1067         return 64;
1068     default:
1069         return 0;
1070     }
1071 }
1072
1073 #if FF_API_OLD_SAMPLE_FMT
1074 int av_get_bits_per_sample_format(enum AVSampleFormat sample_fmt) {
1075     return av_get_bits_per_sample_fmt(sample_fmt);
1076 }
1077 #endif
1078
1079 #if !HAVE_THREADS
1080 int avcodec_thread_init(AVCodecContext *s, int thread_count){
1081     s->thread_count = thread_count;
1082     return -1;
1083 }
1084 #endif
1085
1086 unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
1087 {
1088     unsigned int n = 0;
1089
1090     while(v >= 0xff) {
1091         *s++ = 0xff;
1092         v -= 0xff;
1093         n++;
1094     }
1095     *s = v;
1096     n++;
1097     return n;
1098 }
1099
1100 #if LIBAVCODEC_VERSION_MAJOR < 53
1101 #include "libavcore/parseutils.h"
1102
1103 int av_parse_video_frame_size(int *width_ptr, int *height_ptr, const char *str)
1104 {
1105     return av_parse_video_size(width_ptr, height_ptr, str);
1106 }
1107
1108 int av_parse_video_frame_rate(AVRational *frame_rate, const char *arg)
1109 {
1110     return av_parse_video_rate(frame_rate, arg);
1111 }
1112 #endif
1113
1114 int ff_match_2uint16(const uint16_t (*tab)[2], int size, int a, int b){
1115     int i;
1116     for(i=0; i<size && !(tab[i][0]==a && tab[i][1]==b); i++);
1117     return i;
1118 }
1119
1120 void av_log_missing_feature(void *avc, const char *feature, int want_sample)
1121 {
1122     av_log(avc, AV_LOG_WARNING, "%s not implemented. Update your FFmpeg "
1123             "version to the newest one from SVN. If the problem still "
1124             "occurs, it means that your file has a feature which has not "
1125             "been implemented.", feature);
1126     if(want_sample)
1127         av_log_ask_for_sample(avc, NULL);
1128     else
1129         av_log(avc, AV_LOG_WARNING, "\n");
1130 }
1131
1132 void av_log_ask_for_sample(void *avc, const char *msg)
1133 {
1134     if (msg)
1135         av_log(avc, AV_LOG_WARNING, "%s ", msg);
1136     av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
1137             "of this file to ftp://upload.ffmpeg.org/MPlayer/incoming/ "
1138             "and contact the ffmpeg-devel mailing list.\n");
1139 }
1140
1141 static AVHWAccel *first_hwaccel = NULL;
1142
1143 void av_register_hwaccel(AVHWAccel *hwaccel)
1144 {
1145     AVHWAccel **p = &first_hwaccel;
1146     while (*p)
1147         p = &(*p)->next;
1148     *p = hwaccel;
1149     hwaccel->next = NULL;
1150 }
1151
1152 AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel)
1153 {
1154     return hwaccel ? hwaccel->next : first_hwaccel;
1155 }
1156
1157 AVHWAccel *ff_find_hwaccel(enum CodecID codec_id, enum PixelFormat pix_fmt)
1158 {
1159     AVHWAccel *hwaccel=NULL;
1160
1161     while((hwaccel= av_hwaccel_next(hwaccel))){
1162         if (   hwaccel->id      == codec_id
1163             && hwaccel->pix_fmt == pix_fmt)
1164             return hwaccel;
1165     }
1166     return NULL;
1167 }
1168
1169 int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
1170 {
1171     if (ff_lockmgr_cb) {
1172         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_DESTROY))
1173             return -1;
1174     }
1175
1176     ff_lockmgr_cb = cb;
1177
1178     if (ff_lockmgr_cb) {
1179         if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_CREATE))
1180             return -1;
1181     }
1182     return 0;
1183 }
1184
1185 unsigned int ff_toupper4(unsigned int x)
1186 {
1187     return     toupper( x     &0xFF)
1188             + (toupper((x>>8 )&0xFF)<<8 )
1189             + (toupper((x>>16)&0xFF)<<16)
1190             + (toupper((x>>24)&0xFF)<<24);
1191 }