]> git.sesse.net Git - ffmpeg/blob - libavutil/random_seed.c
indeo4: update AVCodecContext width/height on size change
[ffmpeg] / libavutil / random_seed.c
1 /*
2  * Copyright (c) 2009 Baptiste Coudurier <baptiste.coudurier@gmail.com>
3  *
4  * This file is part of Libav.
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #include "config.h"
22
23 #if HAVE_UNISTD_H
24 #include <unistd.h>
25 #endif
26 #include <fcntl.h>
27 #include <math.h>
28 #include <time.h>
29 #include "timer.h"
30 #include "random_seed.h"
31
32 static int read_random(uint32_t *dst, const char *file)
33 {
34 #if HAVE_UNISTD_H
35     int fd = open(file, O_RDONLY);
36     int err = -1;
37
38     if (fd == -1)
39         return -1;
40     err = read(fd, dst, sizeof(*dst));
41     close(fd);
42
43     return err;
44 #else
45     return -1;
46 #endif
47 }
48
49 static uint32_t get_generic_seed(void)
50 {
51     clock_t last_t  = 0;
52     int bits        = 0;
53     uint64_t random = 0;
54     unsigned i;
55     float s = 0.000000000001;
56
57     for (i = 0; bits < 64; i++) {
58         clock_t t = clock();
59         if (last_t && fabs(t - last_t) > s || t == (clock_t) -1) {
60             if (i < 10000 && s < (1 << 24)) {
61                 s += s;
62                 i = t = 0;
63             } else {
64                 random = 2 * random + (i & 1);
65                 bits++;
66             }
67         }
68         last_t = t;
69     }
70 #ifdef AV_READ_TIME
71     random ^= AV_READ_TIME();
72 #else
73     random ^= clock();
74 #endif
75
76     random += random >> 32;
77
78     return random;
79 }
80
81 uint32_t av_get_random_seed(void)
82 {
83     uint32_t seed;
84
85     if (read_random(&seed, "/dev/urandom") == sizeof(seed))
86         return seed;
87     if (read_random(&seed, "/dev/random")  == sizeof(seed))
88         return seed;
89     return get_generic_seed();
90 }