]> git.sesse.net Git - ffmpeg/blob - libavcodec/utils.c
default_get_buffer() fixes
[ffmpeg] / libavcodec / utils.c
1 /*
2  * utils for libavcodec
3  * Copyright (c) 2001 Fabrice Bellard.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19  
20 /**
21  * @file utils.c
22  * utils.
23  */
24  
25 #include "avcodec.h"
26 #include "dsputil.h"
27 #include "mpegvideo.h"
28
29 void *av_mallocz(unsigned int size)
30 {
31     void *ptr;
32     
33     ptr = av_malloc(size);
34     if (!ptr)
35         return NULL;
36     memset(ptr, 0, size);
37     return ptr;
38 }
39
40 char *av_strdup(const char *s)
41 {
42     char *ptr;
43     int len;
44     len = strlen(s) + 1;
45     ptr = av_malloc(len);
46     if (!ptr)
47         return NULL;
48     memcpy(ptr, s, len);
49     return ptr;
50 }
51
52 /**
53  * realloc which does nothing if the block is large enough
54  */
55 void *av_fast_realloc(void *ptr, unsigned int *size, unsigned int min_size)
56 {
57     if(min_size < *size) 
58         return ptr;
59     
60     *size= min_size + 10*1024;
61
62     return av_realloc(ptr, *size);
63 }
64
65
66 /* allocation of static arrays - do not use for normal allocation */
67 static unsigned int last_static = 0;
68 static char*** array_static = NULL;
69 static const unsigned int grow_static = 64; // ^2
70 void *__av_mallocz_static(void** location, unsigned int size)
71 {
72     unsigned int l = (last_static + grow_static) & ~(grow_static - 1);
73     void *ptr = av_mallocz(size);
74     if (!ptr)
75         return NULL;
76
77     if (location)
78     {
79         if (l > last_static)
80             array_static = av_realloc(array_static, l);
81         array_static[last_static++] = (char**) location;
82         *location = ptr;
83     }
84     return ptr;
85 }
86 /* free all static arrays and reset pointers to 0 */
87 void av_free_static(void)
88 {
89     if (array_static)
90     {
91         unsigned i;
92         for (i = 0; i < last_static; i++)
93         {
94             av_free(*array_static[i]);
95             *array_static[i] = NULL;
96         }
97         av_free(array_static);
98         array_static = 0;
99     }
100     last_static = 0;
101 }
102
103 /* cannot call it directly because of 'void **' casting is not automatic */
104 void __av_freep(void **ptr)
105 {
106     av_free(*ptr);
107     *ptr = NULL;
108 }
109
110 /* encoder management */
111 AVCodec *first_avcodec;
112
113 void register_avcodec(AVCodec *format)
114 {
115     AVCodec **p;
116     p = &first_avcodec;
117     while (*p != NULL) p = &(*p)->next;
118     *p = format;
119     format->next = NULL;
120 }
121
122 typedef struct InternalBuffer{
123     int last_pic_num;
124     uint8_t *base[4];
125     uint8_t *data[4];
126 }InternalBuffer;
127
128 #define INTERNAL_BUFFER_SIZE 32
129
130 #define ALIGN(x, a) (((x)+(a)-1)&~((a)-1))
131
132 void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height){
133     int w_align= 1;    
134     int h_align= 1;    
135     
136     switch(s->pix_fmt){
137     case PIX_FMT_YUV420P:
138     case PIX_FMT_YUV422:
139     case PIX_FMT_YUV422P:
140     case PIX_FMT_YUV444P:
141     case PIX_FMT_GRAY8:
142     case PIX_FMT_YUVJ420P:
143     case PIX_FMT_YUVJ422P:
144     case PIX_FMT_YUVJ444P:
145         w_align= 16; //FIXME check for non mpeg style codecs and use less alignment
146         h_align= 16;
147         break;
148     case PIX_FMT_YUV411P:
149         w_align=32;
150         h_align=8;
151         break;
152     case PIX_FMT_YUV410P:
153         if(s->codec_id == CODEC_ID_SVQ1){
154             w_align=64;
155             h_align=64;
156         }
157         break;
158     default:
159         w_align= 1;
160         h_align= 1;
161         break;
162     }
163
164     *width = ALIGN(*width , w_align);
165     *height= ALIGN(*height, h_align);
166 }
167
168 int avcodec_default_get_buffer(AVCodecContext *s, AVFrame *pic){
169     int i;
170     int w= s->width;
171     int h= s->height;
172     InternalBuffer *buf;
173     
174     assert(pic->data[0]==NULL);
175     assert(INTERNAL_BUFFER_SIZE > s->internal_buffer_count);
176
177     if(s->internal_buffer==NULL){
178         s->internal_buffer= av_mallocz(INTERNAL_BUFFER_SIZE*sizeof(InternalBuffer));
179     }
180 #if 0
181     s->internal_buffer= av_fast_realloc(
182         s->internal_buffer, 
183         &s->internal_buffer_size, 
184         sizeof(InternalBuffer)*FFMAX(99,  s->internal_buffer_count+1)/*FIXME*/
185         );
186 #endif
187      
188     buf= &((InternalBuffer*)s->internal_buffer)[s->internal_buffer_count];
189
190     if(buf->base[0]){
191         pic->age= pic->coded_picture_number - buf->last_pic_num;
192         buf->last_pic_num= pic->coded_picture_number;
193     }else{
194         int h_chroma_shift, v_chroma_shift;
195         int s_align, pixel_size;
196         
197         avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
198         
199         switch(s->pix_fmt){
200         case PIX_FMT_RGB555:
201         case PIX_FMT_RGB565:
202         case PIX_FMT_YUV422:
203             pixel_size=2;
204             break;
205         case PIX_FMT_RGB24:
206         case PIX_FMT_BGR24:
207             pixel_size=3;
208             break;
209         case PIX_FMT_RGBA32:
210             pixel_size=4;
211             break;
212         default:
213             pixel_size=1;
214         }
215
216         avcodec_align_dimensions(s, &w, &h);
217 #if defined(ARCH_POWERPC) || defined(HAVE_MMI) //FIXME some cleaner check
218         s_align= 16;
219 #else
220         s_align= 8;
221 #endif
222             
223         if(!(s->flags&CODEC_FLAG_EMU_EDGE)){
224             w+= EDGE_WIDTH*2;
225             h+= EDGE_WIDTH*2;
226         }
227         
228         buf->last_pic_num= -256*256*256*64;
229
230         for(i=0; i<3; i++){
231             const int h_shift= i==0 ? 0 : h_chroma_shift;
232             const int v_shift= i==0 ? 0 : v_chroma_shift;
233
234             pic->linesize[i]= ALIGN(pixel_size*w>>h_shift, s_align);
235
236             buf->base[i]= av_mallocz((pic->linesize[i]*h>>v_shift)+16); //FIXME 16
237             if(buf->base[i]==NULL) return -1;
238             memset(buf->base[i], 128, pic->linesize[i]*h>>v_shift);
239         
240             if(s->flags&CODEC_FLAG_EMU_EDGE)
241                 buf->data[i] = buf->base[i];
242             else
243                 buf->data[i] = buf->base[i] + (pic->linesize[i]*EDGE_WIDTH>>v_shift) + (EDGE_WIDTH>>h_shift);
244         }
245         pic->age= 256*256*256*64;
246         pic->type= FF_BUFFER_TYPE_INTERNAL;
247     }
248
249     for(i=0; i<4; i++){
250         pic->base[i]= buf->base[i];
251         pic->data[i]= buf->data[i];
252     }
253     s->internal_buffer_count++;
254
255     return 0;
256 }
257
258 void avcodec_default_release_buffer(AVCodecContext *s, AVFrame *pic){
259     int i;
260     InternalBuffer *buf, *last, temp;
261
262     assert(pic->type==FF_BUFFER_TYPE_INTERNAL);
263     assert(s->internal_buffer_count);
264
265     buf = NULL; /* avoids warning */
266     for(i=0; i<s->internal_buffer_count; i++){ //just 3-5 checks so is not worth to optimize
267         buf= &((InternalBuffer*)s->internal_buffer)[i];
268         if(buf->data[0] == pic->data[0])
269             break;
270     }
271     assert(i < s->internal_buffer_count);
272     s->internal_buffer_count--;
273     last = &((InternalBuffer*)s->internal_buffer)[s->internal_buffer_count];
274
275     temp= *buf;
276     *buf= *last;
277     *last= temp;
278
279     for(i=0; i<3; i++){
280         pic->data[i]=NULL;
281 //        pic->base[i]=NULL;
282     }
283 //printf("R%X\n", pic->opaque);
284 }
285
286 enum PixelFormat avcodec_default_get_format(struct AVCodecContext *s, enum PixelFormat * fmt){
287     return fmt[0];
288 }
289
290 void avcodec_get_context_defaults(AVCodecContext *s){
291     s->bit_rate= 800*1000;
292     s->bit_rate_tolerance= s->bit_rate*10;
293     s->qmin= 2;
294     s->qmax= 31;
295     s->mb_qmin= 2;
296     s->mb_qmax= 31;
297     s->rc_eq= "tex^qComp";
298     s->qcompress= 0.5;
299     s->max_qdiff= 3;
300     s->b_quant_factor=1.25;
301     s->b_quant_offset=1.25;
302     s->i_quant_factor=-0.8;
303     s->i_quant_offset=0.0;
304     s->error_concealment= 3;
305     s->error_resilience= 1;
306     s->workaround_bugs= FF_BUG_AUTODETECT;
307     s->frame_rate_base= 1;
308     s->frame_rate = 25;
309     s->gop_size= 50;
310     s->me_method= ME_EPZS;
311     s->get_buffer= avcodec_default_get_buffer;
312     s->release_buffer= avcodec_default_release_buffer;
313     s->get_format= avcodec_default_get_format;
314     s->me_subpel_quality=8;
315     s->lmin= FF_QP2LAMBDA * s->qmin;
316     s->lmax= FF_QP2LAMBDA * s->qmax;
317     
318     s->intra_quant_bias= FF_DEFAULT_QUANT_BIAS;
319     s->inter_quant_bias= FF_DEFAULT_QUANT_BIAS;
320 }
321
322 /**
323  * allocates a AVCodecContext and set it to defaults.
324  * this can be deallocated by simply calling free() 
325  */
326 AVCodecContext *avcodec_alloc_context(void){
327     AVCodecContext *avctx= av_mallocz(sizeof(AVCodecContext));
328     
329     if(avctx==NULL) return NULL;
330     
331     avcodec_get_context_defaults(avctx);
332     
333     return avctx;
334 }
335
336 /**
337  * allocates a AVPFrame and set it to defaults.
338  * this can be deallocated by simply calling free() 
339  */
340 AVFrame *avcodec_alloc_frame(void){
341     AVFrame *pic= av_mallocz(sizeof(AVFrame));
342     
343     return pic;
344 }
345
346 int avcodec_open(AVCodecContext *avctx, AVCodec *codec)
347 {
348     int ret;
349
350     if(avctx->codec)
351         return -1;
352
353     avctx->codec = codec;
354     avctx->codec_id = codec->id;
355     avctx->frame_number = 0;
356     if (codec->priv_data_size > 0) {
357         avctx->priv_data = av_mallocz(codec->priv_data_size);
358         if (!avctx->priv_data) 
359             return -ENOMEM;
360     } else {
361         avctx->priv_data = NULL;
362     }
363     ret = avctx->codec->init(avctx);
364     if (ret < 0) {
365         av_freep(&avctx->priv_data);
366         return ret;
367     }
368     return 0;
369 }
370
371 int avcodec_encode_audio(AVCodecContext *avctx, uint8_t *buf, int buf_size, 
372                          const short *samples)
373 {
374     int ret;
375
376     ret = avctx->codec->encode(avctx, buf, buf_size, (void *)samples);
377     avctx->frame_number++;
378     return ret;
379 }
380
381 int avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size, 
382                          const AVFrame *pict)
383 {
384     int ret;
385
386     ret = avctx->codec->encode(avctx, buf, buf_size, (void *)pict);
387     
388     emms_c(); //needed to avoid a emms_c() call before every return;
389
390     avctx->frame_number++;
391     return ret;
392 }
393
394 /** 
395  * decode a frame. 
396  * @param buf bitstream buffer, must be FF_INPUT_BUFFER_PADDING_SIZE larger then the actual read bytes
397  * because some optimized bitstream readers read 32 or 64 bit at once and could read over the end
398  * @param buf_size the size of the buffer in bytes
399  * @param got_picture_ptr zero if no frame could be decompressed, Otherwise, it is non zero
400  * @return -1 if error, otherwise return the number of
401  * bytes used. 
402  */
403 int avcodec_decode_video(AVCodecContext *avctx, AVFrame *picture, 
404                          int *got_picture_ptr,
405                          uint8_t *buf, int buf_size)
406 {
407     int ret;
408     
409     ret = avctx->codec->decode(avctx, picture, got_picture_ptr, 
410                                buf, buf_size);
411
412     emms_c(); //needed to avoid a emms_c() call before every return;
413     
414     if (*got_picture_ptr)                           
415         avctx->frame_number++;
416     return ret;
417 }
418
419 /* decode an audio frame. return -1 if error, otherwise return the
420    *number of bytes used. If no frame could be decompressed,
421    *frame_size_ptr is zero. Otherwise, it is the decompressed frame
422    *size in BYTES. */
423 int avcodec_decode_audio(AVCodecContext *avctx, int16_t *samples, 
424                          int *frame_size_ptr,
425                          uint8_t *buf, int buf_size)
426 {
427     int ret;
428
429     ret = avctx->codec->decode(avctx, samples, frame_size_ptr, 
430                                buf, buf_size);
431     avctx->frame_number++;
432     return ret;
433 }
434
435 int avcodec_close(AVCodecContext *avctx)
436 {
437     if (avctx->codec->close)
438         avctx->codec->close(avctx);
439     av_freep(&avctx->priv_data);
440     avctx->codec = NULL;
441     return 0;
442 }
443
444 AVCodec *avcodec_find_encoder(enum CodecID id)
445 {
446     AVCodec *p;
447     p = first_avcodec;
448     while (p) {
449         if (p->encode != NULL && p->id == id)
450             return p;
451         p = p->next;
452     }
453     return NULL;
454 }
455
456 AVCodec *avcodec_find_encoder_by_name(const char *name)
457 {
458     AVCodec *p;
459     p = first_avcodec;
460     while (p) {
461         if (p->encode != NULL && strcmp(name,p->name) == 0)
462             return p;
463         p = p->next;
464     }
465     return NULL;
466 }
467
468 AVCodec *avcodec_find_decoder(enum CodecID id)
469 {
470     AVCodec *p;
471     p = first_avcodec;
472     while (p) {
473         if (p->decode != NULL && p->id == id)
474             return p;
475         p = p->next;
476     }
477     return NULL;
478 }
479
480 AVCodec *avcodec_find_decoder_by_name(const char *name)
481 {
482     AVCodec *p;
483     p = first_avcodec;
484     while (p) {
485         if (p->decode != NULL && strcmp(name,p->name) == 0)
486             return p;
487         p = p->next;
488     }
489     return NULL;
490 }
491
492 AVCodec *avcodec_find(enum CodecID id)
493 {
494     AVCodec *p;
495     p = first_avcodec;
496     while (p) {
497         if (p->id == id)
498             return p;
499         p = p->next;
500     }
501     return NULL;
502 }
503
504 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
505 {
506     const char *codec_name;
507     AVCodec *p;
508     char buf1[32];
509     char channels_str[100];
510     int bitrate;
511
512     if (encode)
513         p = avcodec_find_encoder(enc->codec_id);
514     else
515         p = avcodec_find_decoder(enc->codec_id);
516
517     if (p) {
518         codec_name = p->name;
519         if (!encode && enc->codec_id == CODEC_ID_MP3) {
520             if (enc->sub_id == 2)
521                 codec_name = "mp2";
522             else if (enc->sub_id == 1)
523                 codec_name = "mp1";
524         }
525     } else if (enc->codec_name[0] != '\0') {
526         codec_name = enc->codec_name;
527     } else {
528         /* output avi tags */
529         if (enc->codec_type == CODEC_TYPE_VIDEO) {
530             snprintf(buf1, sizeof(buf1), "%c%c%c%c", 
531                      enc->codec_tag & 0xff,
532                      (enc->codec_tag >> 8) & 0xff,
533                      (enc->codec_tag >> 16) & 0xff,
534                      (enc->codec_tag >> 24) & 0xff);
535         } else {
536             snprintf(buf1, sizeof(buf1), "0x%04x", enc->codec_tag);
537         }
538         codec_name = buf1;
539     }
540
541     switch(enc->codec_type) {
542     case CODEC_TYPE_VIDEO:
543         snprintf(buf, buf_size,
544                  "Video: %s%s",
545                  codec_name, enc->mb_decision ? " (hq)" : "");
546         if (enc->codec_id == CODEC_ID_RAWVIDEO) {
547             snprintf(buf + strlen(buf), buf_size - strlen(buf),
548                      ", %s",
549                      avcodec_get_pix_fmt_name(enc->pix_fmt));
550         }
551         if (enc->width) {
552             snprintf(buf + strlen(buf), buf_size - strlen(buf),
553                      ", %dx%d, %0.2f fps",
554                      enc->width, enc->height, 
555                      (float)enc->frame_rate / enc->frame_rate_base);
556         }
557         if (encode) {
558             snprintf(buf + strlen(buf), buf_size - strlen(buf),
559                      ", q=%d-%d", enc->qmin, enc->qmax);
560         }
561         bitrate = enc->bit_rate;
562         break;
563     case CODEC_TYPE_AUDIO:
564         snprintf(buf, buf_size,
565                  "Audio: %s",
566                  codec_name);
567         switch (enc->channels) {
568             case 1:
569                 strcpy(channels_str, "mono");
570                 break;
571             case 2:
572                 strcpy(channels_str, "stereo");
573                 break;
574             case 6:
575                 strcpy(channels_str, "5:1");
576                 break;
577             default:
578                 sprintf(channels_str, "%d channels", enc->channels);
579                 break;
580         }
581         if (enc->sample_rate) {
582             snprintf(buf + strlen(buf), buf_size - strlen(buf),
583                      ", %d Hz, %s",
584                      enc->sample_rate,
585                      channels_str);
586         }
587         
588         /* for PCM codecs, compute bitrate directly */
589         switch(enc->codec_id) {
590         case CODEC_ID_PCM_S16LE:
591         case CODEC_ID_PCM_S16BE:
592         case CODEC_ID_PCM_U16LE:
593         case CODEC_ID_PCM_U16BE:
594             bitrate = enc->sample_rate * enc->channels * 16;
595             break;
596         case CODEC_ID_PCM_S8:
597         case CODEC_ID_PCM_U8:
598         case CODEC_ID_PCM_ALAW:
599         case CODEC_ID_PCM_MULAW:
600             bitrate = enc->sample_rate * enc->channels * 8;
601             break;
602         default:
603             bitrate = enc->bit_rate;
604             break;
605         }
606         break;
607     default:
608         av_abort();
609     }
610     if (encode) {
611         if (enc->flags & CODEC_FLAG_PASS1)
612             snprintf(buf + strlen(buf), buf_size - strlen(buf),
613                      ", pass 1");
614         if (enc->flags & CODEC_FLAG_PASS2)
615             snprintf(buf + strlen(buf), buf_size - strlen(buf),
616                      ", pass 2");
617     }
618     if (bitrate != 0) {
619         snprintf(buf + strlen(buf), buf_size - strlen(buf), 
620                  ", %d kb/s", bitrate / 1000);
621     }
622 }
623
624 unsigned avcodec_version( void )
625 {
626   return LIBAVCODEC_VERSION_INT;
627 }
628
629 unsigned avcodec_build( void )
630 {
631   return LIBAVCODEC_BUILD;
632 }
633
634 /* must be called before any other functions */
635 void avcodec_init(void)
636 {
637     static int inited = 0;
638
639     if (inited != 0)
640         return;
641     inited = 1;
642
643     dsputil_static_init();
644 }
645
646 /**
647  * Flush buffers, should be called when seeking or when swicthing to a different stream.
648  */
649 void avcodec_flush_buffers(AVCodecContext *avctx)
650 {
651     if(avctx->codec->flush)
652         avctx->codec->flush(avctx);
653 }
654
655 void avcodec_default_free_buffers(AVCodecContext *s){
656     int i, j;
657
658     if(s->internal_buffer==NULL) return;
659     
660     for(i=0; i<INTERNAL_BUFFER_SIZE; i++){
661         InternalBuffer *buf= &((InternalBuffer*)s->internal_buffer)[i];
662         for(j=0; j<4; j++){
663             av_freep(&buf->base[j]);
664             buf->data[j]= NULL;
665         }
666     }
667     av_freep(&s->internal_buffer);
668     
669     s->internal_buffer_count=0;
670 }
671
672 char av_get_pict_type_char(int pict_type){
673     switch(pict_type){
674     case I_TYPE: return 'I'; 
675     case P_TYPE: return 'P'; 
676     case B_TYPE: return 'B'; 
677     case S_TYPE: return 'S'; 
678     case SI_TYPE:return 'i'; 
679     case SP_TYPE:return 'p'; 
680     default:     return '?';
681     }
682 }
683
684 int av_reduce(int *dst_nom, int *dst_den, int64_t nom, int64_t den, int64_t max){
685     int exact=1, sign=0;
686     int64_t gcd, larger;
687
688     assert(den != 0);
689
690     if(den < 0){
691         den= -den;
692         nom= -nom;
693     }
694     
695     if(nom < 0){
696         nom= -nom;
697         sign= 1;
698     }
699     
700     for(;;){ //note is executed 1 or 2 times 
701         gcd = ff_gcd(nom, den);
702         nom /= gcd;
703         den /= gcd;
704     
705         larger= FFMAX(nom, den);
706     
707         if(larger > max){
708             int64_t div= (larger + max - 1) / max;
709             nom =  (nom + div/2)/div;
710             den =  (den + div/2)/div;
711             exact=0;
712         }else 
713             break;
714     }
715     
716     if(sign) nom= -nom;
717     
718     *dst_nom = nom;
719     *dst_den = den;
720     
721     return exact;
722 }
723
724 int64_t av_rescale(int64_t a, int b, int c){
725     uint64_t h, l;
726     assert(c > 0);
727     assert(b >=0);
728     
729     if(a<0) return -av_rescale(-a, b, c);
730     
731     h= a>>32;
732     if(h==0) return a*b/c;
733     
734     l= a&0xFFFFFFFF;
735     l *= b;
736     h *= b;
737
738     l += (h%c)<<32;
739
740     return ((h/c)<<32) + l/c;
741 }