Skip to content

Commit 45d3faf

Browse files
authored
server : generate unique tmp filenames (#2718)
#Summary This Merge Request adds a mechanism to generate unique filenames for FFmpeg conversions in whisper_server.cpp. Previously, a single fixed filename was used (e.g., whisper-server-tmp.wav), which could result in unexpected file overwrites under certain circumstances. By generating a unique filename per request, any risk of overwriting temporary files is eliminated. #Background / Motivation • Problem: Relying on a static filename for temporary audio files may lead to overwrites if multiple operations occur simultaneously or if the same file name is reused. • Goal: Dynamically generate unique filenames, ensuring each request or operation uses an isolated temporary file.
1 parent 2ab2eb5 commit 45d3faf

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

examples/server/server.cpp

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,24 @@ void check_ffmpeg_availibility() {
223223
}
224224
}
225225

226+
std::string generate_temp_filename(const std::string &prefix, const std::string &extension) {
227+
auto now = std::chrono::system_clock::now();
228+
auto now_time_t = std::chrono::system_clock::to_time_t(now);
229+
230+
static std::mt19937 rng{std::random_device{}()};
231+
std::uniform_int_distribution<long long> dist(0, 1'000'000'000);
232+
233+
std::stringstream ss;
234+
ss << prefix
235+
<< "-"
236+
<< std::put_time(std::localtime(&now_time_t), "%Y%m%d-%H%M%S")
237+
<< "-"
238+
<< dist(rng)
239+
<< extension;
240+
241+
return ss.str();
242+
}
243+
226244
bool convert_to_wav(const std::string & temp_filename, std::string & error_resp) {
227245
std::ostringstream cmd_stream;
228246
std::string converted_filename_temp = temp_filename + "_temp.wav";
@@ -692,9 +710,7 @@ int main(int argc, char ** argv) {
692710
if (sparams.ffmpeg_converter) {
693711
// if file is not wav, convert to wav
694712
// write to temporary file
695-
//const std::string temp_filename_base = std::tmpnam(nullptr);
696-
const std::string temp_filename_base = "whisper-server-tmp"; // TODO: this is a hack, remove when the mutext is removed
697-
const std::string temp_filename = temp_filename_base + ".wav";
713+
const std::string temp_filename = generate_temp_filename("whisper-server", ".wav");
698714
std::ofstream temp_file{temp_filename, std::ios::binary};
699715
temp_file << audio_file.content;
700716
temp_file.close();

0 commit comments

Comments
 (0)