package main

import (
	"fmt"
	"os/exec"
	"time"
)

func ffmpegGenerateMP4() {
	inputPattern := "./output/img_glitched_%d.jpeg"
	outputVideo := "output.mp4"

	cmd := exec.Command(
		"ffmpeg",
		"-y",
		"-framerate", "30",
		"-i", inputPattern,
		"-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2,setpts=PTS*2.0", // Scale and slow down playback
		"-vcodec", "libx264", // Use H.264 codec
		"-pix_fmt", "yuv420p",
		"-crf", "23", // Compression level: lower is higher quality (range: 18-28)
		"-preset", "fast",
		outputVideo,
	)

	done := make(chan bool)

	go func() {
		err := cmd.Run()
		check(err, "cannot run ffmpeg command!")
		done <- true
	}()

	go func() {
		msg := "Generating MP4"
		c := 0
		for {
			select {
			case <-done:
				return
			default:
				fmt.Printf("\r%s%s", msg, dots(c))
				c = (c + 1)
				time.Sleep(500 * time.Millisecond)
			}
		}
	}()
	<-done
	fmt.Println("\nGIF successfully created in ./output.mp4!")
}
