2 * Copyright (c) 2005 Michael Niedermayer <michaelni@gmx.at>
4 * This file is part of Libav.
6 * Libav is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * Libav is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with Libav; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 * miscellaneous math routines and tables
29 #include "mathematics.h"
32 int64_t av_gcd(int64_t a, int64_t b)
35 return av_gcd(b, a % b);
40 int64_t av_rescale_rnd(int64_t a, int64_t b, int64_t c, enum AVRounding rnd)
44 if (c <= 0 || b < 0 || rnd == 4 || rnd > 5)
47 if (a < 0 && a != INT64_MIN)
48 return -av_rescale_rnd(-a, b, c, rnd ^ ((rnd >> 1) & 1));
50 if (rnd == AV_ROUND_NEAR_INF)
55 if (b <= INT_MAX && c <= INT_MAX) {
57 return (a * b + r) / c;
59 return a / c * b + (a % c * b + r) / c;
62 uint64_t a0 = a & 0xFFFFFFFF;
63 uint64_t a1 = a >> 32;
64 uint64_t b0 = b & 0xFFFFFFFF;
65 uint64_t b1 = b >> 32;
66 uint64_t t1 = a0 * b1 + a1 * b0;
67 uint64_t t1a = t1 << 32;
71 a1 = a1 * b1 + (t1 >> 32) + (a0 < t1a);
75 for (i = 63; i >= 0; i--) {
76 a1 += a1 + ((a0 >> i) & 1);
87 ai = av_mul_i(av_int2i(a), av_int2i(b));
88 ai = av_add_i(ai, av_int2i(r));
90 return av_i2int(av_div_i(ai, av_int2i(c)));
95 int64_t av_rescale(int64_t a, int64_t b, int64_t c)
97 return av_rescale_rnd(a, b, c, AV_ROUND_NEAR_INF);
100 int64_t av_rescale_q_rnd(int64_t a, AVRational bq, AVRational cq,
103 int64_t b = bq.num * (int64_t)cq.den;
104 int64_t c = cq.num * (int64_t)bq.den;
105 return av_rescale_rnd(a, b, c, rnd);
108 int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
110 return av_rescale_q_rnd(a, bq, cq, AV_ROUND_NEAR_INF);
113 int av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b)
115 int64_t a = tb_a.num * (int64_t)tb_b.den;
116 int64_t b = tb_b.num * (int64_t)tb_a.den;
117 if (av_rescale_rnd(ts_a, a, b, AV_ROUND_DOWN) < ts_b)
119 if (av_rescale_rnd(ts_b, b, a, AV_ROUND_DOWN) < ts_a)
124 int64_t av_compare_mod(uint64_t a, uint64_t b, uint64_t mod)
126 int64_t c = (a - b) & (mod - 1);