random_seed.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /*
  2. * Copyright (c) 2009 Baptiste Coudurier <baptiste.coudurier@gmail.com>
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg 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. * FFmpeg 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 FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. #include <unistd.h>
  21. #include <fcntl.h>
  22. #include <math.h>
  23. #include <time.h>
  24. #include "timer.h"
  25. #include "random_seed.h"
  26. static int read_random(uint32_t *dst, const char *file)
  27. {
  28. int fd = open(file, O_RDONLY);
  29. int err = -1;
  30. if (fd == -1)
  31. return -1;
  32. err = read(fd, dst, sizeof(*dst));
  33. close(fd);
  34. return err;
  35. }
  36. static uint32_t get_generic_seed(void)
  37. {
  38. clock_t last_t = 0;
  39. int bits = 0;
  40. uint64_t random = 0;
  41. unsigned i;
  42. float s = 0.000000000001;
  43. for (i = 0; bits < 64; i++) {
  44. clock_t t = clock();
  45. if (last_t && fabs(t - last_t) > s || t == (clock_t) -1) {
  46. if (i < 10000 && s < (1 << 24)) {
  47. s += s;
  48. i = t = 0;
  49. } else {
  50. random = 2 * random + (i & 1);
  51. bits++;
  52. }
  53. }
  54. last_t = t;
  55. }
  56. #ifdef AV_READ_TIME
  57. random ^= AV_READ_TIME();
  58. #else
  59. random ^= clock();
  60. #endif
  61. random += random >> 32;
  62. return random;
  63. }
  64. uint32_t av_get_random_seed(void)
  65. {
  66. uint32_t seed;
  67. if (read_random(&seed, "/dev/urandom") == sizeof(seed))
  68. return seed;
  69. if (read_random(&seed, "/dev/random") == sizeof(seed))
  70. return seed;
  71. return get_generic_seed();
  72. }
  73. #ifdef TEST
  74. #undef printf
  75. #define N 256
  76. #include <stdio.h>
  77. int main(void)
  78. {
  79. int i, j, retry;
  80. uint32_t seeds[N];
  81. for (retry=0; retry<3; retry++){
  82. for (i=0; i<N; i++){
  83. seeds[i] = av_get_random_seed();
  84. for (j=0; j<i; j++)
  85. if (seeds[j] == seeds[i])
  86. goto retry;
  87. }
  88. printf("seeds OK\n");
  89. return 0;
  90. retry:;
  91. }
  92. printf("FAIL at %d with %X\n", j, seeds[j]);
  93. return 1;
  94. }
  95. #endif