// Package pkg contains the streaming concatenation and upload primitives // used by ytcat. package pkg import ( "context" "errors" "fmt" "io" "io/fs" "os" "os/exec" "strings" ) // Check verifies that every source is an existing regular file and returns // their total size in bytes. func Check(sources []string) (int64, error) { var total int64 for _, source := range sources { info, err := os.Stat(source) if err != nil { return 0, fmt.Errorf("could not open file %q: %w", source, err) } if !info.Mode().IsRegular() { return 0, fmt.Errorf("file is not a regular file: %q", source) } total += info.Size() } return total, nil } // Stream is a running ffmpeg process that concatenates the sources and writes // an MPEG-TS stream to stdout. MPEG-TS needs no seeking, so the video data is // never written to a temporary file. type Stream struct { cmd *exec.Cmd out io.ReadCloser cancel context.CancelFunc playlistFile string } // NewStream prepares an ffmpeg process that concatenates sources into a single // MPEG-TS stream. The returned Stream must be started with Start before its // Reader is used. // // The concat demuxer is driven by a small playlist file in the system temp // directory. Only metadata is written to disk; the media itself is streamed // from ffmpeg to the caller. func NewStream(ctx context.Context, sources []string, ffmpeg FFmpeg, logLevel string) (*Stream, error) { if len(sources) == 0 { return nil, fmt.Errorf("no sources given") } if logLevel == "" { logLevel = "error" } playlistFile, err := writePlaylist(sources) if err != nil { return nil, err } ctx, cancel := context.WithCancel(ctx) args := make([]string, 0, len(ffmpeg.Args)+10) args = append(args, ffmpeg.Args...) args = append(args, "-hide_banner", "-loglevel", logLevel, "-protocol_whitelist", "file", "-f", "concat", "-safe", "0", "-i", playlistFile, "-c", "copy", "-f", "mpegts", "pipe:1", ) cmd := exec.CommandContext(ctx, ffmpeg.Command, args...) cmd.Stderr = os.Stderr out, err := cmd.StdoutPipe() if err != nil { cancel() _ = os.Remove(playlistFile) return nil, fmt.Errorf("could not create ffmpeg stdout pipe: %w", err) } return &Stream{cmd: cmd, out: out, cancel: cancel, playlistFile: playlistFile}, nil } // Start starts the ffmpeg process. On failure the playlist file is removed. func (s *Stream) Start() error { if err := s.cmd.Start(); err != nil { s.cancel() return errors.Join(fmt.Errorf("could not start ffmpeg: %w", err), s.removePlaylist()) } return nil } // Reader returns the MPEG-TS stream produced by ffmpeg. func (s *Stream) Reader() io.Reader { return s.out } // Close stops ffmpeg if it is still running, waits for it to exit and removes // the playlist file. It must only be called after the reader has been fully // consumed or is no longer needed. func (s *Stream) Close() error { s.cancel() if s.out != nil { _ = s.out.Close() } var waitErr error if err := s.cmd.Wait(); err != nil { waitErr = fmt.Errorf("ffmpeg failed: %w", err) } return errors.Join(waitErr, s.removePlaylist()) } func (s *Stream) removePlaylist() error { if s.playlistFile == "" { return nil } name := s.playlistFile s.playlistFile = "" if err := os.Remove(name); err != nil && !errors.Is(err, fs.ErrNotExist) { return fmt.Errorf("could not remove playlist file %q: %w", name, err) } return nil } // writePlaylist writes a concat demuxer playlist for sources to a temporary // file and returns its path. func writePlaylist(sources []string) (string, error) { f, err := os.CreateTemp("", "ytcat-playlist-*") if err != nil { return "", fmt.Errorf("could not create playlist file: %w", err) } name := f.Name() if _, err := io.WriteString(f, playlist(sources)); err != nil { _ = f.Close() _ = os.Remove(name) return "", fmt.Errorf("could not write playlist file %q: %w", name, err) } if err := f.Close(); err != nil { _ = os.Remove(name) return "", fmt.Errorf("could not close playlist file %q: %w", name, err) } return name, nil } // playlist renders the ffmpeg concat demuxer playlist for sources. func playlist(sources []string) string { var b strings.Builder for _, source := range sources { fmt.Fprintf(&b, "file '%s'\n", escapePath(source)) } return b.String() } // escapePath escapes a path for use inside a single-quoted concat demuxer // file directive. Backslashes and single quotes are escaped with a backslash. func escapePath(path string) string { path = strings.ReplaceAll(path, `\`, `\\`) path = strings.ReplaceAll(path, `'`, `\'`) return path }