random_seed.c 2.2 KB

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