You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.1KB

  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. #include "config.h"
  21. #if HAVE_UNISTD_H
  22. #include <unistd.h>
  23. #endif
  24. #include <fcntl.h>
  25. #include <math.h>
  26. #include <time.h>
  27. #include "timer.h"
  28. #include "random_seed.h"
  29. static int read_random(uint32_t *dst, const char *file)
  30. {
  31. #if HAVE_UNISTD_H
  32. int fd = open(file, O_RDONLY);
  33. int err = -1;
  34. if (fd == -1)
  35. return -1;
  36. err = read(fd, dst, sizeof(*dst));
  37. close(fd);
  38. return err;
  39. #else
  40. return -1;
  41. #endif
  42. }
  43. static uint32_t get_generic_seed(void)
  44. {
  45. clock_t last_t = 0;
  46. int bits = 0;
  47. uint64_t random = 0;
  48. unsigned i;
  49. float s = 0.000000000001;
  50. for (i = 0; bits < 64; i++) {
  51. clock_t t = clock();
  52. if (last_t && fabs(t - last_t) > s || t == (clock_t) -1) {
  53. if (i < 10000 && s < (1 << 24)) {
  54. s += s;
  55. i = t = 0;
  56. } else {
  57. random = 2 * random + (i & 1);
  58. bits++;
  59. }
  60. }
  61. last_t = t;
  62. }
  63. #ifdef AV_READ_TIME
  64. random ^= AV_READ_TIME();
  65. #else
  66. random ^= clock();
  67. #endif
  68. random += random >> 32;
  69. return random;
  70. }
  71. uint32_t av_get_random_seed(void)
  72. {
  73. uint32_t seed;
  74. if (read_random(&seed, "/dev/urandom") == sizeof(seed))
  75. return seed;
  76. if (read_random(&seed, "/dev/random") == sizeof(seed))
  77. return seed;
  78. return get_generic_seed();
  79. }