105 lines
2.2 KiB
Go
105 lines
2.2 KiB
Go
package task
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"os/exec"
|
|
"sync"
|
|
|
|
"git.lastassault.de/speatzle/morffix/config"
|
|
"git.lastassault.de/speatzle/morffix/types"
|
|
)
|
|
|
|
type countReader struct {
|
|
io.Reader
|
|
n int
|
|
}
|
|
|
|
func (w *countReader) Read(p []byte) (int, error) {
|
|
n, err := w.Reader.Read(p)
|
|
w.n += n
|
|
return n, err
|
|
}
|
|
|
|
// dropCR drops a terminal \r from the data.
|
|
func dropCR(data []byte) []byte {
|
|
if len(data) > 0 && data[len(data)-1] == '\r' {
|
|
return data[0 : len(data)-1]
|
|
}
|
|
return data
|
|
}
|
|
|
|
func scanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
|
|
if atEOF && len(data) == 0 {
|
|
return 0, nil, nil
|
|
}
|
|
if i := bytes.IndexByte(data, '\n'); i >= 0 {
|
|
// We have a full newline-terminated line.
|
|
return i + 1, dropCR(data[0:i]), nil
|
|
}
|
|
if i := bytes.IndexByte(data, '\r'); i >= 0 {
|
|
// We have a return line.
|
|
return i + 1, dropCR(data[0:i]), nil
|
|
}
|
|
// If we're at EOF, we have a final, non-terminated line. Return it.
|
|
if atEOF {
|
|
return len(data), dropCR(data), nil
|
|
}
|
|
// Request more data.
|
|
return 0, nil, nil
|
|
}
|
|
|
|
func runFfmpegCommand(ctx context.Context, l *slog.Logger, conf config.Config, command types.FFmpegCommand) error {
|
|
l.InfoContext(ctx, "Running ffmpeg", "args", command.GetArgs())
|
|
cmd := exec.CommandContext(ctx, conf.Worker.FFmpegPath, command.GetArgs()...)
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
stdout, err := cmd.StdoutPipe()
|
|
if err != nil {
|
|
return fmt.Errorf("Error getting StdoutPipe: %w", err)
|
|
}
|
|
|
|
wg.Add(1)
|
|
outScanner := bufio.NewScanner(stdout)
|
|
outScanner.Split(scanLines)
|
|
go func() {
|
|
for outScanner.Scan() {
|
|
l.InfoContext(ctx, outScanner.Text())
|
|
}
|
|
wg.Done()
|
|
}()
|
|
|
|
stderr, err := cmd.StderrPipe()
|
|
if err != nil {
|
|
return fmt.Errorf("Error getting StderrPipe: %w", err)
|
|
}
|
|
wg.Add(1)
|
|
errScanner := bufio.NewScanner(stderr)
|
|
errScanner.Split(scanLines)
|
|
go func() {
|
|
for errScanner.Scan() {
|
|
l.InfoContext(ctx, errScanner.Text())
|
|
}
|
|
wg.Done()
|
|
}()
|
|
|
|
err = cmd.Start()
|
|
if err != nil {
|
|
l.ErrorContext(ctx, "Error Starting ffmpeg", "err", err)
|
|
return fmt.Errorf("Error Starting ffmpeg: %w", err)
|
|
}
|
|
|
|
wg.Wait()
|
|
|
|
err = cmd.Wait()
|
|
if err != nil {
|
|
l.ErrorContext(ctx, "Error Running ffmpeg", "err", err)
|
|
return fmt.Errorf("Error Running ffmpeg: %w", err)
|
|
}
|
|
return nil
|
|
}
|