From c365e2f7b17e6a890827802e063b823bf6e4385f Mon Sep 17 00:00:00 2001 From: Andreas Klauer Date: Fri, 27 Sep 2024 19:35:37 +0200 Subject: [PATCH] misc/random: seed using libavutil/random_seed When starting multiple processes of `mpv --shuffle` in parallel, sometimes the random seed happens to be identical, so files are played in the same random order. mp_rand_seed(0) now uses a random seed provided by libavutil, and only falls back to time in case of failure. --- misc/random.c | 13 +++++++++++++ misc/random.h | 2 +- osdep/timer.c | 2 -- player/main.c | 2 ++ 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/misc/random.c b/misc/random.c index d40474bee6..83cf0a727e 100644 --- a/misc/random.c +++ b/misc/random.c @@ -20,7 +20,10 @@ #include +#include + #include "osdep/threads.h" +#include "osdep/timer.h" #include "random.h" static uint64_t state[4]; @@ -44,6 +47,16 @@ void mp_rand_seed(uint64_t seed) #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION seed = 42; #endif + + if (seed == 0) { + uint8_t buf[sizeof(seed)]; + if (av_random_bytes(buf, sizeof(buf)) < 0) { + seed = mp_raw_time_ns(); + } else { + memcpy(&seed, buf, sizeof(seed)); + } + } + mp_mutex_lock(&state_mutex); state[0] = seed; for (int i = 1; i < 4; i++) diff --git a/misc/random.h b/misc/random.h index dae66a0939..23b4f82399 100644 --- a/misc/random.h +++ b/misc/random.h @@ -24,7 +24,7 @@ /* * Initialize the pseudo-random number generator's state with - * the given 64-bit seed. + * the given 64-bit seed. If the seed is 0, it is randomized. */ void mp_rand_seed(uint64_t seed); diff --git a/osdep/timer.c b/osdep/timer.c index 86cfaebf88..c0aac8972b 100644 --- a/osdep/timer.c +++ b/osdep/timer.c @@ -22,7 +22,6 @@ #include "common/common.h" #include "common/msg.h" -#include "misc/random.h" #include "threads.h" #include "timer.h" @@ -32,7 +31,6 @@ static mp_once timer_init_once = MP_STATIC_ONCE_INITIALIZER; static void do_timer_init(void) { mp_raw_time_init(); - mp_rand_seed(mp_raw_time_ns()); raw_time_offset = mp_raw_time_ns(); assert(raw_time_offset > 0); } diff --git a/player/main.c b/player/main.c index 21478a6e5f..8ed0f4d94d 100644 --- a/player/main.c +++ b/player/main.c @@ -30,6 +30,7 @@ #include "mpv_talloc.h" #include "misc/dispatch.h" +#include "misc/random.h" #include "misc/thread_pool.h" #include "osdep/io.h" #include "osdep/terminal.h" @@ -263,6 +264,7 @@ struct MPContext *mp_create(void) talloc_enable_leak_report(); mp_time_init(); + mp_rand_seed(0); struct MPContext *mpctx = talloc(NULL, MPContext); *mpctx = (struct MPContext){