AVRational
[libav.git] / 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] + ALIGN((pic->linesize[i]*EDGE_WIDTH>>v_shift) + (EDGE_WIDTH>>h_shift), s_align);
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 s->sample_aspect_ratio= (AVRational){0,1};
318
319 s->intra_quant_bias= FF_DEFAULT_QUANT_BIAS;
320 s->inter_quant_bias= FF_DEFAULT_QUANT_BIAS;
321 }
322
323 /**
324 * allocates a AVCodecContext and set it to defaults.
325 * this can be deallocated by simply calling free()
326 */
327 AVCodecContext *avcodec_alloc_context(void){
328 AVCodecContext *avctx= av_mallocz(sizeof(AVCodecContext));
329
330 if(avctx==NULL) return NULL;
331
332 avcodec_get_context_defaults(avctx);
333
334 return avctx;
335 }
336
337 /**
338 * allocates a AVPFrame and set it to defaults.
339 * this can be deallocated by simply calling free()
340 */
341 AVFrame *avcodec_alloc_frame(void){
342 AVFrame *pic= av_mallocz(sizeof(AVFrame));
343
344 return pic;
345 }
346
347 int avcodec_open(AVCodecContext *avctx, AVCodec *codec)
348 {
349 int ret;
350
351 if(avctx->codec)
352 return -1;
353
354 avctx->codec = codec;
355 avctx->codec_id = codec->id;
356 avctx->frame_number = 0;
357 if (codec->priv_data_size > 0) {
358 avctx->priv_data = av_mallocz(codec->priv_data_size);
359 if (!avctx->priv_data)
360 return -ENOMEM;
361 } else {
362 avctx->priv_data = NULL;
363 }
364 ret = avctx->codec->init(avctx);
365 if (ret < 0) {
366 av_freep(&avctx->priv_data);
367 return ret;
368 }
369 return 0;
370 }
371
372 int avcodec_encode_audio(AVCodecContext *avctx, uint8_t *buf, int buf_size,
373 const short *samples)
374 {
375 int ret;
376
377 ret = avctx->codec->encode(avctx, buf, buf_size, (void *)samples);
378 avctx->frame_number++;
379 return ret;
380 }
381
382 int avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,
383 const AVFrame *pict)
384 {
385 int ret;
386
387 ret = avctx->codec->encode(avctx, buf, buf_size, (void *)pict);
388
389 emms_c(); //needed to avoid a emms_c() call before every return;
390
391 avctx->frame_number++;
392 return ret;
393 }
394
395 /**
396 * decode a frame.
397 * @param buf bitstream buffer, must be FF_INPUT_BUFFER_PADDING_SIZE larger then the actual read bytes
398 * because some optimized bitstream readers read 32 or 64 bit at once and could read over the end
399 * @param buf_size the size of the buffer in bytes
400 * @param got_picture_ptr zero if no frame could be decompressed, Otherwise, it is non zero
401 * @return -1 if error, otherwise return the number of
402 * bytes used.
403 */
404 int avcodec_decode_video(AVCodecContext *avctx, AVFrame *picture,
405 int *got_picture_ptr,
406 uint8_t *buf, int buf_size)
407 {
408 int ret;
409
410 ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
411 buf, buf_size);
412
413 emms_c(); //needed to avoid a emms_c() call before every return;
414
415 if (*got_picture_ptr)
416 avctx->frame_number++;
417 return ret;
418 }
419
420 /* decode an audio frame. return -1 if error, otherwise return the
421 *number of bytes used. If no frame could be decompressed,
422 *frame_size_ptr is zero. Otherwise, it is the decompressed frame
423 *size in BYTES. */
424 int avcodec_decode_audio(AVCodecContext *avctx, int16_t *samples,
425 int *frame_size_ptr,
426 uint8_t *buf, int buf_size)
427 {
428 int ret;
429
430 ret = avctx->codec->decode(avctx, samples, frame_size_ptr,
431 buf, buf_size);
432 avctx->frame_number++;
433 return ret;
434 }
435
436 int avcodec_close(AVCodecContext *avctx)
437 {
438 if (avctx->codec->close)
439 avctx->codec->close(avctx);
440 av_freep(&avctx->priv_data);
441 avctx->codec = NULL;
442 return 0;
443 }
444
445 AVCodec *avcodec_find_encoder(enum CodecID id)
446 {
447 AVCodec *p;
448 p = first_avcodec;
449 while (p) {
450 if (p->encode != NULL && p->id == id)
451 return p;
452 p = p->next;
453 }
454 return NULL;
455 }
456
457 AVCodec *avcodec_find_encoder_by_name(const char *name)
458 {
459 AVCodec *p;
460 p = first_avcodec;
461 while (p) {
462 if (p->encode != NULL && strcmp(name,p->name) == 0)
463 return p;
464 p = p->next;
465 }
466 return NULL;
467 }
468
469 AVCodec *avcodec_find_decoder(enum CodecID id)
470 {
471 AVCodec *p;
472 p = first_avcodec;
473 while (p) {
474 if (p->decode != NULL && p->id == id)
475 return p;
476 p = p->next;
477 }
478 return NULL;
479 }
480
481 AVCodec *avcodec_find_decoder_by_name(const char *name)
482 {
483 AVCodec *p;
484 p = first_avcodec;
485 while (p) {
486 if (p->decode != NULL && strcmp(name,p->name) == 0)
487 return p;
488 p = p->next;
489 }
490 return NULL;
491 }
492
493 AVCodec *avcodec_find(enum CodecID id)
494 {
495 AVCodec *p;
496 p = first_avcodec;
497 while (p) {
498 if (p->id == id)
499 return p;
500 p = p->next;
501 }
502 return NULL;
503 }
504
505 void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
506 {
507 const char *codec_name;
508 AVCodec *p;
509 char buf1[32];
510 char channels_str[100];
511 int bitrate;
512
513 if (encode)
514 p = avcodec_find_encoder(enc->codec_id);
515 else
516 p = avcodec_find_decoder(enc->codec_id);
517
518 if (p) {
519 codec_name = p->name;
520 if (!encode && enc->codec_id == CODEC_ID_MP3) {
521 if (enc->sub_id == 2)
522 codec_name = "mp2";
523 else if (enc->sub_id == 1)
524 codec_name = "mp1";
525 }
526 } else if (enc->codec_name[0] != '\0') {
527 codec_name = enc->codec_name;
528 } else {
529 /* output avi tags */
530 if (enc->codec_type == CODEC_TYPE_VIDEO) {
531 snprintf(buf1, sizeof(buf1), "%c%c%c%c",
532 enc->codec_tag & 0xff,
533 (enc->codec_tag >> 8) & 0xff,
534 (enc->codec_tag >> 16) & 0xff,
535 (enc->codec_tag >> 24) & 0xff);
536 } else {
537 snprintf(buf1, sizeof(buf1), "0x%04x", enc->codec_tag);
538 }
539 codec_name = buf1;
540 }
541
542 switch(enc->codec_type) {
543 case CODEC_TYPE_VIDEO:
544 snprintf(buf, buf_size,
545 "Video: %s%s",
546 codec_name, enc->mb_decision ? " (hq)" : "");
547 if (enc->codec_id == CODEC_ID_RAWVIDEO) {
548 snprintf(buf + strlen(buf), buf_size - strlen(buf),
549 ", %s",
550 avcodec_get_pix_fmt_name(enc->pix_fmt));
551 }
552 if (enc->width) {
553 snprintf(buf + strlen(buf), buf_size - strlen(buf),
554 ", %dx%d, %0.2f fps",
555 enc->width, enc->height,
556 (float)enc->frame_rate / enc->frame_rate_base);
557 }
558 if (encode) {
559 snprintf(buf + strlen(buf), buf_size - strlen(buf),
560 ", q=%d-%d", enc->qmin, enc->qmax);
561 }
562 bitrate = enc->bit_rate;
563 break;
564 case CODEC_TYPE_AUDIO:
565 snprintf(buf, buf_size,
566 "Audio: %s",
567 codec_name);
568 switch (enc->channels) {
569 case 1:
570 strcpy(channels_str, "mono");
571 break;
572 case 2:
573 strcpy(channels_str, "stereo");
574 break;
575 case 6:
576 strcpy(channels_str, "5:1");
577 break;
578 default:
579 sprintf(channels_str, "%d channels", enc->channels);
580 break;
581 }
582 if (enc->sample_rate) {
583 snprintf(buf + strlen(buf), buf_size - strlen(buf),
584 ", %d Hz, %s",
585 enc->sample_rate,
586 channels_str);
587 }
588
589 /* for PCM codecs, compute bitrate directly */
590 switch(enc->codec_id) {
591 case CODEC_ID_PCM_S16LE:
592 case CODEC_ID_PCM_S16BE:
593 case CODEC_ID_PCM_U16LE:
594 case CODEC_ID_PCM_U16BE:
595 bitrate = enc->sample_rate * enc->channels * 16;
596 break;
597 case CODEC_ID_PCM_S8:
598 case CODEC_ID_PCM_U8:
599 case CODEC_ID_PCM_ALAW:
600 case CODEC_ID_PCM_MULAW:
601 bitrate = enc->sample_rate * enc->channels * 8;
602 break;
603 default:
604 bitrate = enc->bit_rate;
605 break;
606 }
607 break;
608 default:
609 av_abort();
610 }
611 if (encode) {
612 if (enc->flags & CODEC_FLAG_PASS1)
613 snprintf(buf + strlen(buf), buf_size - strlen(buf),
614 ", pass 1");
615 if (enc->flags & CODEC_FLAG_PASS2)
616 snprintf(buf + strlen(buf), buf_size - strlen(buf),
617 ", pass 2");
618 }
619 if (bitrate != 0) {
620 snprintf(buf + strlen(buf), buf_size - strlen(buf),
621 ", %d kb/s", bitrate / 1000);
622 }
623 }
624
625 unsigned avcodec_version( void )
626 {
627 return LIBAVCODEC_VERSION_INT;
628 }
629
630 unsigned avcodec_build( void )
631 {
632 return LIBAVCODEC_BUILD;
633 }
634
635 /* must be called before any other functions */
636 void avcodec_init(void)
637 {
638 static int inited = 0;
639
640 if (inited != 0)
641 return;
642 inited = 1;
643
644 dsputil_static_init();
645 }
646
647 /**
648 * Flush buffers, should be called when seeking or when swicthing to a different stream.
649 */
650 void avcodec_flush_buffers(AVCodecContext *avctx)
651 {
652 if(avctx->codec->flush)
653 avctx->codec->flush(avctx);
654 }
655
656 void avcodec_default_free_buffers(AVCodecContext *s){
657 int i, j;
658
659 if(s->internal_buffer==NULL) return;
660
661 for(i=0; i<INTERNAL_BUFFER_SIZE; i++){
662 InternalBuffer *buf= &((InternalBuffer*)s->internal_buffer)[i];
663 for(j=0; j<4; j++){
664 av_freep(&buf->base[j]);
665 buf->data[j]= NULL;
666 }
667 }
668 av_freep(&s->internal_buffer);
669
670 s->internal_buffer_count=0;
671 }
672
673 char av_get_pict_type_char(int pict_type){
674 switch(pict_type){
675 case I_TYPE: return 'I';
676 case P_TYPE: return 'P';
677 case B_TYPE: return 'B';
678 case S_TYPE: return 'S';
679 case SI_TYPE:return 'i';
680 case SP_TYPE:return 'p';
681 default: return '?';
682 }
683 }
684
685 int av_reduce(int *dst_nom, int *dst_den, int64_t nom, int64_t den, int64_t max){
686 int exact=1, sign=0;
687 int64_t gcd, larger;
688
689 assert(den != 0);
690
691 if(den < 0){
692 den= -den;
693 nom= -nom;
694 }
695
696 if(nom < 0){
697 nom= -nom;
698 sign= 1;
699 }
700
701 for(;;){ //note is executed 1 or 2 times
702 gcd = ff_gcd(nom, den);
703 nom /= gcd;
704 den /= gcd;
705
706 larger= FFMAX(nom, den);
707
708 if(larger > max){
709 int64_t div= (larger + max - 1) / max;
710 nom = (nom + div/2)/div;
711 den = (den + div/2)/div;
712 exact=0;
713 }else
714 break;
715 }
716
717 if(sign) nom= -nom;
718
719 *dst_nom = nom;
720 *dst_den = den;
721
722 return exact;
723 }
724
725 int64_t av_rescale(int64_t a, int b, int c){
726 uint64_t h, l;
727 assert(c > 0);
728 assert(b >=0);
729
730 if(a<0) return -av_rescale(-a, b, c);
731
732 h= a>>32;
733 if(h==0) return a*b/c;
734
735 l= a&0xFFFFFFFF;
736 l *= b;
737 h *= b;
738
739 l += (h%c)<<32;
740
741 return ((h/c)<<32) + l/c;
742 }