Skip to content

Effort free video editing!

Let --output be a device or pipe

WyattBlue80f31f7862c0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 500c1c6e..daa600c9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@
- The `text` action takes `:ass`, which reads the text as raw ASS override tags, including in vertical layout.
- `whisper --language` takes three-letter codes, tags like `en-US`, and language names. An unknown language is now an error.
- With an explicit `--output`, retimed subtitle sidecars are named after the output and written beside it (`video.en.srt` with `-o out/final.mp4` gives `out/final.en.srt`).
+ - `--output` can be a device or pipe, like `/dev/null`, `/dev/stdout`, or `>(cmd)`. MP4 sent to a pipe is fragmented so it plays.
## Performance
- Rendering transitions is faster.
diff --git a/src/av.nim b/src/av.nim
index 56ff9fe6..85cadb61 100644
--- a/src/av.nim
+++ b/src/av.nim
@@ -541,9 +541,10 @@ type OutputContainer* = object
started: bool = false
streaming*: bool = false # consumers tail/mirror the file; writes must be append-only
-proc openWrite*(file: string): OutputContainer =
+proc openWrite*(file: string, format: ptr AVOutputFormat = nil): OutputContainer =
+ ## Without a `format`, FFmpeg guesses one from the extension of `file`.
let formatCtx: ptr AVFormatContext = nil
- discard avformat_alloc_output_context2(addr formatCtx, nil, nil, file.cstring)
+ discard avformat_alloc_output_context2(addr formatCtx, format, nil, file.cstring)
if formatCtx == nil:
error "Could not create output context"
diff --git a/src/conductor.nim b/src/conductor.nim
index d9b711fd..1c44f4ed 100644
--- a/src/conductor.nim
+++ b/src/conductor.nim
@@ -196,10 +196,18 @@ proc exportExt(ext: string, myExport: ExportKind, hasVideo: bool): string =
if hasVideo and not holdsVideo("x" & ext): ".mp4" else: ext
else: ext
+type OutputTarget = tuple
+ path: string # where to write
+ kind: ExportKind
+ formatName: string # a name whose extension picks the container
+
proc setOutput(userOut: string, `export`: ExportKind, path: string,
- isUrl = false, hasVideo = false): (string, ExportKind) {.raises: [AutoEditorError].} =
+ isUrl = false, hasVideo = false): OutputTarget {.raises: [AutoEditorError].} =
var dir, name, ext: string
- if userOut == "" or userOut == "-":
+ let device = userOut != "" and userOut != "-" and isDevicePath(userOut)
+ if device:
+ ext = agSplitFile(userOut).ext
+ elif userOut == "" or userOut == "-":
if path == "":
error "`--output` must be set." # When a timeline file is the input.
(dir, name, ext) = agSplitFile(path)
@@ -239,15 +247,20 @@ proc setOutput(userOut: string, `export`: ExportKind, path: string,
ext = fitted
if userOut == "-":
- return ("-", myExport)
+ return ("-", myExport, "-" & ext)
+ if device:
+ # A device keeps its name; the format comes from what a file would be.
+ return (userOut, myExport, "x" & ext)
if userOut == "":
- return (&"{root}_ALTERED{ext}", myExport)
+ let path = &"{root}_ALTERED{ext}"
+ return (path, myExport, path)
- return (&"{root}{ext}", myExport)
+ let path = &"{root}{ext}"
+ return (path, myExport, path)
proc defaultOutput*(input: string, `export`: ExportKind, hasVideo: bool): string =
## Where an export of `input` goes when no output is asked for.
- setOutput("", `export`, input, hasVideo = hasVideo)[0]
+ setOutput("", `export`, input, hasVideo = hasVideo).path
proc setVideoCodec(inCodec: string, src: MediaInfo, rule: Rules,
isUrl = false): string {.raises: [].} =
@@ -697,20 +710,21 @@ proc editMedia*(args: var mainArgs, inputVideo: VideoSettings, audio: AudioSetti
mi = built.mi
var exportKind: ExportKind
+ var formatName: string
var tlName: string
var fcpVersion: uint8
let hasVideo = tlV3.v.len > 0 and not args.vn
if args.`export`.kind == exAuto:
- (output, exportKind) = setOutput(args.output, exAuto, usePath, args.urlInput,
- hasVideo)
+ (output, exportKind, formatName) = setOutput(args.output, exAuto, usePath,
+ args.urlInput, hasVideo)
tlName = args.`export`.name
fcpVersion = args.`export`.version
else:
exportKind = args.`export`.kind
tlName = args.`export`.name
fcpVersion = args.`export`.version
- (output, _) = setOutput(args.output, exportKind, usePath, args.urlInput,
- hasVideo)
+ (output, _, formatName) = setOutput(args.output, exportKind, usePath,
+ args.urlInput, hasVideo)
if args.preview:
preview(tlV3)
@@ -768,13 +782,29 @@ proc editMedia*(args: var mainArgs, inputVideo: VideoSettings, audio: AudioSetti
if output == "-":
error "Exporting media files to stdout is not supported."
- let rule = initRules(output)
+ let rule = initRules(formatName)
+ let device = isDevicePath(output)
+ if device:
+ # Faststart reopens the finished file to read it back, which a device
+ # (even /dev/stdout redirected to a file) won't allow.
+ if args.faststart:
+ warning "--faststart needs a regular file; writing without it"
+ args.faststart = false
+ args.noFaststart = true
+ if isPipePath(output) and
+ $rule.format.name in ["mp4", "mov", "ipod", "3gp", "3g2", "psp", "f4v"]:
+ if args.noFragmented:
+ error &"{rule.format.name} can't be written to a pipe without " &
+ "fragmenting; drop --no-fragmented"
+ args.fragmented = true
var video = inputVideo
video.codec = setVideoCodec(video.codec, mi, rule, args.urlInput)
let cache = newMediaCache()
defer: cache.close()
if exportKind == exClipSequence:
+ if device:
+ error "clip-sequence export writes several files; --output must be a file path"
if not tlV3.isLinear:
error "Timeline too complex to use clip-sequence export"
@@ -808,8 +838,9 @@ proc editMedia*(args: var mainArgs, inputVideo: VideoSettings, audio: AudioSetti
makeMedia(args, video, audio, tlV3, output, rule, bar, cache)
# Retiming embedded subtitles is handled by makeMedia. Also retime every
- # subtitle-only sibling of each original media input into its own sidecar.
- for input in args.inputs:
+ # subtitle-only sibling of each original media input into its own sidecar,
+ # named after the output, which a device has no room for.
+ for input in (if device: @[] else: args.inputs):
let (inputDir, inputName, _) = agSplitFile(input)
var inputLayer: seq[Clip]
let baseLayer =
@@ -858,7 +889,7 @@ proc editMedia*(args: var mainArgs, inputVideo: VideoSettings, audio: AudioSetti
let seconds = round(epochTime() - startTime, 2)
notice &"Finished. took {seconds} seconds ({toTimecode(seconds, Code.display)})"
- if args.noOpen:
+ if args.noOpen or device:
discard
elif args.open:
when not defined(emscripten):
diff --git a/src/exports/otio.nim b/src/exports/otio.nim
index 45fb442b..05ba6deb 100644
--- a/src/exports/otio.nim
+++ b/src/exports/otio.nim
@@ -520,7 +520,8 @@ proc otioWrite*(name, output: string, tl: v3) =
# picture doesn't cover the frame. (Premiere's color-matte generator references a
# project-local item by GUID and can't be carried portably, so it isn't used.)
var videoTrackNum = 0
- if output != "-" and tl.bg != RGBColor(red: 0, green: 0, blue: 0):
+ if output != "-" and not isDevicePath(output) and
+ tl.bg != RGBColor(red: 0, green: 0, blue: 0):
let (dir, nm, _) = splitFile(output)
let pngPath = dir / (nm & "-bg.png")
writeSolidPng(pngPath, tl.res[0], tl.res[1], tl.bg.toRgb)
diff --git a/src/main.nim b/src/main.nim
index 8f3e0083..5ec7e5ca 100644
--- a/src/main.nim
+++ b/src/main.nim
@@ -676,7 +676,7 @@ judge making cuts.
".json", ".v1", ".v2", ".v3"]
var capturePath: string
if keepRecording:
- if args.output == "-":
+ if args.output == "-" or isDevicePath(args.output):
capturePath = "mic_RECORDING.mka"
else:
let (outDir, outName, _) = agSplitFile(args.output)
diff --git a/src/render/format.nim b/src/render/format.nim
index 51d04bc1..afd9c2a2 100644
--- a/src/render/format.nim
+++ b/src/render/format.nim
@@ -173,7 +173,7 @@ proc makeMedia*(args: mainArgs, inputVideo: VideoSettings, audio: AudioSettings,
elif not args.noFaststart:
options.add("movflags", "faststart")
- var output = openWrite(outputPath)
+ var output = openWrite(outputPath, rules.format)
output.options = options
output.streaming = args.fragmented and not args.noFragmented
diff --git a/src/util/fun.nim b/src/util/fun.nim
index 2a777ab2..3b70339b 100644
--- a/src/util/fun.nim
+++ b/src/util/fun.nim
@@ -104,6 +104,38 @@ func toTimecode*(secs: float, fmt: Code): string =
of display:
&"{sign}{h:d}:{m:02d}:{s.round.int:02d}"
+when defined(posix):
+ from std/posix import Stat, stat, S_ISREG, S_ISDIR, S_ISFIFO, S_ISSOCK
+
+proc isDevicePath*(path: string): bool {.raises: [].} =
+ ## Whether `path` names something other than a file to create or replace:
+ ## a device (/dev/null), a pipe (/dev/stdout, `>(cmd)`), or a socket. Its
+ ## name is fixed, so nothing may add an extension or derive siblings from it.
+ when defined(windows):
+ let (_, name, _) = splitFile(path)
+ path.startsWith(r"\\.\") or name.toUpperAscii in ["NUL", "CON", "PRN",
+ "AUX", "COM1", "COM2", "COM3", "COM4", "LPT1", "LPT2", "LPT3"]
+ elif defined(posix) and not defined(emscripten):
+ # An alias of an open descriptor (/dev/stdout redirected to a file)
+ # stats as whatever it points at.
+ if path in ["/dev/stdout", "/dev/stderr"] or path.startsWith("/dev/fd/") or
+ path.startsWith("/proc/") and "/fd/" in path:
+ return true
+ var st: Stat
+ stat(path.cstring, st) == 0 and not S_ISREG(st.st_mode) and
+ not S_ISDIR(st.st_mode)
+ else:
+ false
+
+proc isPipePath*(path: string): bool {.raises: [].} =
+ ## Whether writing `path` can't seek back, as a muxer finishing its header
+ ## would.
+ when defined(posix) and not defined(emscripten):
+ var st: Stat
+ stat(path.cstring, st) == 0 and (S_ISFIFO(st.st_mode) or S_ISSOCK(st.st_mode))
+ else:
+ false
+
func agSplitFile*(path: string): tuple[dir, name, ext: string] =
## Platform-independent splitFile. Treats both '/' and '\' as path separators
## on every OS, so results don't drift between Linux, macOS, and Windows.
diff --git a/src/util/rules.nim b/src/util/rules.nim
index 9ccc774d..46fdc943 100644
--- a/src/util/rules.nim
+++ b/src/util/rules.nim
@@ -11,6 +11,9 @@ func allowsCodec*(self: Rules, codecId: AVCodecID): bool =
var tag: cuint = 0
return av_codec_get_tag2(self.ofmt.codec_tag, codecId, addr tag) > 0
+func format*(self: Rules): ptr AVOutputFormat =
+ self.ofmt
+
func defaultVid*(self: Rules): AVCodecID =
self.ofmt.video_codec