From 67ce861718d3c0c418c0a488c46d277f8213d592 Mon Sep 17 00:00:00 2001 From: Serge Tkatchouk Date: Thu, 26 Nov 2020 07:51:55 +0800 Subject: [PATCH] Mark cache files as partial until `ffmpeg` finishes without errors --- server/encode/encode.go | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/server/encode/encode.go b/server/encode/encode.go index 2b64328..ff38a49 100644 --- a/server/encode/encode.go +++ b/server/encode/encode.go @@ -110,13 +110,15 @@ func ffmpegCommand(filePath string, profile Profile) *exec.Cmd { } func encode(out io.Writer, trackPath, cachePath string, profile Profile) error { + // prepare cache part file path + cachePartPath := fmt.Sprintf("%s.part", cachePath) // prepare the command and file descriptors cmd := ffmpegCommand(trackPath, profile) pipeReader, pipeWriter := io.Pipe() cmd.Stdout = pipeWriter cmd.Stderr = pipeWriter - // create cache file - cacheFile, err := os.Create(cachePath) + // create cache part file + cacheFile, err := os.Create(cachePartPath) if err != nil { return fmt.Errorf("writing to cache file %q: %v: %w", cachePath, err, err) } @@ -130,12 +132,14 @@ func encode(out io.Writer, trackPath, cachePath string, profile Profile) error { if err := cmd.Run(); err != nil { return fmt.Errorf("running ffmpeg: %w", err) } - // close all pipes and flush cache file + // close all pipes and flush cache part file _ = pipeWriter.Close() if err := cacheFile.Sync(); err != nil { return fmt.Errorf("flushing %q: %w", cachePath, err) } _ = cacheFile.Close() + // rename cache part file to mark it as valid cache file + os.Rename(cachePartPath, cachePath) return nil }