ad085653a520cefddf624051066e28dcfe0c3598
[libav.git] / libavcodec / rational.c
1 /*
2 * Rational numbers
3 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
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 /**
22 * @file rational.c
23 * Rational numbers
24 * @author Michael Niedermayer <michaelni@gmx.at>
25 */
26
27 //#include <math.h>
28 #include <limits.h>
29
30 #include "common.h"
31 #include "avcodec.h"
32 #include "rational.h"
33
34 AVRational av_mul_q(AVRational b, AVRational c){
35 av_reduce(&b.num, &b.den, b.num * (int64_t)c.num, b.den * (int64_t)c.den, INT_MAX);
36 return b;
37 }
38
39 AVRational av_div_q(AVRational b, AVRational c){
40 av_reduce(&b.num, &b.den, b.num * (int64_t)c.den, b.den * (int64_t)c.num, INT_MAX);
41 return b;
42 }
43
44 AVRational av_add_q(AVRational b, AVRational c){
45 av_reduce(&b.num, &b.den, b.num * (int64_t)c.den + c.num * (int64_t)b.den, b.den * (int64_t)c.den, INT_MAX);
46 return b;
47 }
48
49 AVRational av_sub_q(AVRational b, AVRational c){
50 av_reduce(&b.num, &b.den, b.num * (int64_t)c.den - c.num * (int64_t)b.den, b.den * (int64_t)c.den, INT_MAX);
51 return b;
52 }
53
54 /**
55 * Converts a double precission floating point number to a AVRational.
56 * @param max the maximum allowed numerator and denominator
57 */
58 AVRational av_d2q(double d, int max){
59 AVRational a;
60 int exponent= FFMAX( (int)(log(ABS(d) + 1e-20)/log(2)), 0);
61 int64_t den= 1LL << (61 - exponent);
62 av_reduce(&a.num, &a.den, (int64_t)(d * den + 0.5), den, max);
63
64 return a;
65 }