Mark cache files as partial until ffmpeg finishes without errors

This commit is contained in:
Serge Tkatchouk
2020-11-26 07:51:55 +08:00
committed by Senan Kelly
parent 9541b86938
commit 67ce861718

View File

@@ -110,13 +110,15 @@ func ffmpegCommand(filePath string, profile Profile) *exec.Cmd {
} }
func encode(out io.Writer, trackPath, cachePath string, profile Profile) error { 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 // prepare the command and file descriptors
cmd := ffmpegCommand(trackPath, profile) cmd := ffmpegCommand(trackPath, profile)
pipeReader, pipeWriter := io.Pipe() pipeReader, pipeWriter := io.Pipe()
cmd.Stdout = pipeWriter cmd.Stdout = pipeWriter
cmd.Stderr = pipeWriter cmd.Stderr = pipeWriter
// create cache file // create cache part file
cacheFile, err := os.Create(cachePath) cacheFile, err := os.Create(cachePartPath)
if err != nil { if err != nil {
return fmt.Errorf("writing to cache file %q: %v: %w", cachePath, err, err) 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 { if err := cmd.Run(); err != nil {
return fmt.Errorf("running ffmpeg: %w", err) return fmt.Errorf("running ffmpeg: %w", err)
} }
// close all pipes and flush cache file // close all pipes and flush cache part file
_ = pipeWriter.Close() _ = pipeWriter.Close()
if err := cacheFile.Sync(); err != nil { if err := cacheFile.Sync(); err != nil {
return fmt.Errorf("flushing %q: %w", cachePath, err) return fmt.Errorf("flushing %q: %w", cachePath, err)
} }
_ = cacheFile.Close() _ = cacheFile.Close()
// rename cache part file to mark it as valid cache file
os.Rename(cachePartPath, cachePath)
return nil return nil
} }