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 libavcodec/utils.c
25 * utils.
26 */
27
28/* needed for mkstemp() */
29#define _XOPEN_SOURCE 600
30
31#include "libavutil/avstring.h"
32#include "libavutil/integer.h"
33#include "libavutil/crc.h"
34#include "avcodec.h"
35#include "dsputil.h"
36#include "opt.h"
37#include "imgconvert.h"
38#include "audioconvert.h"
39#include "internal.h"
40#include <stdlib.h>
41#include <stdarg.h>
42#include <limits.h>
43#include <float.h>
44#if !HAVE_MKSTEMP
45#include <fcntl.h>
46#endif
47
48const uint8_t ff_reverse[256]={
490x00,0x80,0x40,0xC0,0x20,0xA0,0x60,0xE0,0x10,0x90,0x50,0xD0,0x30,0xB0,0x70,0xF0,
500x08,0x88,0x48,0xC8,0x28,0xA8,0x68,0xE8,0x18,0x98,0x58,0xD8,0x38,0xB8,0x78,0xF8,
510x04,0x84,0x44,0xC4,0x24,0xA4,0x64,0xE4,0x14,0x94,0x54,0xD4,0x34,0xB4,0x74,0xF4,
520x0C,0x8C,0x4C,0xCC,0x2C,0xAC,0x6C,0xEC,0x1C,0x9C,0x5C,0xDC,0x3C,0xBC,0x7C,0xFC,
530x02,0x82,0x42,0xC2,0x22,0xA2,0x62,0xE2,0x12,0x92,0x52,0xD2,0x32,0xB2,0x72,0xF2,
540x0A,0x8A,0x4A,0xCA,0x2A,0xAA,0x6A,0xEA,0x1A,0x9A,0x5A,0xDA,0x3A,0xBA,0x7A,0xFA,
550x06,0x86,0x46,0xC6,0x26,0xA6,0x66,0xE6,0x16,0x96,0x56,0xD6,0x36,0xB6,0x76,0xF6,
560x0E,0x8E,0x4E,0xCE,0x2E,0xAE,0x6E,0xEE,0x1E,0x9E,0x5E,0xDE,0x3E,0xBE,0x7E,0xFE,
570x01,0x81,0x41,0xC1,0x21,0xA1,0x61,0xE1,0x11,0x91,0x51,0xD1,0x31,0xB1,0x71,0xF1,
580x09,0x89,0x49,0xC9,0x29,0xA9,0x69,0xE9,0x19,0x99,0x59,0xD9,0x39,0xB9,0x79,0xF9,
590x05,0x85,0x45,0xC5,0x25,0xA5,0x65,0xE5,0x15,0x95,0x55,0xD5,0x35,0xB5,0x75,0xF5,
600x0D,0x8D,0x4D,0xCD,0x2D,0xAD,0x6D,0xED,0x1D,0x9D,0x5D,0xDD,0x3D,0xBD,0x7D,0xFD,
610x03,0x83,0x43,0xC3,0x23,0xA3,0x63,0xE3,0x13,0x93,0x53,0xD3,0x33,0xB3,0x73,0xF3,
620x0B,0x8B,0x4B,0xCB,0x2B,0xAB,0x6B,0xEB,0x1B,0x9B,0x5B,0xDB,0x3B,0xBB,0x7B,0xFB,
630x07,0x87,0x47,0xC7,0x27,0xA7,0x67,0xE7,0x17,0x97,0x57,0xD7,0x37,0xB7,0x77,0xF7,
640x0F,0x8F,0x4F,0xCF,0x2F,0xAF,0x6F,0xEF,0x1F,0x9F,0x5F,0xDF,0x3F,0xBF,0x7F,0xFF,
65};
66
67static int volatile entangled_thread_counter=0;
68int (*ff_lockmgr_cb)(void **mutex, enum AVLockOp op);
69static void *codec_mutex;
70
71void *av_fast_realloc(void *ptr, unsigned int *size, unsigned int min_size)
72{
73    if(min_size < *size)
74        return ptr;
75
76    *size= FFMAX(17*min_size/16 + 32, min_size);
77
78    ptr= av_realloc(ptr, *size);
79    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
80        *size= 0;
81
82    return ptr;
83}
84
85/* encoder management */
86static AVCodec *first_avcodec = NULL;
87
88AVCodec *av_codec_next(AVCodec *c){
89    if(c) return c->next;
90    else  return first_avcodec;
91}
92
93void avcodec_register(AVCodec *codec)
94{
95    AVCodec **p;
96    avcodec_init();
97    p = &first_avcodec;
98    while (*p != NULL) p = &(*p)->next;
99    *p = codec;
100    codec->next = NULL;
101}
102
103#if LIBAVCODEC_VERSION_MAJOR < 53
104void register_avcodec(AVCodec *codec)
105{
106    avcodec_register(codec);
107}
108#endif
109
110void avcodec_set_dimensions(AVCodecContext *s, int width, int height){
111    s->coded_width = width;
112    s->coded_height= height;
113    s->width = -((-width )>>s->lowres);
114    s->height= -((-height)>>s->lowres);
115}
116
117typedef struct InternalBuffer{
118    int last_pic_num;
119    uint8_t *base[4];
120    uint8_t *data[4];
121    int linesize[4];
122    int width, height;
123    enum PixelFormat pix_fmt;
124}InternalBuffer;
125
126#define INTERNAL_BUFFER_SIZE 32
127
128#define ALIGN(x, a) (((x)+(a)-1)&~((a)-1))
129
130void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height){
131    int w_align= 1;
132    int h_align= 1;
133
134    switch(s->pix_fmt){
135    case PIX_FMT_YUV420P:
136    case PIX_FMT_YUYV422:
137    case PIX_FMT_UYVY422:
138    case PIX_FMT_YUV422P:
139    case PIX_FMT_YUV444P:
140    case PIX_FMT_GRAY8:
141    case PIX_FMT_GRAY16BE:
142    case PIX_FMT_GRAY16LE:
143    case PIX_FMT_YUVJ420P:
144    case PIX_FMT_YUVJ422P:
145    case PIX_FMT_YUVJ444P:
146    case PIX_FMT_YUVA420P:
147        w_align= 16; //FIXME check for non mpeg style codecs and use less alignment
148        h_align= 16;
149        break;
150    case PIX_FMT_YUV411P:
151    case PIX_FMT_UYYVYY411:
152        w_align=32;
153        h_align=8;
154        break;
155    case PIX_FMT_YUV410P:
156        if(s->codec_id == CODEC_ID_SVQ1){
157            w_align=64;
158            h_align=64;
159        }
160    case PIX_FMT_RGB555:
161        if(s->codec_id == CODEC_ID_RPZA){
162            w_align=4;
163            h_align=4;
164        }
165    case PIX_FMT_PAL8:
166    case PIX_FMT_BGR8:
167    case PIX_FMT_RGB8:
168        if(s->codec_id == CODEC_ID_SMC){
169            w_align=4;
170            h_align=4;
171        }
172        break;
173    case PIX_FMT_BGR24:
174        if((s->codec_id == CODEC_ID_MSZH) || (s->codec_id == CODEC_ID_ZLIB)){
175            w_align=4;
176            h_align=4;
177        }
178        break;
179    default:
180        w_align= 1;
181        h_align= 1;
182        break;
183    }
184
185    *width = ALIGN(*width , w_align);
186    *height= ALIGN(*height, h_align);
187    if(s->codec_id == CODEC_ID_H264)
188        *height+=2; // some of the optimized chroma MC reads one line too much
189}
190
191int avcodec_check_dimensions(void *av_log_ctx, unsigned int w, unsigned int h){
192    if((int)w>0 && (int)h>0 && (w+128)*(uint64_t)(h+128) < INT_MAX/4)
193        return 0;
194
195    av_log(av_log_ctx, AV_LOG_ERROR, "picture size invalid (%ux%u)\n", w, h);
196    return -1;
197}
198
199int avcodec_default_get_buffer(AVCodecContext *s, AVFrame *pic){
200    int i;
201    int w= s->width;
202    int h= s->height;
203    InternalBuffer *buf;
204    int *picture_number;
205
206    if(pic->data[0]!=NULL) {
207        av_log(s, AV_LOG_ERROR, "pic->data[0]!=NULL in avcodec_default_get_buffer\n");
208        return -1;
209    }
210    if(s->internal_buffer_count >= INTERNAL_BUFFER_SIZE) {
211        av_log(s, AV_LOG_ERROR, "internal_buffer_count overflow (missing release_buffer?)\n");
212        return -1;
213    }
214
215    if(avcodec_check_dimensions(s,w,h))
216        return -1;
217
218    if(s->internal_buffer==NULL){
219        s->internal_buffer= av_mallocz((INTERNAL_BUFFER_SIZE+1)*sizeof(InternalBuffer));
220    }
221#if 0
222    s->internal_buffer= av_fast_realloc(
223        s->internal_buffer,
224        &s->internal_buffer_size,
225        sizeof(InternalBuffer)*FFMAX(99,  s->internal_buffer_count+1)/*FIXME*/
226        );
227#endif
228
229    buf= &((InternalBuffer*)s->internal_buffer)[s->internal_buffer_count];
230    picture_number= &(((InternalBuffer*)s->internal_buffer)[INTERNAL_BUFFER_SIZE]).last_pic_num; //FIXME ugly hack
231    (*picture_number)++;
232
233    if(buf->base[0] && (buf->width != w || buf->height != h || buf->pix_fmt != s->pix_fmt)){
234        for(i=0; i<4; i++){
235            av_freep(&buf->base[i]);
236            buf->data[i]= NULL;
237        }
238    }
239
240    if(buf->base[0]){
241        pic->age= *picture_number - buf->last_pic_num;
242        buf->last_pic_num= *picture_number;
243    }else{
244        int h_chroma_shift, v_chroma_shift;
245        int size[4] = {0};
246        int tmpsize;
247        AVPicture picture;
248        int stride_align[4];
249
250        avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
251
252        avcodec_align_dimensions(s, &w, &h);
253
254        if(!(s->flags&CODEC_FLAG_EMU_EDGE)){
255            w+= EDGE_WIDTH*2;
256            h+= EDGE_WIDTH*2;
257        }
258
259        ff_fill_linesize(&picture, s->pix_fmt, w);
260
261        for (i=0; i<4; i++){
262//STRIDE_ALIGN is 8 for SSE* but this does not work for SVQ1 chroma planes
263//we could change STRIDE_ALIGN to 16 for x86/sse but it would increase the
264//picture size unneccessarily in some cases. The solution here is not
265//pretty and better ideas are welcome!
266#if HAVE_MMX
267            if(s->codec_id == CODEC_ID_SVQ1)
268                stride_align[i]= 16;
269            else
270#endif
271            stride_align[i] = STRIDE_ALIGN;
272            picture.linesize[i] = ALIGN(picture.linesize[i], stride_align[i]);
273        }
274
275        tmpsize = ff_fill_pointer(&picture, NULL, s->pix_fmt, h);
276        if (tmpsize < 0)
277            return -1;
278
279        for (i=0; i<3 && picture.data[i+1]; i++)
280            size[i] = picture.data[i+1] - picture.data[i];
281        size[i] = tmpsize - (picture.data[i] - picture.data[0]);
282
283        buf->last_pic_num= -256*256*256*64;
284        memset(buf->base, 0, sizeof(buf->base));
285        memset(buf->data, 0, sizeof(buf->data));
286
287        for(i=0; i<4 && size[i]; i++){
288            const int h_shift= i==0 ? 0 : h_chroma_shift;
289            const int v_shift= i==0 ? 0 : v_chroma_shift;
290
291            buf->linesize[i]= picture.linesize[i];
292
293            buf->base[i]= av_malloc(size[i]+16); //FIXME 16
294            if(buf->base[i]==NULL) return -1;
295            memset(buf->base[i], 128, size[i]);
296
297            // no edge if EDEG EMU or not planar YUV
298            if((s->flags&CODEC_FLAG_EMU_EDGE) || !size[2])
299                buf->data[i] = buf->base[i];
300            else
301                buf->data[i] = buf->base[i] + ALIGN((buf->linesize[i]*EDGE_WIDTH>>v_shift) + (EDGE_WIDTH>>h_shift), stride_align[i]);
302        }
303        if(size[1] && !size[2])
304            ff_set_systematic_pal((uint32_t*)buf->data[1], s->pix_fmt);
305        buf->width  = s->width;
306        buf->height = s->height;
307        buf->pix_fmt= s->pix_fmt;
308        pic->age= 256*256*256*64;
309    }
310    pic->type= FF_BUFFER_TYPE_INTERNAL;
311
312    for(i=0; i<4; i++){
313        pic->base[i]= buf->base[i];
314        pic->data[i]= buf->data[i];
315        pic->linesize[i]= buf->linesize[i];
316    }
317    s->internal_buffer_count++;
318
319    pic->reordered_opaque= s->reordered_opaque;
320
321    if(s->debug&FF_DEBUG_BUFFERS)
322        av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p, %d buffers used\n", pic, s->internal_buffer_count);
323
324    return 0;
325}
326
327void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic){
328    int i;
329    InternalBuffer *buf, *last;
330
331    assert(pic->type==FF_BUFFER_TYPE_INTERNAL);
332    assert(s->internal_buffer_count);
333
334    buf = NULL; /* avoids warning */
335    for(i=0; i<s->internal_buffer_count; i++){ //just 3-5 checks so is not worth to optimize
336        buf= &((InternalBuffer*)s->internal_buffer)[i];
337        if(buf->data[0] == pic->data[0])
338            break;
339    }
340    assert(i < s->internal_buffer_count);
341    s->internal_buffer_count--;
342    last = &((InternalBuffer*)s->internal_buffer)[s->internal_buffer_count];
343
344    FFSWAP(InternalBuffer, *buf, *last);
345
346    for(i=0; i<4; i++){
347        pic->data[i]=NULL;
348//        pic->base[i]=NULL;
349    }
350//printf("R%X\n", pic->opaque);
351
352    if(s->debug&FF_DEBUG_BUFFERS)
353        av_log(s, AV_LOG_DEBUG, "default_release_buffer called on pic %p, %d buffers used\n", pic, s->internal_buffer_count);
354}
355
356int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic){
357    AVFrame temp_pic;
358    int i;
359
360    /* If no picture return a new buffer */
361    if(pic->data[0] == NULL) {
362        /* We will copy from buffer, so must be readable */
363        pic->buffer_hints |= FF_BUFFER_HINTS_READABLE;
364        return s->get_buffer(s, pic);
365    }
366
367    /* If internal buffer type return the same buffer */
368    if(pic->type == FF_BUFFER_TYPE_INTERNAL)
369        return 0;
370
371    /*
372     * Not internal type and reget_buffer not overridden, emulate cr buffer
373     */
374    temp_pic = *pic;
375    for(i = 0; i < 4; i++)
376        pic->data[i] = pic->base[i] = NULL;
377    pic->opaque = NULL;
378    /* Allocate new frame */
379    if (s->get_buffer(s, pic))
380        return -1;
381    /* Copy image data from old buffer to new buffer */
382    av_picture_copy((AVPicture*)pic, (AVPicture*)&temp_pic, s->pix_fmt, s->width,
383             s->height);
384    s->release_buffer(s, &temp_pic); // Release old frame
385    return 0;
386}
387
388int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2),void *arg, int *ret, int count, int size){
389    int i;
390
391    for(i=0; i<count; i++){
392        int r= func(c, (char*)arg + i*size);
393        if(ret) ret[i]= r;
394    }
395    return 0;
396}
397
398enum PixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum PixelFormat *fmt){
399    while (*fmt != PIX_FMT_NONE && ff_is_hwaccel_pix_fmt(*fmt))
400        ++fmt;
401    return fmt[0];
402}
403
404void avcodec_get_frame_defaults(AVFrame *pic){
405    memset(pic, 0, sizeof(AVFrame));
406
407    pic->pts= AV_NOPTS_VALUE;
408    pic->key_frame= 1;
409}
410
411AVFrame *avcodec_alloc_frame(void){
412    AVFrame *pic= av_malloc(sizeof(AVFrame));
413
414    if(pic==NULL) return NULL;
415
416    avcodec_get_frame_defaults(pic);
417
418    return pic;
419}
420
421int attribute_align_arg avcodec_open(AVCodecContext *avctx, AVCodec *codec)
422{
423    int ret= -1;
424
425    /* If there is a user-supplied mutex locking routine, call it. */
426    if (ff_lockmgr_cb) {
427        if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
428            return -1;
429    }
430
431    entangled_thread_counter++;
432    if(entangled_thread_counter != 1){
433        av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
434        goto end;
435    }
436
437    if(avctx->codec || !codec)
438        goto end;
439
440    if (codec->priv_data_size > 0) {
441        avctx->priv_data = av_mallocz(codec->priv_data_size);
442        if (!avctx->priv_data) {
443            ret = AVERROR(ENOMEM);
444            goto end;
445        }
446    } else {
447        avctx->priv_data = NULL;
448    }
449
450    if(avctx->coded_width && avctx->coded_height)
451        avcodec_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
452    else if(avctx->width && avctx->height)
453        avcodec_set_dimensions(avctx, avctx->width, avctx->height);
454
455    if((avctx->coded_width||avctx->coded_height) && avcodec_check_dimensions(avctx,avctx->coded_width,avctx->coded_height)){
456        av_freep(&avctx->priv_data);
457        ret = AVERROR(EINVAL);
458        goto end;
459    }
460
461    avctx->codec = codec;
462    avctx->codec_id = codec->id;
463    avctx->frame_number = 0;
464    if(avctx->codec->init){
465        ret = avctx->codec->init(avctx);
466        if (ret < 0) {
467            av_freep(&avctx->priv_data);
468            avctx->codec= NULL;
469            goto end;
470        }
471    }
472    ret=0;
473end:
474    entangled_thread_counter--;
475
476    /* Release any user-supplied mutex. */
477    if (ff_lockmgr_cb) {
478        (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
479    }
480    return ret;
481}
482
483int attribute_align_arg avcodec_encode_audio(AVCodecContext *avctx, uint8_t *buf, int buf_size,
484                         const short *samples)
485{
486    if(buf_size < FF_MIN_BUFFER_SIZE && 0){
487        av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
488        return -1;
489    }
490    if((avctx->codec->capabilities & CODEC_CAP_DELAY) || samples){
491        int ret = avctx->codec->encode(avctx, buf, buf_size, samples);
492        avctx->frame_number++;
493        return ret;
494    }else
495        return 0;
496}
497
498int attribute_align_arg avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,
499                         const AVFrame *pict)
500{
501    if(buf_size < FF_MIN_BUFFER_SIZE){
502        av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");
503        return -1;
504    }
505    if(avcodec_check_dimensions(avctx,avctx->width,avctx->height))
506        return -1;
507    if((avctx->codec->capabilities & CODEC_CAP_DELAY) || pict){
508        int ret = avctx->codec->encode(avctx, buf, buf_size, pict);
509        avctx->frame_number++;
510        emms_c(); //needed to avoid an emms_c() call before every return;
511
512        return ret;
513    }else
514        return 0;
515}
516
517int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
518                            const AVSubtitle *sub)
519{
520    int ret;
521    if(sub->start_display_time) {
522        av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
523        return -1;
524    }
525    if(sub->num_rects == 0 || !sub->rects)
526        return -1;
527    ret = avctx->codec->encode(avctx, buf, buf_size, sub);
528    avctx->frame_number++;
529    return ret;
530}
531
532int attribute_align_arg avcodec_decode_video(AVCodecContext *avctx, AVFrame *picture,
533                         int *got_picture_ptr,
534                         const uint8_t *buf, int buf_size)
535{
536    int ret;
537
538    *got_picture_ptr= 0;
539    if((avctx->coded_width||avctx->coded_height) && avcodec_check_dimensions(avctx,avctx->coded_width,avctx->coded_height))
540        return -1;
541    if((avctx->codec->capabilities & CODEC_CAP_DELAY) || buf_size){
542        ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
543                                buf, buf_size);
544
545        emms_c(); //needed to avoid an emms_c() call before every return;
546
547        if (*got_picture_ptr)
548            avctx->frame_number++;
549    }else
550        ret= 0;
551
552    return ret;
553}
554
555int attribute_align_arg avcodec_decode_audio2(AVCodecContext *avctx, int16_t *samples,
556                         int *frame_size_ptr,
557                         const uint8_t *buf, int buf_size)
558{
559    int ret;
560
561    if((avctx->codec->capabilities & CODEC_CAP_DELAY) || buf_size){
562        //FIXME remove the check below _after_ ensuring that all audio check that the available space is enough
563        if(*frame_size_ptr < AVCODEC_MAX_AUDIO_FRAME_SIZE){
564            av_log(avctx, AV_LOG_ERROR, "buffer smaller than AVCODEC_MAX_AUDIO_FRAME_SIZE\n");
565            return -1;
566        }
567        if(*frame_size_ptr < FF_MIN_BUFFER_SIZE ||
568        *frame_size_ptr < avctx->channels * avctx->frame_size * sizeof(int16_t)){
569            av_log(avctx, AV_LOG_ERROR, "buffer %d too small\n", *frame_size_ptr);
570            return -1;
571        }
572
573        ret = avctx->codec->decode(avctx, samples, frame_size_ptr,
574                                buf, buf_size);
575        avctx->frame_number++;
576    }else{
577        ret= 0;
578        *frame_size_ptr=0;
579    }
580    return ret;
581}
582
583int avcodec_decode_subtitle(AVCodecContext *avctx, AVSubtitle *sub,
584                            int *got_sub_ptr,
585                            const uint8_t *buf, int buf_size)
586{
587    int ret;
588
589    *got_sub_ptr = 0;
590    ret = avctx->codec->decode(avctx, sub, got_sub_ptr,
591                               buf, buf_size);
592    if (*got_sub_ptr)
593        avctx->frame_number++;
594    return ret;
595}
596
597int avcodec_close(AVCodecContext *avctx)
598{
599    /* If there is a user-supplied mutex locking routine, call it. */
600    if (ff_lockmgr_cb) {
601        if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))
602            return -1;
603    }
604
605    entangled_thread_counter++;
606    if(entangled_thread_counter != 1){
607        av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");
608        entangled_thread_counter--;
609        return -1;
610    }
611
612    if (HAVE_THREADS && avctx->thread_opaque)
613        avcodec_thread_free(avctx);
614    if (avctx->codec->close)
615        avctx->codec->close(avctx);
616    avcodec_default_free_buffers(avctx);
617    av_freep(&avctx->priv_data);
618    avctx->codec = NULL;
619    entangled_thread_counter--;
620
621    /* Release any user-supplied mutex. */
622    if (ff_lockmgr_cb) {
623        (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);
624    }
625    return 0;
626}
627
628AVCodec *avcodec_find_encoder(enum CodecID id)
629{
630    AVCodec *p;
631    p = first_avcodec;
632    while (p) {
633        if (p->encode != NULL && p->id == id)
634            return p;
635        p = p->next;
636    }
637    return NULL;
638}
639
640AVCodec *avcodec_find_encoder_by_name(const char *name)
641{
642    AVCodec *p;
643    if (!name)
644        return NULL;
645    p = first_avcodec;
646    while (p) {
647        if (p->encode != NULL && strcmp(name,p->name) == 0)
648            return p;
649        p = p->next;
650    }
651    return NULL;
652}
653
654AVCodec *avcodec_find_decoder(enum CodecID id)
655{
656    AVCodec *p;
657    p = first_avcodec;
658    while (p) {
659        if (p->decode != NULL && p->id == id)
660            return p;
661        p = p->next;
662    }
663    return NULL;
664}
665
666AVCodec *avcodec_find_decoder_by_name(const char *name)
667{
668    AVCodec *p;
669    if (!name)
670        return NULL;
671    p = first_avcodec;
672    while (p) {
673        if (p->decode != NULL && strcmp(name,p->name) == 0)
674            return p;
675        p = p->next;
676    }
677    return NULL;
678}
679
680void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
681{
682    const char *codec_name;
683    AVCodec *p;
684    char buf1[32];
685    int bitrate;
686    AVRational display_aspect_ratio;
687
688    if (encode)
689        p = avcodec_find_encoder(enc->codec_id);
690    else
691        p = avcodec_find_decoder(enc->codec_id);
692
693    if (p) {
694        codec_name = p->name;
695    } else if (enc->codec_id == CODEC_ID_MPEG2TS) {
696        /* fake mpeg2 transport stream codec (currently not
697           registered) */
698        codec_name = "mpeg2ts";
699    } else if (enc->codec_name[0] != '\0') {
700        codec_name = enc->codec_name;
701    } else {
702        /* output avi tags */
703        if(   isprint(enc->codec_tag&0xFF) && isprint((enc->codec_tag>>8)&0xFF)
704           && isprint((enc->codec_tag>>16)&0xFF) && isprint((enc->codec_tag>>24)&0xFF)){
705            snprintf(buf1, sizeof(buf1), "%c%c%c%c / 0x%04X",
706                     enc->codec_tag & 0xff,
707                     (enc->codec_tag >> 8) & 0xff,
708                     (enc->codec_tag >> 16) & 0xff,
709                     (enc->codec_tag >> 24) & 0xff,
710                      enc->codec_tag);
711        } else {
712            snprintf(buf1, sizeof(buf1), "0x%04x", enc->codec_tag);
713        }
714        codec_name = buf1;
715    }
716
717    switch(enc->codec_type) {
718    case CODEC_TYPE_VIDEO:
719        snprintf(buf, buf_size,
720                 "Video: %s%s",
721                 codec_name, enc->mb_decision ? " (hq)" : "");
722        if (enc->pix_fmt != PIX_FMT_NONE) {
723            snprintf(buf + strlen(buf), buf_size - strlen(buf),
724                     ", %s",
725                     avcodec_get_pix_fmt_name(enc->pix_fmt));
726        }
727        if (enc->width) {
728            snprintf(buf + strlen(buf), buf_size - strlen(buf),
729                     ", %dx%d",
730                     enc->width, enc->height);
731            if (enc->sample_aspect_ratio.num) {
732                av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
733                          enc->width*enc->sample_aspect_ratio.num,
734                          enc->height*enc->sample_aspect_ratio.den,
735                          1024*1024);
736                snprintf(buf + strlen(buf), buf_size - strlen(buf),
737                         " [PAR %d:%d DAR %d:%d]",
738                         enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den,
739                         display_aspect_ratio.num, display_aspect_ratio.den);
740            }
741            if(av_log_get_level() >= AV_LOG_DEBUG){
742                int g= av_gcd(enc->time_base.num, enc->time_base.den);
743                snprintf(buf + strlen(buf), buf_size - strlen(buf),
744                     ", %d/%d",
745                     enc->time_base.num/g, enc->time_base.den/g);
746            }
747        }
748        if (encode) {
749            snprintf(buf + strlen(buf), buf_size - strlen(buf),
750                     ", q=%d-%d", enc->qmin, enc->qmax);
751        }
752        bitrate = enc->bit_rate;
753        break;
754    case CODEC_TYPE_AUDIO:
755        snprintf(buf, buf_size,
756                 "Audio: %s",
757                 codec_name);
758        if (enc->sample_rate) {
759            snprintf(buf + strlen(buf), buf_size - strlen(buf),
760                     ", %d Hz", enc->sample_rate);
761        }
762        av_strlcat(buf, ", ", buf_size);
763        avcodec_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout);
764        if (enc->sample_fmt != SAMPLE_FMT_NONE) {
765            snprintf(buf + strlen(buf), buf_size - strlen(buf),
766                     ", %s", avcodec_get_sample_fmt_name(enc->sample_fmt));
767        }
768
769        /* for PCM codecs, compute bitrate directly */
770        switch(enc->codec_id) {
771        case CODEC_ID_PCM_F64BE:
772        case CODEC_ID_PCM_F64LE:
773            bitrate = enc->sample_rate * enc->channels * 64;
774            break;
775        case CODEC_ID_PCM_S32LE:
776        case CODEC_ID_PCM_S32BE:
777        case CODEC_ID_PCM_U32LE:
778        case CODEC_ID_PCM_U32BE:
779        case CODEC_ID_PCM_F32BE:
780        case CODEC_ID_PCM_F32LE:
781            bitrate = enc->sample_rate * enc->channels * 32;
782            break;
783        case CODEC_ID_PCM_S24LE:
784        case CODEC_ID_PCM_S24BE:
785        case CODEC_ID_PCM_U24LE:
786        case CODEC_ID_PCM_U24BE:
787        case CODEC_ID_PCM_S24DAUD:
788            bitrate = enc->sample_rate * enc->channels * 24;
789            break;
790        case CODEC_ID_PCM_S16LE:
791        case CODEC_ID_PCM_S16BE:
792        case CODEC_ID_PCM_S16LE_PLANAR:
793        case CODEC_ID_PCM_U16LE:
794        case CODEC_ID_PCM_U16BE:
795            bitrate = enc->sample_rate * enc->channels * 16;
796            break;
797        case CODEC_ID_PCM_S8:
798        case CODEC_ID_PCM_U8:
799        case CODEC_ID_PCM_ALAW:
800        case CODEC_ID_PCM_MULAW:
801        case CODEC_ID_PCM_ZORK:
802            bitrate = enc->sample_rate * enc->channels * 8;
803            break;
804        default:
805            bitrate = enc->bit_rate;
806            break;
807        }
808        break;
809    case CODEC_TYPE_DATA:
810        snprintf(buf, buf_size, "Data: %s", codec_name);
811        bitrate = enc->bit_rate;
812        break;
813    case CODEC_TYPE_SUBTITLE:
814        snprintf(buf, buf_size, "Subtitle: %s", codec_name);
815        bitrate = enc->bit_rate;
816        break;
817    case CODEC_TYPE_ATTACHMENT:
818        snprintf(buf, buf_size, "Attachment: %s", codec_name);
819        bitrate = enc->bit_rate;
820        break;
821    default:
822        snprintf(buf, buf_size, "Invalid Codec type %d", enc->codec_type);
823        return;
824    }
825    if (encode) {
826        if (enc->flags & CODEC_FLAG_PASS1)
827            snprintf(buf + strlen(buf), buf_size - strlen(buf),
828                     ", pass 1");
829        if (enc->flags & CODEC_FLAG_PASS2)
830            snprintf(buf + strlen(buf), buf_size - strlen(buf),
831                     ", pass 2");
832    }
833    if (bitrate != 0) {
834        snprintf(buf + strlen(buf), buf_size - strlen(buf),
835                 ", %d kb/s", bitrate / 1000);
836    }
837}
838
839unsigned avcodec_version( void )
840{
841  return LIBAVCODEC_VERSION_INT;
842}
843
844void avcodec_init(void)
845{
846    static int initialized = 0;
847
848    if (initialized != 0)
849        return;
850    initialized = 1;
851
852    dsputil_static_init();
853}
854
855void avcodec_flush_buffers(AVCodecContext *avctx)
856{
857    if(avctx->codec->flush)
858        avctx->codec->flush(avctx);
859}
860
861void avcodec_default_free_buffers(AVCodecContext *s){
862    int i, j;
863
864    if(s->internal_buffer==NULL) return;
865
866    for(i=0; i<INTERNAL_BUFFER_SIZE; i++){
867        InternalBuffer *buf= &((InternalBuffer*)s->internal_buffer)[i];
868        for(j=0; j<4; j++){
869            av_freep(&buf->base[j]);
870            buf->data[j]= NULL;
871        }
872    }
873    av_freep(&s->internal_buffer);
874
875    s->internal_buffer_count=0;
876}
877
878char av_get_pict_type_char(int pict_type){
879    switch(pict_type){
880    case FF_I_TYPE: return 'I';
881    case FF_P_TYPE: return 'P';
882    case FF_B_TYPE: return 'B';
883    case FF_S_TYPE: return 'S';
884    case FF_SI_TYPE:return 'i';
885    case FF_SP_TYPE:return 'p';
886    case FF_BI_TYPE:return 'b';
887    default:        return '?';
888    }
889}
890
891int av_get_bits_per_sample(enum CodecID codec_id){
892    switch(codec_id){
893    case CODEC_ID_ADPCM_SBPRO_2:
894        return 2;
895    case CODEC_ID_ADPCM_SBPRO_3:
896        return 3;
897    case CODEC_ID_ADPCM_SBPRO_4:
898    case CODEC_ID_ADPCM_CT:
899        return 4;
900    case CODEC_ID_PCM_ALAW:
901    case CODEC_ID_PCM_MULAW:
902    case CODEC_ID_PCM_S8:
903    case CODEC_ID_PCM_U8:
904    case CODEC_ID_PCM_ZORK:
905        return 8;
906    case CODEC_ID_PCM_S16BE:
907    case CODEC_ID_PCM_S16LE:
908    case CODEC_ID_PCM_S16LE_PLANAR:
909    case CODEC_ID_PCM_U16BE:
910    case CODEC_ID_PCM_U16LE:
911        return 16;
912    case CODEC_ID_PCM_S24DAUD:
913    case CODEC_ID_PCM_S24BE:
914    case CODEC_ID_PCM_S24LE:
915    case CODEC_ID_PCM_U24BE:
916    case CODEC_ID_PCM_U24LE:
917        return 24;
918    case CODEC_ID_PCM_S32BE:
919    case CODEC_ID_PCM_S32LE:
920    case CODEC_ID_PCM_U32BE:
921    case CODEC_ID_PCM_U32LE:
922    case CODEC_ID_PCM_F32BE:
923    case CODEC_ID_PCM_F32LE:
924        return 32;
925    case CODEC_ID_PCM_F64BE:
926    case CODEC_ID_PCM_F64LE:
927        return 64;
928    default:
929        return 0;
930    }
931}
932
933int av_get_bits_per_sample_format(enum SampleFormat sample_fmt) {
934    switch (sample_fmt) {
935    case SAMPLE_FMT_U8:
936        return 8;
937    case SAMPLE_FMT_S16:
938        return 16;
939    case SAMPLE_FMT_S32:
940    case SAMPLE_FMT_FLT:
941        return 32;
942    case SAMPLE_FMT_DBL:
943        return 64;
944    default:
945        return 0;
946    }
947}
948
949#if !HAVE_THREADS
950int avcodec_thread_init(AVCodecContext *s, int thread_count){
951    return -1;
952}
953#endif
954
955unsigned int av_xiphlacing(unsigned char *s, unsigned int v)
956{
957    unsigned int n = 0;
958
959    while(v >= 0xff) {
960        *s++ = 0xff;
961        v -= 0xff;
962        n++;
963    }
964    *s = v;
965    n++;
966    return n;
967}
968
969/* Wrapper to work around the lack of mkstemp() on mingw/cygin.
970 * Also, tries to create file in /tmp first, if possible.
971 * *prefix can be a character constant; *filename will be allocated internally.
972 * Returns file descriptor of opened file (or -1 on error)
973 * and opened file name in **filename. */
974int av_tempfile(char *prefix, char **filename) {
975    int fd=-1;
976#if !HAVE_MKSTEMP
977    *filename = tempnam(".", prefix);
978#else
979    size_t len = strlen(prefix) + 12; /* room for "/tmp/" and "XXXXXX\0" */
980    *filename = av_malloc(len);
981#endif
982    /* -----common section-----*/
983    if (*filename == NULL) {
984        av_log(NULL, AV_LOG_ERROR, "ff_tempfile: Cannot allocate file name\n");
985        return -1;
986    }
987#if !HAVE_MKSTEMP
988    fd = open(*filename, O_RDWR | O_BINARY | O_CREAT, 0444);
989#else
990    snprintf(*filename, len, "/tmp/%sXXXXXX", prefix);
991    fd = mkstemp(*filename);
992    if (fd < 0) {
993        snprintf(*filename, len, "./%sXXXXXX", prefix);
994        fd = mkstemp(*filename);
995    }
996#endif
997    /* -----common section-----*/
998    if (fd < 0) {
999        av_log(NULL, AV_LOG_ERROR, "ff_tempfile: Cannot open temporary file %s\n", *filename);
1000        return -1;
1001    }
1002    return fd; /* success */
1003}
1004
1005typedef struct {
1006    const char *abbr;
1007    int width, height;
1008} VideoFrameSizeAbbr;
1009
1010typedef struct {
1011    const char *abbr;
1012    int rate_num, rate_den;
1013} VideoFrameRateAbbr;
1014
1015static const VideoFrameSizeAbbr video_frame_size_abbrs[] = {
1016    { "ntsc",      720, 480 },
1017    { "pal",       720, 576 },
1018    { "qntsc",     352, 240 }, /* VCD compliant NTSC */
1019    { "qpal",      352, 288 }, /* VCD compliant PAL */
1020    { "sntsc",     640, 480 }, /* square pixel NTSC */
1021    { "spal",      768, 576 }, /* square pixel PAL */
1022    { "film",      352, 240 },
1023    { "ntsc-film", 352, 240 },
1024    { "sqcif",     128,  96 },
1025    { "qcif",      176, 144 },
1026    { "cif",       352, 288 },
1027    { "4cif",      704, 576 },
1028    { "qqvga",     160, 120 },
1029    { "qvga",      320, 240 },
1030    { "vga",       640, 480 },
1031    { "svga",      800, 600 },
1032    { "xga",      1024, 768 },
1033    { "uxga",     1600,1200 },
1034    { "qxga",     2048,1536 },
1035    { "sxga",     1280,1024 },
1036    { "qsxga",    2560,2048 },
1037    { "hsxga",    5120,4096 },
1038    { "wvga",      852, 480 },
1039    { "wxga",     1366, 768 },
1040    { "wsxga",    1600,1024 },
1041    { "wuxga",    1920,1200 },
1042    { "woxga",    2560,1600 },
1043    { "wqsxga",   3200,2048 },
1044    { "wquxga",   3840,2400 },
1045    { "whsxga",   6400,4096 },
1046    { "whuxga",   7680,4800 },
1047    { "cga",       320, 200 },
1048    { "ega",       640, 350 },
1049    { "hd480",     852, 480 },
1050    { "hd720",    1280, 720 },
1051    { "hd1080",   1920,1080 },
1052};
1053
1054static const VideoFrameRateAbbr video_frame_rate_abbrs[]= {
1055    { "ntsc",      30000, 1001 },
1056    { "pal",          25,    1 },
1057    { "qntsc",     30000, 1001 }, /* VCD compliant NTSC */
1058    { "qpal",         25,    1 }, /* VCD compliant PAL */
1059    { "sntsc",     30000, 1001 }, /* square pixel NTSC */
1060    { "spal",         25,    1 }, /* square pixel PAL */
1061    { "film",         24,    1 },
1062    { "ntsc-film", 24000, 1001 },
1063};
1064
1065int av_parse_video_frame_size(int *width_ptr, int *height_ptr, const char *str)
1066{
1067    int i;
1068    int n = FF_ARRAY_ELEMS(video_frame_size_abbrs);
1069    char *p;
1070    int frame_width = 0, frame_height = 0;
1071
1072    for(i=0;i<n;i++) {
1073        if (!strcmp(video_frame_size_abbrs[i].abbr, str)) {
1074            frame_width = video_frame_size_abbrs[i].width;
1075            frame_height = video_frame_size_abbrs[i].height;
1076            break;
1077        }
1078    }
1079    if (i == n) {
1080        p = str;
1081        frame_width = strtol(p, &p, 10);
1082        if (*p)
1083            p++;
1084        frame_height = strtol(p, &p, 10);
1085    }
1086    if (frame_width <= 0 || frame_height <= 0)
1087        return -1;
1088    *width_ptr = frame_width;
1089    *height_ptr = frame_height;
1090    return 0;
1091}
1092
1093int av_parse_video_frame_rate(AVRational *frame_rate, const char *arg)
1094{
1095    int i;
1096    int n = FF_ARRAY_ELEMS(video_frame_rate_abbrs);
1097    char* cp;
1098
1099    /* First, we check our abbreviation table */
1100    for (i = 0; i < n; ++i)
1101         if (!strcmp(video_frame_rate_abbrs[i].abbr, arg)) {
1102             frame_rate->num = video_frame_rate_abbrs[i].rate_num;
1103             frame_rate->den = video_frame_rate_abbrs[i].rate_den;
1104             return 0;
1105         }
1106
1107    /* Then, we try to parse it as fraction */
1108    cp = strchr(arg, '/');
1109    if (!cp)
1110        cp = strchr(arg, ':');
1111    if (cp) {
1112        char* cpp;
1113        frame_rate->num = strtol(arg, &cpp, 10);
1114        if (cpp != arg || cpp == cp)
1115            frame_rate->den = strtol(cp+1, &cpp, 10);
1116        else
1117           frame_rate->num = 0;
1118    }
1119    else {
1120        /* Finally we give up and parse it as double */
1121        AVRational time_base = av_d2q(strtod(arg, 0), 1001000);
1122        frame_rate->den = time_base.den;
1123        frame_rate->num = time_base.num;
1124    }
1125    if (!frame_rate->num || !frame_rate->den)
1126        return -1;
1127    else
1128        return 0;
1129}
1130
1131void ff_log_missing_feature(void *avc, const char *feature, int want_sample)
1132{
1133    av_log(avc, AV_LOG_WARNING, "%s not implemented. Update your FFmpeg "
1134            "version to the newest one from SVN. If the problem still "
1135            "occurs, it means that your file has a feature which has not "
1136            "been implemented.", feature);
1137    if(want_sample)
1138        ff_log_ask_for_sample(avc, NULL);
1139    else
1140        av_log(avc, AV_LOG_WARNING, "\n");
1141}
1142
1143void ff_log_ask_for_sample(void *avc, const char *msg)
1144{
1145    if (msg)
1146        av_log(avc, AV_LOG_WARNING, "%s ", msg);
1147    av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample "
1148            "of this file to ftp://upload.ffmpeg.org/MPlayer/incoming/ "
1149            "and contact the ffmpeg-devel mailing list.\n");
1150}
1151
1152static AVHWAccel *first_hwaccel = NULL;
1153
1154void av_register_hwaccel(AVHWAccel *hwaccel)
1155{
1156    AVHWAccel **p = &first_hwaccel;
1157    while (*p)
1158        p = &(*p)->next;
1159    *p = hwaccel;
1160    hwaccel->next = NULL;
1161}
1162
1163AVHWAccel *av_hwaccel_next(AVHWAccel *hwaccel)
1164{
1165    return hwaccel ? hwaccel->next : first_hwaccel;
1166}
1167
1168AVHWAccel *ff_find_hwaccel(enum CodecID codec_id, enum PixelFormat pix_fmt)
1169{
1170    AVHWAccel *hwaccel=NULL;
1171
1172    while((hwaccel= av_hwaccel_next(hwaccel))){
1173        if (   hwaccel->id      == codec_id
1174            && hwaccel->pix_fmt == pix_fmt)
1175            return hwaccel;
1176    }
1177    return NULL;
1178}
1179
1180int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op))
1181{
1182    if (ff_lockmgr_cb) {
1183        if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_DESTROY))
1184            return -1;
1185    }
1186
1187    ff_lockmgr_cb = cb;
1188
1189    if (ff_lockmgr_cb) {
1190        if (ff_lockmgr_cb(&codec_mutex, AV_LOCK_CREATE))
1191            return -1;
1192    }
1193    return 0;
1194}
1195