Effort free video editing!
Replace continue with structured branches
WyattBlueaba6bb871737
diff --git a/src/action.nim b/src/action.nimindex 53dafe57..1e4366dd 100644--- a/src/action.nim+++ b/src/action.nim@@ -2317,42 +2317,39 @@ when not defined(nimscript):var pendDur = 0.0'f32for part in splitUnescaped(val.strip(), ',', textOnly = true):let trimmedPart = part.strip()- if trimmedPart == "nil":- continue- if trimmedPart == "cut":- return aCut-- let segs = trimmedPart.split(":")- if segs[0] == "ease" and segs.len in {2, 3}:- pendActive = true- pendCurve = parseEasing(segs[1])- if segs.len == 3:- (pendDur, pendUnit) = parseDuration(segs[2])+ if trimmedPart != "nil":+ if trimmedPart == "cut":+ return aCut++ let segs = trimmedPart.split(":")+ if segs[0] == "ease" and segs.len in {2, 3}:+ pendActive = true+ pendCurve = parseEasing(segs[1])+ if segs.len == 3:+ (pendDur, pendUnit) = parseDuration(segs[2])+ else:+ pendUnit = duClip+ pendDur = 0.0'f32else:- pendUnit = duClip- pendDur = 0.0'f32- continue-- var action = parseAction(trimmedPart)- if pendActive and action.kind in {actZoom, actBlur, actOpacity, actBrightness,- actVolume, actPos, actPixelate} and not action.hasEase:- action.hasEase = true- action.easeCurve = pendCurve- # Timed keyframes keep their own timing; they take only the curve.- if not action.isTimed:- action.easeDurUnit = pendUnit- action.easeDur = pendDur- if action.kind == actLuv:- # Adjacent-fusion: collapse this actLuv into previous one if it's also actLuv.- # Per field, the non-identity value wins; later wins on genuine conflicts.- if list.len > 0 and list[^1].kind == actLuv:- var prev = list[^1]- if action.brighthue != luvBrighthueId: prev.brighthue = action.brighthue- if action.contrast != luvContrastId: prev.contrast = action.contrast- if action.saturation != luvSaturationId: prev.saturation = action.saturation- list[^1] = prev- continue- list.add action+ var action = parseAction(trimmedPart)+ if pendActive and action.kind in {actZoom, actBlur, actOpacity, actBrightness,+ actVolume, actPos, actPixelate} and not action.hasEase:+ action.hasEase = true+ action.easeCurve = pendCurve+ # Timed keyframes keep their own timing; they take only the curve.+ if not action.isTimed:+ action.easeDurUnit = pendUnit+ action.easeDur = pendDur+ # Adjacent-fusion: collapse this actLuv into previous one if it's also actLuv.+ # Per field, the non-identity value wins; later wins on genuine conflicts.+ if action.kind == actLuv and list.len > 0 and list[^1].kind == actLuv:+ var prev = list[^1]+ if action.brighthue != luvBrighthueId: prev.brighthue = action.brighthue+ if action.contrast != luvContrastId: prev.contrast = action.contrast+ if action.saturation != luvSaturationId: prev.saturation = action.saturation+ list[^1] = prev+ else:+ list.add action# Drop any all-identity actLuv (no-op), and canonicalize `loop`: it's a# per-clip flag, not an ordered effect, so any number of `loop` tokens@@ -2363,11 +2360,11 @@ when not defined(nimscript):for a in list:if a.kind == actLuv and a.brighthue == luvBrighthueId anda.contrast == luvContrastId and a.saturation == luvSaturationId:- continue- if a.kind == actLoop:+ discard+ elif a.kind == actLoop:hasLoop = true- continue- pruned.add a+ else:+ pruned.add aif hasLoop:pruned.insert(Action(kind: actLoop), 0)return newActions(pruned)diff --git a/src/analyze/audio.nim b/src/analyze/audio.nimindex e0c63a43..d4e8cb9a 100644--- a/src/analyze/audio.nim+++ b/src/analyze/audio.nim@@ -438,10 +438,10 @@ proc streamPeaks*(input: string, stream, samplesPerBucket: int,let bar = initBar(BarType.none) # for the cancel flagfor (bucketStart, peaks) in processor.channelPeaks(container, audioStream, channels):bar.tick(0)- if bucketStart + samplesPerBucket <= startSample: continue- if bucketStart >= endSample: break- for c in 0 ..< min(n, peaks.len):- if result[c].firstSample < 0: result[c].firstSample = bucketStart- result[c].peaks.add peaks[c]+ if bucketStart + samplesPerBucket > startSample:+ if bucketStart >= endSample: break+ for c in 0 ..< min(n, peaks.len):+ if result[c].firstSample < 0: result[c].firstSample = bucketStart+ result[c].peaks.add peaks[c]for w in result.mitems:if w.firstSample < 0: w.firstSample = startSamplediff --git a/src/analyze/blackdetect.nim b/src/analyze/blackdetect.nimindex e015cf23..53026cb7 100644--- a/src/analyze/blackdetect.nim+++ b/src/analyze/blackdetect.nim@@ -39,15 +39,15 @@ proc blackLumaMax(fmt: AVPixelFormat, range: AVColorRange, thres: uint8): int =error "Could not allocate luma probe"let vsub = av_pix_fmt_desc_get(fmt).log2_chroma_h.intfor p in 0 ..< src.data.len:- if src.data[p] == nil: continue- # Other planes get neutral chroma; fill no more rows than a subsampled- # plane has.- let rows = (if p == 0: h else: (h + (1 shl vsub) - 1) shr vsub)- for y in 0 ..< rows:- let row = cast[ptr UncheckedArray[uint8]](cast[int](src.data[p]) +- y * src.linesize[p].int)- for x in 0 ..< src.linesize[p].int:- row[x] = (if p == 0: uint8(min(x, 255)) else: 128'u8)+ if src.data[p] != nil:+ # Other planes get neutral chroma; fill no more rows than a subsampled+ # plane has.+ let rows = (if p == 0: h else: (h + (1 shl vsub) - 1) shr vsub)+ for y in 0 ..< rows:+ let row = cast[ptr UncheckedArray[uint8]](cast[int](src.data[p]) ++ y * src.linesize[p].int)+ for x in 0 ..< src.linesize[p].int:+ row[x] = (if p == 0: uint8(min(x, 255)) else: 128'u8)dst.format = AV_PIX_FMT_GRAY8.cintdst.width = wdst.height = hdiff --git a/src/analyze/subtitle.nim b/src/analyze/subtitle.nimindex a8f01447..f884b13a 100644--- a/src/analyze/subtitle.nim+++ b/src/analyze/subtitle.nim@@ -35,34 +35,32 @@ proc subtitle*(container: InputContainer, tb: AVRational, pattern: Re,if packet.stream_index == s:# Duration 0 means unknown; an empty span can't mark a frame anyway.- if packet.pts == AV_NOPTS_VALUE or packet.duration <= 0:- continue+ if not (packet.pts == AV_NOPTS_VALUE or packet.duration <= 0):+ let+ startFloat = float((packet.pts - container.startPts(addr subtitleStream)) *+ subtitleStream.time_base)+ durFloat = float(packet.duration * subtitleStream.time_base)+ # A subtitle is active for any frame it overlaps, so snap outward:+ # floor the start, ceil the end. round() could clip a frame the+ # subtitle actually touches. Edit lists and hand-written srt/ass can+ # start a cue before 0.+ start = max(0, floor(startFloat * tb).int)+ `end` = ceil((startFloat + durFloat) * tb).int- let- startFloat = float((packet.pts - container.startPts(addr subtitleStream)) *- subtitleStream.time_base)- durFloat = float(packet.duration * subtitleStream.time_base)- # A subtitle is active for any frame it overlaps, so snap outward:- # floor the start, ceil the end. round() could clip a frame the- # subtitle actually touches. Edit lists and hand-written srt/ass can- # start a cue before 0.- start = max(0, floor(startFloat * tb).int)- `end` = ceil((startFloat + durFloat) * tb).int+ var gotSubtitle: cint = 0+ let ret = avcodec_decode_subtitle2(codecCtx, addr subtitle,+ addr gotSubtitle, packet)- var gotSubtitle: cint = 0- let ret = avcodec_decode_subtitle2(codecCtx, addr subtitle,- addr gotSubtitle, packet)+ if ret >= 0 and gotSubtitle != 0:+ defer: avsubtitle_free(addr subtitle)- if ret >= 0 and gotSubtitle != 0:- defer: avsubtitle_free(addr subtitle)-- length = max(length, `end`)- for i in 0..<subtitle.num_rects:- let rect = subtitle.rects[i]- if rect.`type` == SUBTITLE_ASS and rect.ass != nil:- var assText: string = $rect.ass- if match(assText.dialogue, pattern).len > 0:- spans.add((start, `end`))+ length = max(length, `end`)+ for i in 0..<subtitle.num_rects:+ let rect = subtitle.rects[i]+ if rect.`type` == SUBTITLE_ASS and rect.ass != nil:+ var assText: string = $rect.ass+ if match(assText.dialogue, pattern).len > 0:+ spans.add((start, `end`))var val = newSeq[bool](length)for span in spans:diff --git a/src/av.nim b/src/av.nimindex ed8ac730..cb58b52b 100644--- a/src/av.nim+++ b/src/av.nim@@ -489,21 +489,21 @@ iterator flushDecode*(container: InputContainer, index: cint,ret = avcodec_receive_frame(codecCtx, frame)if ret == 0:yield frame- continue- if ret != AVERROR_EAGAIN:- break # AVERROR_EOF or fatal error+ else:+ if ret != AVERROR_EAGAIN:+ break # AVERROR_EOF or fatal error- if flushed:- break+ if flushed:+ break- ret = av_read_frame(container.formatContext, packet)- if ret < 0:- discard avcodec_send_packet(codecCtx, nil) # signal end-of-stream- flushed = true- else:- if packet.stream_index == index:- discard avcodec_send_packet(codecCtx, packet)- av_packet_unref(packet)+ ret = av_read_frame(container.formatContext, packet)+ if ret < 0:+ discard avcodec_send_packet(codecCtx, nil) # signal end-of-stream+ flushed = true+ else:+ if packet.stream_index == index:+ discard avcodec_send_packet(codecCtx, packet)+ av_packet_unref(packet)proc startPts*(container: InputContainer, stream: ptr AVStream): int64 =## The container's start time in `stream`'s time base, which is time 0 to@@ -989,26 +989,24 @@ func dialogue*(assText: string): string =curChar = assText[i]nextChar = (if i + 1 >= textLen: '\0' else: assText[i + 1])- if not state:- if curChar == '\\' and nextChar == 'N':- # `\N` is a hard line break.- result &= "\n"- i += 2- continue- if curChar == '\\' and nextChar in {'n', 'h'}:- # `\n` (soft break) and `\h` (non-breaking space) collapse to a space.- result &= " "- i += 2- continue- if curChar == '\\' and nextChar in {'{', '}'}:- # libass reads `\{` and `\}` as literal braces, never as a block.- result &= nextChar- i += 2- continue- if curChar == '{' and i < lastClose:- state = true- else:- result &= curChar- elif curChar == '}':- state = false- i += 1+ if not state and curChar == '\\' and nextChar == 'N':+ # `\N` is a hard line break.+ result &= "\n"+ i += 2+ elif not state and curChar == '\\' and nextChar in {'n', 'h'}:+ # `\n` (soft break) and `\h` (non-breaking space) collapse to a space.+ result &= " "+ i += 2+ elif not state and curChar == '\\' and nextChar in {'{', '}'}:+ # libass reads `\{` and `\}` as literal braces, never as a block.+ result &= nextChar+ i += 2+ else:+ if not state:+ if curChar == '{' and i < lastClose:+ state = true+ else:+ result &= curChar+ elif curChar == '}':+ state = false+ i += 1diff --git a/src/cli.nim b/src/cli.nimindex bc0cdb9f..3ec34aa7 100644--- a/src/cli.nim+++ b/src/cli.nim@@ -367,26 +367,24 @@ func optionDidYouMean*(key: string, opts: seq[OptDef]): string =proc writeZshOptions(name: string, opts: seq[OptDef]) =echo " " & name & "=("for opt in opts:- if opt.hidden:- continue- let desc =- if opt.help != "":- opt.help.split('\n')[0].replace("'", "'\\''").replace(":", "\\:")- else: ""- for name in opt.names.split(", "):- let n = name.strip().replace(":", "\\:")- if desc != "":- echo " '" & n & ":" & desc & "'"- else:- echo " '" & n & "'"+ if not opt.hidden:+ let desc =+ if opt.help != "":+ opt.help.split('\n')[0].replace("'", "'\\''").replace(":", "\\:")+ else: ""+ for name in opt.names.split(", "):+ let n = name.strip().replace(":", "\\:")+ if desc != "":+ echo " '" & n & ":" & desc & "'"+ else:+ echo " '" & n & "'"echo " )"proc zshcomplete*() =var locals = @["subcommands", "options"]for cmd in commands:- if not cmd.shellCompletion:- continue- locals.add cmd.name & "_options"+ if cmd.shellCompletion:+ locals.add cmd.name & "_options"echo "#compdef auto-editor"echo ""@@ -394,18 +392,16 @@ proc zshcomplete*() =echo " local -a " & locals.join(" ")echo " subcommands=("for cmd in commands:- if not cmd.shellCompletion:- continue- if cmd.help != "":- echo " '" & cmd.name & ":" & cmd.help.replace("'", "'\\''") & "'"- else:- echo " '" & cmd.name & "'"+ if cmd.shellCompletion:+ if cmd.help != "":+ echo " '" & cmd.name & ":" & cmd.help.replace("'", "'\\''") & "'"+ else:+ echo " '" & cmd.name & "'"echo " )"writeZshOptions("options", mainOptions)for cmd in commands:- if not cmd.shellCompletion:- continue- writeZshOptions(cmd.name & "_options", cmd.opts)+ if cmd.shellCompletion:+ writeZshOptions(cmd.name & "_options", cmd.opts)echo """if (( CURRENT == 2 )); then_describe 'command' subcommands@@ -414,13 +410,12 @@ proc zshcomplete*() =elsecase "$words[2]" in"""for cmd in commands:- if not cmd.shellCompletion:- continue- echo " " & cmd.name & ")"- echo " _describe 'option' " & cmd.name & "_options"- if cmd.files:- echo " _files"- echo " ;;"+ if cmd.shellCompletion:+ echo " " & cmd.name & ")"+ echo " _describe 'option' " & cmd.name & "_options"+ if cmd.files:+ echo " _files"+ echo " ;;"echo """ *)_describe 'option' options_filesdiff --git a/src/cmds/cache.nim b/src/cmds/cache.nimindex 47002356..83d04851 100644--- a/src/cmds/cache.nim+++ b/src/cmds/cache.nim@@ -34,19 +34,18 @@ proc main*(args: seq[string]) =if kind == pcFile:let (_, key, ext) = agSplitFile(path)# Only .bin files with the 16-char hash prefix are cache entries.- if ext != ".bin" or key.len < 16:- continue- let size = getFileSize(path)- totalSize += size- let (sizeNum, sizeUnit) = formatBytes(size)-- let hashPart = key[0 ..< 16]- let restPart = key[16 .. ^1]-- stdout.styledWrite(fgYellow, "entry: ")- stdout.write "\e[90m", hashPart, "\e[0m"- stdout.styledWriteLine(restPart, " ", fgYellow, "size: ", fgGreen, sizeNum,- fgBlue, sizeUnit, resetStyle)+ if ext == ".bin" and key.len >= 16:+ let size = getFileSize(path)+ totalSize += size+ let (sizeNum, sizeUnit) = formatBytes(size)++ let hashPart = key[0 ..< 16]+ let restPart = key[16 .. ^1]++ stdout.styledWrite(fgYellow, "entry: ")+ stdout.write "\e[90m", hashPart, "\e[0m"+ stdout.styledWriteLine(restPart, " ", fgYellow, "size: ", fgGreen, sizeNum,+ fgBlue, sizeUnit, resetStyle)except:discarddiff --git a/src/cmds/desc.nim b/src/cmds/desc.nimindex 1f27d5ba..8b382838 100644--- a/src/cmds/desc.nim+++ b/src/cmds/desc.nim@@ -16,15 +16,16 @@ proc main*(args: seq[string]) =try:formatContext = av.openFormatCtx(inputFile.cstring)except IOError:- continue+ formatContext = nil- let entry = av_dict_get(formatContext.metadata, "description", nil, 0)- try:- if entry != nil:- stdout.write("\n" & $entry.value & "\n\n")- else:- stdout.write("\nNo description.\n\n")- except IOError:- discard+ if formatContext != nil:+ let entry = av_dict_get(formatContext.metadata, "description", nil, 0)+ try:+ if entry != nil:+ stdout.write("\n" & $entry.value & "\n\n")+ else:+ stdout.write("\nNo description.\n\n")+ except IOError:+ discard- avformat_close_input(addr formatContext)+ avformat_close_input(addr formatContext)diff --git a/src/cmds/help.nim b/src/cmds/help.nimindex 880ac111..94288bff 100644--- a/src/cmds/help.nim+++ b/src/cmds/help.nim@@ -11,24 +11,23 @@ proc printHelp*(usage: string, opts: seq[OptDef]) {.noreturn.} =echo "Options:"for opt in opts:- if opt.hidden:- continue- var optStr = " " & opt.names- if opt.metavar != "":- optStr &= " " & opt.metavar+ if not opt.hidden:+ var optStr = " " & opt.names+ if opt.metavar != "":+ optStr &= " " & opt.metavar- if optStr.len >= optWidth:- echo optStr- let wrapped = wrapText(opt.help, helpWidth, 0)- for line in wrapped.split("\n"):- echo " ".repeat(optWidth) & line- else:- let padding = optWidth - optStr.len- let wrapped = wrapText(opt.help, helpWidth, optWidth)- let helpLines = wrapped.split("\n")- echo optStr & " ".repeat(padding) & helpLines[0]- for i in 1 ..< helpLines.len:- echo helpLines[i]+ if optStr.len >= optWidth:+ echo optStr+ let wrapped = wrapText(opt.help, helpWidth, 0)+ for line in wrapped.split("\n"):+ echo " ".repeat(optWidth) & line+ else:+ let padding = optWidth - optStr.len+ let wrapped = wrapText(opt.help, helpWidth, optWidth)+ let helpLines = wrapped.split("\n")+ echo optStr & " ".repeat(padding) & helpLines[0]+ for i in 1 ..< helpLines.len:+ echo helpLines[i]echo "\n -h, --help" & " ".repeat(optWidth - 14) &wrapText("Show info about this program then exit", helpWidth, optWidth)@@ -48,13 +47,12 @@ template parseArgs*(args: seq[string], opts: seq[OptDef], usage: string,for key {.inject.} in args:if parseOptions and expecting == coNone and key == "--":parseOptions = false- continue- if parseOptions:- if genCliMacro(key, args, opts):- expectingKey = key- continue- if key in ["-h", "--help"]:- printHelp(usage, opts)- if key.startsWith(prefix):- error "Unknown option: " & key & optionDidYouMean(key, opts)- body+ elif parseOptions and genCliMacro(key, args, opts):+ expectingKey = key+ else:+ if parseOptions:+ if key in ["-h", "--help"]:+ printHelp(usage, opts)+ if key.startsWith(prefix):+ error "Unknown option: " & key & optionDidYouMean(key, opts)+ bodydiff --git a/src/cmds/info.nim b/src/cmds/info.nimindex 2c99cdc0..fcf2f457 100644--- a/src/cmds/info.nim+++ b/src/cmds/info.nim@@ -250,35 +250,32 @@ proc printCodecList(ofmt: ptr AVOutputFormat, kind: CodecListKind) =let codec = av_codec_iterate(addr opaque)if codec == nil: break- case kind- of clkEncoders:- if av_codec_is_encoder(codec) == 0: continue- if not hwEncoderUsable(codec): continue- of clkDecoders:- if av_codec_is_decoder(codec) == 0: continue- of clkCodecs:- if codec.id in seen: continue- if avcodec_find_encoder(codec.id) == nil: continue-- if avformat_query_codec(ofmt, codec.id, FF_COMPLIANCE_EXPERIMENTAL) <= 0:- continue- if kind == clkCodecs:- seen.incl(codec.id)-- var name = if kind == clkCodecs: $avcodec_get_name(codec.id) else: $codec.name- if not noColor and- avformat_query_codec(ofmt, codec.id, FF_COMPLIANCE_STRICT) <= 0:- name = "\e[31m" & name & "\e[0m"-- template bucket(list, best) =- if kind in {clkCodecs, clkEncoders} and codec.id == best: list.insert(name, 0)- else: list.add name-- case codec.`type`- of AVMEDIA_TYPE_VIDEO: bucket(videos, bestVideo)- of AVMEDIA_TYPE_AUDIO: bucket(audios, bestAudio)- of AVMEDIA_TYPE_SUBTITLE: bucket(subs, bestSubtitle)- else: others.add name+ # Whether this codec belongs in the listing `kind` asked for.+ let passesKind =+ case kind+ of clkEncoders: av_codec_is_encoder(codec) != 0 and hwEncoderUsable(codec)+ of clkDecoders: av_codec_is_decoder(codec) != 0+ of clkCodecs: codec.id notin seen and avcodec_find_encoder(codec.id) != nil++ if passesKind and+ avformat_query_codec(ofmt, codec.id, FF_COMPLIANCE_EXPERIMENTAL) > 0:+ if kind == clkCodecs:+ seen.incl(codec.id)++ var name = if kind == clkCodecs: $avcodec_get_name(codec.id) else: $codec.name+ if not noColor and+ avformat_query_codec(ofmt, codec.id, FF_COMPLIANCE_STRICT) <= 0:+ name = "\e[31m" & name & "\e[0m"++ template bucket(list, best) =+ if kind in {clkCodecs, clkEncoders} and codec.id == best: list.insert(name, 0)+ else: list.add name++ case codec.`type`+ of AVMEDIA_TYPE_VIDEO: bucket(videos, bestVideo)+ of AVMEDIA_TYPE_AUDIO: bucket(audios, bestAudio)+ of AVMEDIA_TYPE_SUBTITLE: bucket(subs, bestSubtitle)+ else: others.add nameecho "v: " & videos.join(",")echo "a: " & audios.join(",")diff --git a/src/cmds/subdump.nim b/src/cmds/subdump.nimindex 229c9d9a..4a300122 100644--- a/src/cmds/subdump.nim+++ b/src/cmds/subdump.nim@@ -21,33 +21,32 @@ iterator subtitleEvents(container: InputContainer, stream: cint):while av_read_frame(formatCtx, container.packet) >= 0:defer: av_packet_unref(container.packet)let pkt = container.packet- if pkt.stream_index != stream: continue- var gotSubtitle: cint = 0- if avcodec_decode_subtitle2(codecCtx, addr subtitle, addr gotSubtitle, pkt) < 0 or- gotSubtitle == 0:- continue- defer: avsubtitle_free(addr subtitle)- # AVSubtitle.pts is in AV_TIME_BASE when set; otherwise fall back to the- # packet pts in the stream time_base. Display times are ms relative to- # that base; some codecs (e.g. mov_text) instead carry the duration on- # the packet.- let base =- if subtitle.pts != AV_NOPTS_VALUE:- float(subtitle.pts - startUs) / AV_TIME_BASE.float- elif pkt.pts != AV_NOPTS_VALUE: float(pkt.pts - startPts) * tbSeconds- else: 0.0- let start = base + subtitle.start_display_time.float / 1000.0- let finish =- if subtitle.end_display_time > subtitle.start_display_time:- base + subtitle.end_display_time.float / 1000.0- elif pkt.duration > 0:- base + pkt.duration.float * tbSeconds- else:- start- for r in 0 ..< subtitle.num_rects:- let rect = subtitle.rects[r]- if rect.`type` == SUBTITLE_ASS and rect.ass != nil:- yield (start, finish, $rect.ass)+ if pkt.stream_index == stream:+ var gotSubtitle: cint = 0+ if avcodec_decode_subtitle2(codecCtx, addr subtitle, addr gotSubtitle, pkt) >= 0 and+ gotSubtitle != 0:+ defer: avsubtitle_free(addr subtitle)+ # AVSubtitle.pts is in AV_TIME_BASE when set; otherwise fall back to the+ # packet pts in the stream time_base. Display times are ms relative to+ # that base; some codecs (e.g. mov_text) instead carry the duration on+ # the packet.+ let base =+ if subtitle.pts != AV_NOPTS_VALUE:+ float(subtitle.pts - startUs) / AV_TIME_BASE.float+ elif pkt.pts != AV_NOPTS_VALUE: float(pkt.pts - startPts) * tbSeconds+ else: 0.0+ let start = base + subtitle.start_display_time.float / 1000.0+ let finish =+ if subtitle.end_display_time > subtitle.start_display_time:+ base + subtitle.end_display_time.float / 1000.0+ elif pkt.duration > 0:+ base + pkt.duration.float * tbSeconds+ else:+ start+ for r in 0 ..< subtitle.num_rects:+ let rect = subtitle.rects[r]+ if rect.`type` == SUBTITLE_ASS and rect.ass != nil:+ yield (start, finish, $rect.ass)type SubtitleCue* = tuple[start, stop: float64, text: string] ## secondsdiff --git a/src/conductor.nim b/src/conductor.nimindex 4d6d871c..f2a5a0b8 100644--- a/src/conductor.nim+++ b/src/conductor.nim@@ -340,11 +340,12 @@ proc applyAdds(tl: var v3, args: var mainArgs,returnvar matches = falsefor i, spec in args.adds:- if soundOnly[i]: continue # no picture, so it needs no canvas- for clip in tl.a[0]:- if clip.effects.int == spec.selector:- matches = true- break+ # Sound-only specs have no picture, so they can't match here.+ if not soundOnly[i]:+ for clip in tl.a[0]:+ if clip.effects.int == spec.selector:+ matches = true+ breakif matches: breakif not matches:return@@ -398,30 +399,28 @@ proc applyAdds(tl: var v3, args: var mainArgs,if clip.effects.int == spec.selector:track.add Clip(src: srcPtr, start: clip.start, dur: clip.dur,offset: (if follows: clip.offset else: 0), effects: eIdx, stream: 0)- if track.len == 0:- continue-- if not soundOnly[i]:- tl.langs.insert(toLang("und"), tl.v.len) # keep video langs before audio- tl.v.add track-- # An added layer is an overlay, so its sound has to be heard over the base- # rather than written beside it as a second stream (which .wav/.mp3 can't- # hold). Audio langs come last, so append.- if audioGen:- tl.langs.add toLang("und")- tl.a.add track- args.mixAudioStreams = true- else:- # The overlay's own audio, one layer per stream, on the same sections as- # its picture so the two stay in sync.- for stream in 0 ..< mis[i].a.len:- var atrack = track- for clip in atrack.mitems:- clip.stream = int16(stream)- tl.langs.add mis[i].a[stream].lang- tl.a.add atrack+ if track.len != 0:+ if not soundOnly[i]:+ tl.langs.insert(toLang("und"), tl.v.len) # keep video langs before audio+ tl.v.add track++ # An added layer is an overlay, so its sound has to be heard over the base+ # rather than written beside it as a second stream (which .wav/.mp3 can't+ # hold). Audio langs come last, so append.+ if audioGen:+ tl.langs.add toLang("und")+ tl.a.add trackargs.mixAudioStreams = true+ else:+ # The overlay's own audio, one layer per stream, on the same sections as+ # its picture so the two stay in sync.+ for stream in 0 ..< mis[i].a.len:+ var atrack = track+ for clip in atrack.mitems:+ clip.stream = int16(stream)+ tl.langs.add mis[i].a[stream].lang+ tl.a.add atrack+ args.mixAudioStreams = truetl.updateNumberOfSrc()proc applyLayers(tl: var v3, args: var mainArgs, interner: var StringInterner) =@@ -442,52 +441,52 @@ proc applyLayers(tl: var v3, args: var mainArgs, interner: var StringInterner) =let spec = args.layers[li]let first = clamp(spec.start, 0, total)let last = clamp((if spec.finish < 0: total else: spec.finish), first, total)- if last <= first: continue- var own: seq[Action]- if spec.effects.len > 0:- try:- let parsed = parseActions(spec.effects)- defer: parsed.free()- for a in parsed: own.add a- except ActionParseError as e:- error e.msg- let src = interner.intern(spec.path)- let mi = initMediaInfo(spec.path)- var track: seq[Clip]- if spec.followCuts and not mi.isStill:- # The base's sections, speeds included, so the layer stays in step- # with the source it's laid over.- var groups: Table[uint32, uint32]- for clip in base:- let a = max(clip.start, first)- let b = min(clip.start + clip.dur, last)- if b <= a: continue- # Offsets are in speed-scaled frames, so a trim of k output frames- # moves the offset by k; a speed ramp is cut down with the clip.- var part = tl.sliceClip(effectIndex, clip, a, b)- if part.effects notin groups:- var acts: seq[Action]- for x in tl.effects[part.effects]: acts.add x- acts.add own- groups[part.effects] = tl.group(effectIndex, acts)- part.src = src- part.stream = 0- part.effects = groups[part.effects]- track.add part- else:- track.add Clip(src: src, start: first, dur: last - first, offset: first,- effects: tl.group(effectIndex, own))-- if mi.v.len > 0:- tl.langs.insert(toLang("und"), tl.v.len) # keep video langs before audio- tl.v.add track- # Its sound is heard over the base, like an `add:` layer's.- for stream in 0 ..< mi.a.len:- var atrack = track- for clip in atrack.mitems: clip.stream = int16(stream)- tl.langs.add mi.a[stream].lang- tl.a.add atrack- args.mixAudioStreams = true+ if last > first:+ var own: seq[Action]+ if spec.effects.len > 0:+ try:+ let parsed = parseActions(spec.effects)+ defer: parsed.free()+ for a in parsed: own.add a+ except ActionParseError as e:+ error e.msg+ let src = interner.intern(spec.path)+ let mi = initMediaInfo(spec.path)+ var track: seq[Clip]+ if spec.followCuts and not mi.isStill:+ # The base's sections, speeds included, so the layer stays in step+ # with the source it's laid over.+ var groups: Table[uint32, uint32]+ for clip in base:+ let a = max(clip.start, first)+ let b = min(clip.start + clip.dur, last)+ if b > a:+ # Offsets are in speed-scaled frames, so a trim of k output frames+ # moves the offset by k; a speed ramp is cut down with the clip.+ var part = tl.sliceClip(effectIndex, clip, a, b)+ if part.effects notin groups:+ var acts: seq[Action]+ for x in tl.effects[part.effects]: acts.add x+ acts.add own+ groups[part.effects] = tl.group(effectIndex, acts)+ part.src = src+ part.stream = 0+ part.effects = groups[part.effects]+ track.add part+ else:+ track.add Clip(src: src, start: first, dur: last - first, offset: first,+ effects: tl.group(effectIndex, own))++ if mi.v.len > 0:+ tl.langs.insert(toLang("und"), tl.v.len) # keep video langs before audio+ tl.v.add track+ # Its sound is heard over the base, like an `add:` layer's.+ for stream in 0 ..< mi.a.len:+ var atrack = track+ for clip in atrack.mitems: clip.stream = int16(stream)+ tl.langs.add mi.a[stream].lang+ tl.a.add atrack+ args.mixAudioStreams = truetl.updateNumberOfSrc()type BuiltTimeline* = object@@ -609,29 +608,29 @@ proc buildTimeline*(args: var mainArgs, audio: AudioSettings,getConLen())else:remapRange(actionIndex, span, tbf, remap, getConLen())- continue- # A set-action range is an explicit override, conceptually distinct- # from the `-w:0`/`-w:1` (silent/normal) sections. Give it a unique- # effects index (never deduping into indices 0/1) so an `add` selector- # matches only what it should: `-w:1 add` overlays genuine active- # sections, not a `--set-action`/`--add-in` range, and a set-action's- # own `add` matches just that range.- actionMap.add actionRange[0]- let aIdx = actionMap.len - 1- if args.setActionConcat:- # An editor's range, over the inputs end to end: only its part on- # this input applies, in this input's frames.- let lo = max(toTb(span[0], tbf) - concatOffset, 0)- let hi = min(toTb(span[1], tbf) - concatOffset, labels.len)- if hi > lo:- applyToRange(actionIndex, (frames(lo), frames(hi)), tbf, aIdx,- getConLen())else:- applyToRange(actionIndex, span, tbf, aIdx, getConLen())- if i == 0:- for a in args.adds.mitems:- if a.setActionRef == sIdx:- a.selector = aIdx+ # A set-action range is an explicit override, conceptually distinct+ # from the `-w:0`/`-w:1` (silent/normal) sections. Give it a unique+ # effects index (never deduping into indices 0/1) so an `add` selector+ # matches only what it should: `-w:1 add` overlays genuine active+ # sections, not a `--set-action`/`--add-in` range, and a set-action's+ # own `add` matches just that range.+ actionMap.add actionRange[0]+ let aIdx = actionMap.len - 1+ if args.setActionConcat:+ # An editor's range, over the inputs end to end: only its part on+ # this input applies, in this input's frames.+ let lo = max(toTb(span[0], tbf) - concatOffset, 0)+ let hi = min(toTb(span[1], tbf) - concatOffset, labels.len)+ if hi > lo:+ applyToRange(actionIndex, (frames(lo), frames(hi)), tbf, aIdx,+ getConLen())+ else:+ applyToRange(actionIndex, span, tbf, aIdx, getConLen())+ if i == 0:+ for a in args.adds.mitems:+ if a.setActionRef == sIdx:+ a.selector = aIdxlet inputMi = initMediaInfo(container.formatContext, args.inputs[i])@@ -880,38 +879,33 @@ proc editMedia*(args: var mainArgs, inputVideo: VideoSettings, audio: AudioSettiif clip.src != nil and clip.src[] == input:inputLayer.add clip- if inputLayer.len == 0:- continue-- var siblings: seq[string]- for kind, name in walkDir(if inputDir == "": "." else: inputDir, relative = true):- if kind in {pcFile, pcLinkToFile} and name.startsWith(inputName & "."):- siblings.add inputDir / name- siblings.sort()- for sibling in siblings:- if sibling == input:- continue- var sidecar: InputContainer- try:- sidecar = av.open(sibling)- except IOError:- continue- let isSubtitleOnly = sidecar.subtitle.len > 0 and- sidecar.video.len == 0 and sidecar.audio.len == 0- sidecar.close()- if not isSubtitleOnly:- continue-- let (subDir, subName, subExt) = agSplitFile(sibling)- var altered = (subDir / subName) & "_ALTERED" & subExt- if args.output != "":- let (outDir, outName, _) = agSplitFile(output)- altered =- if args.inputs.len == 1: (outDir / outName) & subName[inputName.len .. ^1] & subExt- else: (outDir / subName) & "_ALTERED" & subExt- if altered == sibling:- altered = (subDir / subName) & "_ALTERED" & subExt- makeAlteredSubtitle(sibling, altered, inputLayer, tlV3.effects, tlV3.tb)+ if inputLayer.len != 0:+ var siblings: seq[string]+ for kind, name in walkDir(if inputDir == "": "." else: inputDir, relative = true):+ if kind in {pcFile, pcLinkToFile} and name.startsWith(inputName & "."):+ siblings.add inputDir / name+ siblings.sort()+ for sibling in siblings:+ if sibling != input:+ var sidecar: InputContainer+ try:+ sidecar = av.open(sibling)+ except IOError:+ continue+ let isSubtitleOnly = sidecar.subtitle.len > 0 and+ sidecar.video.len == 0 and sidecar.audio.len == 0+ sidecar.close()+ if isSubtitleOnly:+ let (subDir, subName, subExt) = agSplitFile(sibling)+ var altered = (subDir / subName) & "_ALTERED" & subExt+ if args.output != "":+ let (outDir, outName, _) = agSplitFile(output)+ altered =+ if args.inputs.len == 1: (outDir / outName) & subName[inputName.len .. ^1] & subExt+ else: (outDir / subName) & "_ALTERED" & subExt+ if altered == sibling:+ altered = (subDir / subName) & "_ALTERED" & subExt+ makeAlteredSubtitle(sibling, altered, inputLayer, tlV3.effects, tlV3.tb)bar.destroy()diff --git a/src/edit.nim b/src/edit.nimindex e15ff906..fff32683 100644--- a/src/edit.nim+++ b/src/edit.nim@@ -364,12 +364,12 @@ proc evalEdit(e: EditExpr, container: InputContainer, input: string,# can read, like the `apac` one in iPhone Spatial Audio files.debug &"audio: skipping stream {i}, no decoder for " &$avcodec_get_name(codecId)- continue- let channelIndex = streamChannel(i)- if channelIndex >= -1:- result.orWithThreshold(- audio(bar, container, input, tb, i.int16, channelIndex), m.threshold)- matched = true+ else:+ let channelIndex = streamChannel(i)+ if channelIndex >= -1:+ result.orWithThreshold(+ audio(bar, container, input, tb, i.int16, channelIndex), m.threshold)+ matched = trueif not matched:if undecodable > 0 and undecodable == container.audio.len:error "audio: no audio stream in this file can be decoded."diff --git a/src/editlexer.nim b/src/editlexer.nimindex 740a5fa7..2086e674 100644--- a/src/editlexer.nim+++ b/src/editlexer.nim@@ -76,59 +76,56 @@ proc getNextToken(self: var Lexer): Token {.raises: [ValueError].} =while self.`char` != '\0':while self.`char` != '\0' and isWhiteSpace(self.`char`):self.advance()- if self.`char` == '\0':- continue-- if self.`char` == ';':- while self.`char` != '\0' and self.`char` != '\n':- self.advance()- continue-- if self.`char` in "(){}[]":- let par = self.`char`- self.advance()- return Token(kind: if par in "({[": Lparen else: Rparen,- `from`: self.pos - 1, to: self.pos)+ if self.`char` != '\0':+ if self.`char` == ';':+ while self.`char` != '\0' and self.`char` != '\n':+ self.advance()+ else:+ if self.`char` in "(){}[]":+ let par = self.`char`+ self.advance()+ return Token(kind: if par in "({[": Lparen else: Rparen,+ `from`: self.pos - 1, to: self.pos)- if self.`char` == ':':- self.advance()- return Token(kind: Colon, `from`: self.pos - 1, to: self.pos)+ if self.`char` == ':':+ self.advance()+ return Token(kind: Colon, `from`: self.pos - 1, to: self.pos)- if self.`char` == '=':- self.advance()- return Token(kind: Equal, `from`: self.pos - 1, to: self.pos)+ if self.`char` == '=':+ self.advance()+ return Token(kind: Equal, `from`: self.pos - 1, to: self.pos)- if self.`char` == ',':- self.advance()- return Token(kind: Comma, `from`: self.pos - 1, to: self.pos)+ if self.`char` == ',':+ self.advance()+ return Token(kind: Comma, `from`: self.pos - 1, to: self.pos)- if self.`char` == '"':- self.advance()- let `from` = self.pos- var hasEscapes = false- while self.`char` != '\0' and self.`char` != '"':- if self.`char` == '\\' and self.pos + 1 < uint32(self.text.len):- hasEscapes = true+ if self.`char` == '"':self.advance()- self.advance()- if self.`char` != '"':- raise newException(ValueError, "Unterminated string literal")- let `to` = self.pos- self.advance()- return Token(kind: Str, `from`: `from`, to: `to`, hasEscapes: hasEscapes)+ let `from` = self.pos+ var hasEscapes = false+ while self.`char` != '\0' and self.`char` != '"':+ if self.`char` == '\\' and self.pos + 1 < uint32(self.text.len):+ hasEscapes = true+ self.advance()+ self.advance()+ if self.`char` != '"':+ raise newException(ValueError, "Unterminated string literal")+ let `to` = self.pos+ self.advance()+ return Token(kind: Str, `from`: `from`, to: `to`, hasEscapes: hasEscapes)- if self.`char` in "0123456789." or (self.`char` == '-' and self.pos + 1 <- uint32(self.text.len) and self.text[self.pos + 1] in "0123456789."):- let `from` = self.pos- while self.`char` notin "()[]{}\",:;\0 \t\n\r\x0b\x0c":- self.advance()- return Token(kind: Num, `from`: `from`, to: self.pos)+ if self.`char` in "0123456789." or (self.`char` == '-' and self.pos + 1 <+ uint32(self.text.len) and self.text[self.pos + 1] in "0123456789."):+ let `from` = self.pos+ while self.`char` notin "()[]{}\",:;\0 \t\n\r\x0b\x0c":+ self.advance()+ return Token(kind: Num, `from`: `from`, to: self.pos)- let `from` = self.pos- while self.`char` notin ".()[]{}=\",:;\0 \t\n\r\x0b\x0c":- self.advance()+ let `from` = self.pos+ while self.`char` notin ".()[]{}=\",:;\0 \t\n\r\x0b\x0c":+ self.advance()- return Token(kind: Sym, `from`: `from`, to: self.pos)+ return Token(kind: Sym, `from`: `from`, to: self.pos)return Token(kind: Eof)diff --git a/src/exports/drops.nim b/src/exports/drops.nimindex 6d3c8351..31380956 100644--- a/src/exports/drops.nim+++ b/src/exports/drops.nim@@ -77,43 +77,42 @@ func carried(s: DropScan, layer: seq[Clip], i: int, rule: LayerRule,proc scan(s: var DropScan, tl: v3, layers: seq[seq[Clip]], video: bool,rule: LayerRule, supported: set[ActionKind], ramps: bool) {.raises: [].} =for i, layer in layers:- if layer.len == 0: continue- let isBase = (if video: i == 0 else: i == 0 and not s.videoBase)- # Generator layers (add:text, add:tone) have no file for an editor to- # reference. A video base without files is different: it's the canvas- # an audio-only timeline gets for its overlays, not content.- if not (video and i == 0) and layer.allIt(it.src == nil):- inc s.generated- continue- if not s.carried(layer, i, rule, isBase):- if video: inc s.droppedV else: inc s.droppedA- continue- for clip in layer:- if clip.src == nil: continue- for act in tl.effects[clip.effects]:- if act.kind notin supported and act.kind.appliesTo(video):- let name = ($act).split({':', ','})[0]- if name notin s.actions: s.actions.add name- elif act.kind == actSpeed and act.sKf.len > 0 and not ramps:- const name = "speed ramp (as its mean speed)"- if name notin s.actions: s.actions.add name+ if layer.len != 0:+ let isBase = (if video: i == 0 else: i == 0 and not s.videoBase)+ # Generator layers (add:text, add:tone) have no file for an editor to+ # reference. A video base without files is different: it's the canvas+ # an audio-only timeline gets for its overlays, not content.+ if not (video and i == 0) and layer.allIt(it.src == nil):+ inc s.generated+ elif not s.carried(layer, i, rule, isBase):+ if video: inc s.droppedV else: inc s.droppedA+ else:+ for clip in layer:+ if clip.src != nil:+ for act in tl.effects[clip.effects]:+ if act.kind notin supported and act.kind.appliesTo(video):+ let name = ($act).split({':', ','})[0]+ if name notin s.actions: s.actions.add name+ elif act.kind == actSpeed and act.sKf.len > 0 and not ramps:+ const name = "speed ramp (as its mean speed)"+ if name notin s.actions: s.actions.add namefunc shortensSpans(base: seq[Clip], markers: seq[Marker]): bool {.raises: [].} =## Whether a marker span runs past the clip it's written on. FCPXML keeps## a marker on the base layer's clip it starts during, as fcp11 does, so## the span ends with that clip.for m in markers:- if m.dur <= 0: continue- for i, clip in base:- if clip.src == nil: continue- var hi = high(int64)- for j in i + 1 ..< base.len:- if base[j].src != nil:- hi = base[j].start- break- if m.start >= (if i == 0: 0'i64 else: clip.start) and m.start < hi:- if m.dur > clip.start + clip.dur - m.start: return true- break+ if m.dur > 0:+ for i, clip in base:+ if clip.src != nil:+ var hi = high(int64)+ for j in i + 1 ..< base.len:+ if base[j].src != nil:+ hi = base[j].start+ break+ if m.start >= (if i == 0: 0'i64 else: clip.start) and m.start < hi:+ if m.dur > clip.start + clip.dur - m.start: return true+ breakfunc fcpxmlShortensSpans(tl: v3): bool {.raises: [].} =if tl.hasBaseVideo: tl.v[0].shortensSpans(tl.markers)diff --git a/src/exports/edl.nim b/src/exports/edl.nimindex 2ada3a99..bc7e13a9 100644--- a/src/exports/edl.nim+++ b/src/exports/edl.nim@@ -107,80 +107,80 @@ proc trackEvents(tl: v3, track: TrackExport, reels: Table[ptr string, string],int64(round((clip.offset.float64 + float64(frame - clip.start)) * map.mean))for j, clip in track.clips:- if clip.src == nil: continue- let reel = reels[clip.src]- let speed = initSpeedMap(tl.effects[clip.effects]).mean- let name = extractFilename(clip.src[])- let clipEnd = clip.start + clip.dur- var recIn = clip.start- var recOut = clipEnd- var ev = Event(channels: {track.channel})- var fromLine = Line(dur: -1)- var hasFrom = false+ if clip.src != nil:+ let reel = reels[clip.src]+ let speed = initSpeedMap(tl.effects[clip.effects]).mean+ let name = extractFilename(clip.src[])+ let clipEnd = clip.start + clip.dur+ var recIn = clip.start+ var recOut = clipEnd+ var ev = Event(channels: {track.channel})+ var fromLine = Line(dur: -1)+ var hasFrom = false- if plan[j].outgoing >= 0:- let t = track.transitions[plan[j].outgoing]- # The record out of this clip's own event is where the transition- # begins; the transition's event carries the rest.- recOut = t.spanStart- if plan[j].incoming >= 0:- let t = track.transitions[plan[j].incoming]- recIn = t.spanStart- hasFrom = true- if t.alignment == taStart or j == 0 or track.clips[j - 1].src == nil:- fromLine.reel = "BL"+ if plan[j].outgoing >= 0:+ let t = track.transitions[plan[j].outgoing]+ # The record out of this clip's own event is where the transition+ # begins; the transition's event carries the rest.+ recOut = t.spanStart+ if plan[j].incoming >= 0:+ let t = track.transitions[plan[j].incoming]+ recIn = t.spanStart+ hasFrom = true+ if t.alignment == taStart or j == 0 or track.clips[j - 1].src == nil:+ fromLine.reel = "BL"+ else:+ let prev = track.clips[j - 1]+ fromLine.reel = reels[prev.src]+ let src = prev.sourceAt(recIn)+ fromLine.srcIn = src+ fromLine.srcOut = src+ ev.comments.add "FROM CLIP NAME: " & extractFilename(prev.src[])+ fromLine.trans = "C"+ fromLine.recIn = recIn+ fromLine.recOut = recIn+ ev.lines.add fromLine+ var line = Line(reel: reel, trans: transitionCode(t.kind), dur: t.dur)+ line.srcIn = max(0'i64, clip.sourceAt(recIn))+ line.srcOut = line.srcIn + (recOut - recIn)+ line.recIn = recIn+ line.recOut = recOut+ ev.lines.add line+ ev.comments.add "TO CLIP NAME: " & name+ ev.comments.add "SOURCE FILE: " & paths[clip.src]+ ev.comments.add "EFFECT NAME: " & transitionName(t.kind, track.video)else:- let prev = track.clips[j - 1]- fromLine.reel = reels[prev.src]- let src = prev.sourceAt(recIn)- fromLine.srcIn = src- fromLine.srcOut = src- ev.comments.add "FROM CLIP NAME: " & extractFilename(prev.src[])- fromLine.trans = "C"- fromLine.recIn = recIn- fromLine.recOut = recIn- ev.lines.add fromLine- var line = Line(reel: reel, trans: transitionCode(t.kind), dur: t.dur)- line.srcIn = max(0'i64, clip.sourceAt(recIn))- line.srcOut = line.srcIn + (recOut - recIn)- line.recIn = recIn- line.recOut = recOut- ev.lines.add line- ev.comments.add "TO CLIP NAME: " & name- ev.comments.add "SOURCE FILE: " & paths[clip.src]- ev.comments.add "EFFECT NAME: " & transitionName(t.kind, track.video)- else:- let srcIn = clip.sourceAt(recIn)- ev.lines.add Line(reel: reel, trans: "C", dur: -1, srcIn: srcIn,- srcOut: srcIn + (recOut - recIn), recIn: recIn, recOut: recOut)- ev.comments.add "FROM CLIP NAME: " & name- ev.comments.add "SOURCE FILE: " & paths[clip.src]+ let srcIn = clip.sourceAt(recIn)+ ev.lines.add Line(reel: reel, trans: "C", dur: -1, srcIn: srcIn,+ srcOut: srcIn + (recOut - recIn), recIn: recIn, recOut: recOut)+ ev.comments.add "FROM CLIP NAME: " & name+ ev.comments.add "SOURCE FILE: " & paths[clip.src]- if speed != 1.0:- # `M2 REEL fps source-in`: the source frames played a second.- ev.m2Reel = reel- ev.m2 = &"{speed * base.float64:05.1f}" & " " &- formatTimecode(ev.lines[^1].srcIn, base, drop)- ev.mergeable = not hasFrom and speed == 1.0- ev.key = (clip.src, clip.stream, recIn, recOut, ev.lines[^1].srcIn)- ev.order = (recIn, order)- if recOut > recIn:- result.add ev+ if speed != 1.0:+ # `M2 REEL fps source-in`: the source frames played a second.+ ev.m2Reel = reel+ ev.m2 = &"{speed * base.float64:05.1f}" & " " &+ formatTimecode(ev.lines[^1].srcIn, base, drop)+ ev.mergeable = not hasFrom and speed == 1.0+ ev.key = (clip.src, clip.stream, recIn, recOut, ev.lines[^1].srcIn)+ ev.order = (recIn, order)+ if recOut > recIn:+ result.add ev- if plan[j].outgoing >= 0:- let t = track.transitions[plan[j].outgoing]- if t.alignment == taEnd:- # Fade to black: the clip plays on under the transition.- let src = clip.sourceAt(recOut)- var fade = Event(channels: {track.channel}, order: (recOut, order))- fade.lines.add Line(reel: reel, trans: "C", dur: -1, srcIn: src,- srcOut: src, recIn: recOut, recOut: recOut)- fade.lines.add Line(reel: "BL", trans: transitionCode(t.kind),- dur: t.dur, srcIn: 0, srcOut: t.dur, recIn: recOut,- recOut: recOut + t.dur)- fade.comments.add "FROM CLIP NAME: " & name- fade.comments.add "EFFECT NAME: " & transitionName(t.kind, track.video)- result.add fade+ if plan[j].outgoing >= 0:+ let t = track.transitions[plan[j].outgoing]+ if t.alignment == taEnd:+ # Fade to black: the clip plays on under the transition.+ let src = clip.sourceAt(recOut)+ var fade = Event(channels: {track.channel}, order: (recOut, order))+ fade.lines.add Line(reel: reel, trans: "C", dur: -1, srcIn: src,+ srcOut: src, recIn: recOut, recOut: recOut)+ fade.lines.add Line(reel: "BL", trans: transitionCode(t.kind),+ dur: t.dur, srcIn: 0, srcOut: t.dur, recIn: recOut,+ recOut: recOut + t.dur)+ fade.comments.add "FROM CLIP NAME: " & name+ fade.comments.add "EFFECT NAME: " & transitionName(t.kind, track.video)+ result.add fadeproc edlWrite*(name, output: string, tl: v3) =let base = timecodeBase(tl.tb)diff --git a/src/exports/fcp11.nim b/src/exports/fcp11.nimindex 63ad1ce1..c121ff9d 100644--- a/src/exports/fcp11.nim+++ b/src/exports/fcp11.nim@@ -142,34 +142,34 @@ proc anchorCaptions(asset: XmlNode, tl: v3, orders: seq[CueOrder], clip: Clip,template cue: Caption = track.cues[i]let start = max(cue.start, clip.start)let dur = cue.start + cue.dur - start- if dur <= 0: continue- inc styleId- let caption = newElement("caption")- var name = cue.text- let nl = name.find('\n')- if nl >= 0: name = name[0 ..< nl]- caption.attrs = {- "lane": $(t + 1),- "offset": fraction(clip.offset + startPoint + start - clip.start, tl.tb),- "name": name,- "duration": fraction(dur, tl.tb),- "role": "SRT?captionFormat=SRT." & fcpLang(track.lang),- }.toXmlAttributes- let text = newElement("text")- let styled = newElement("text-style")- styled.attrs = {"ref": "ts" & $styleId}.toXmlAttributes- styled.add newText(cue.text)- text.add styled- caption.add text- let def = newElement("text-style-def")- def.attrs = {"id": "ts" & $styleId}.toXmlAttributes- let style = newElement("text-style")- style.attrs = {"font": "Helvetica", "fontSize": "63", "fontFace": "Regular",- "fontColor": "1 1 1 1", "backgroundColor": "0 0 0 0.75",- "alignment": "center"}.toXmlAttributes- def.add style- caption.add def- asset.add caption+ if dur > 0:+ inc styleId+ let caption = newElement("caption")+ var name = cue.text+ let nl = name.find('\n')+ if nl >= 0: name = name[0 ..< nl]+ caption.attrs = {+ "lane": $(t + 1),+ "offset": fraction(clip.offset + startPoint + start - clip.start, tl.tb),+ "name": name,+ "duration": fraction(dur, tl.tb),+ "role": "SRT?captionFormat=SRT." & fcpLang(track.lang),+ }.toXmlAttributes+ let text = newElement("text")+ let styled = newElement("text-style")+ styled.attrs = {"ref": "ts" & $styleId}.toXmlAttributes+ styled.add newText(cue.text)+ text.add styled+ caption.add text+ let def = newElement("text-style-def")+ def.attrs = {"id": "ts" & $styleId}.toXmlAttributes+ let style = newElement("text-style")+ style.attrs = {"font": "Helvetica", "fontSize": "63", "fontFace": "Regular",+ "fontColor": "1 1 1 1", "backgroundColor": "0 0 0 0.75",+ "alignment": "center"}.toXmlAttributes+ def.add style+ caption.add def+ asset.add captionproc addMarkers(asset: XmlNode, tl: v3, clip: Clip, startPoint: int64,lo, hi: int64) {.raises: [].} =@@ -177,18 +177,18 @@ proc addMarkers(asset: XmlNode, tl: v3, clip: Clip, startPoint: int64,## they start during: FCPXML keeps markers on clips, in the clip's own## time, and has no place for a color.for m in tl.markers:- if m.start < lo or m.start >= hi: continue- let marker = newElement("marker")- var attrs = @{- "start": fraction(clip.offset + startPoint + m.start - clip.start, tl.tb),- # A span ends with its clip: nothing can carry it across the cut.- "duration": fraction(max(1'i64,- min(m.dur, clip.start + clip.dur - m.start)), tl.tb),- "value": m.name,- }- if m.note != "": attrs.add ("note", m.note)- marker.attrs = attrs.toXmlAttributes- asset.add marker+ if m.start >= lo and m.start < hi:+ let marker = newElement("marker")+ var attrs = @{+ "start": fraction(clip.offset + startPoint + m.start - clip.start, tl.tb),+ # A span ends with its clip: nothing can carry it across the cut.+ "duration": fraction(max(1'i64,+ min(m.dur, clip.start + clip.dur - m.start)), tl.tb),+ "value": m.name,+ }+ if m.note != "": attrs.add ("note", m.note)+ marker.attrs = attrs.toXmlAttributes+ asset.add markerproc makeClip(spine: XmlNode, tl: v3, sources: seq[MediaInfo],ptrToIdx: Table[ptr string, int], clip: Clip): (XmlNode, int64) =diff --git a/src/exports/fcp7.nim b/src/exports/fcp7.nimindex faa92bc0..a7f693df 100644--- a/src/exports/fcp7.nim+++ b/src/exports/fcp7.nim@@ -171,18 +171,18 @@ proc clipFilters(effects: Actions, clip: Clip, isVideo: bool, inFrame, outFrame,dur: int64, fps: float): seq[XmlNode] =var seen: set[ActionKind]for a in effects:- if a.kind in seen: continue- seen.incl a.kind- case a.kind- of actSpeed:- result.add speedup(initSpeedMap(effects), clip, inFrame, outFrame)- of actOpacity:- if isVideo:- result.add opacityFilter(a, inFrame, outFrame, dur, fps)- of actVolume:- if not isVideo:- result.add audioLevelsFilter(a, inFrame, outFrame, dur, fps)- else: discard+ if a.kind notin seen:+ seen.incl a.kind+ case a.kind+ of actSpeed:+ result.add speedup(initSpeedMap(effects), clip, inFrame, outFrame)+ of actOpacity:+ if isVideo:+ result.add opacityFilter(a, inFrame, outFrame, dur, fps)+ of actVolume:+ if not isVideo:+ result.add audioLevelsFilter(a, inFrame, outFrame, dur, fps)+ else: discardproc mediaDef(filedef: XmlNode, url: string, mi: MediaInfo, tl: v3, tb: int64,@@ -313,62 +313,61 @@ proc resolveWriteAudio(audio: XmlNode, files: var FileDefs, tl: v3,for sub, ids in audioIds[t]:let track = newElement("track")for j, aclip in alayer.pairs:- if ids[j] == 0:- continue- let mi = ptrToMi[aclip.src]- if transitionLinks[j].incoming >= 0:- let transition = transitions[transitionLinks[j].incoming]- if transition.alignment == taStart:- track.add dissolveItem(transition, "audio", timebase, ntsc)-- var startVal = $aclip.start- var endVal = $(aclip.start + aclip.dur)- var inFrame = aclip.offset- var outFrame = aclip.offset + aclip.dur- if transitionLinks[j].incoming >= 0:- let transition = transitions[transitionLinks[j].incoming]- if transition.alignment == taCenter:- startVal = "-1"- inFrame = max(0'i64, inFrame - transition.dur div 2)- elif transition.alignment == taStart:- startVal = "-1"- if transitionLinks[j].outgoing >= 0:- let transition = transitions[transitionLinks[j].outgoing]- if transition.alignment == taCenter:- endVal = "-1"- outFrame += transition.dur - transition.dur div 2- elif transition.alignment == taEnd:- endVal = "-1"- let inVal = $inFrame- let outVal = $outFrame-- let clipitem = newElement("clipitem")- clipitem.attrs = {"id": &"clipitem-{ids[j]}"}.toXmlAttributes- clipitem.add elem("name", agSplitFile(mi.path).name)- clipitem.add elem("start", startVal)- clipitem.add elem("end", endVal)- clipitem.add elem("enabled", "TRUE")- clipitem.add elem("in", inVal)- clipitem.add elem("out", outVal)- clipitem.addTicks(tl.effects[aclip.effects], aclip, inFrame, outFrame, tl.tb, false)-- files.makeFiledef(clipitem, mi, tl, timebase, ntsc)-- let sourcetrack = newElement("sourcetrack")- sourcetrack.add elem("mediatype", "audio")- sourcetrack.add elem("trackindex", $(sub + 1))- clipitem.add sourcetrack-- clipitem.addResolveLinks(tl, audioIds, j)-- for f in clipFilters(tl.effects[aclip.effects], aclip, false, inFrame,- outFrame, aclip.dur, tl.tb.float64):- clipitem.add f-- track.add clipitem- if transitionLinks[j].outgoing >= 0:- track.add dissolveItem(transitions[transitionLinks[j].outgoing],- "audio", timebase, ntsc)+ if ids[j] != 0:+ let mi = ptrToMi[aclip.src]+ if transitionLinks[j].incoming >= 0:+ let transition = transitions[transitionLinks[j].incoming]+ if transition.alignment == taStart:+ track.add dissolveItem(transition, "audio", timebase, ntsc)++ var startVal = $aclip.start+ var endVal = $(aclip.start + aclip.dur)+ var inFrame = aclip.offset+ var outFrame = aclip.offset + aclip.dur+ if transitionLinks[j].incoming >= 0:+ let transition = transitions[transitionLinks[j].incoming]+ if transition.alignment == taCenter:+ startVal = "-1"+ inFrame = max(0'i64, inFrame - transition.dur div 2)+ elif transition.alignment == taStart:+ startVal = "-1"+ if transitionLinks[j].outgoing >= 0:+ let transition = transitions[transitionLinks[j].outgoing]+ if transition.alignment == taCenter:+ endVal = "-1"+ outFrame += transition.dur - transition.dur div 2+ elif transition.alignment == taEnd:+ endVal = "-1"+ let inVal = $inFrame+ let outVal = $outFrame++ let clipitem = newElement("clipitem")+ clipitem.attrs = {"id": &"clipitem-{ids[j]}"}.toXmlAttributes+ clipitem.add elem("name", agSplitFile(mi.path).name)+ clipitem.add elem("start", startVal)+ clipitem.add elem("end", endVal)+ clipitem.add elem("enabled", "TRUE")+ clipitem.add elem("in", inVal)+ clipitem.add elem("out", outVal)+ clipitem.addTicks(tl.effects[aclip.effects], aclip, inFrame, outFrame, tl.tb, false)++ files.makeFiledef(clipitem, mi, tl, timebase, ntsc)++ let sourcetrack = newElement("sourcetrack")+ sourcetrack.add elem("mediatype", "audio")+ sourcetrack.add elem("trackindex", $(sub + 1))+ clipitem.add sourcetrack++ clipitem.addResolveLinks(tl, audioIds, j)++ for f in clipFilters(tl.effects[aclip.effects], aclip, false, inFrame,+ outFrame, aclip.dur, tl.tb.float64):+ clipitem.add f++ track.add clipitem+ if transitionLinks[j].outgoing >= 0:+ track.add dissolveItem(transitions[transitionLinks[j].outgoing],+ "audio", timebase, ntsc)audio.add tracktype AudioTrackInfo = object@@ -437,67 +436,66 @@ proc premiereWriteAudio(audio: XmlNode, files: var FileDefs, tl: v3,track.add elem("outputchannelindex", $(atrack.explodedIndex + 1))for j, aclip in alayer.pairs:- if aclip.src == nil:- continue- if transitionLinks[j].incoming >= 0:- let t = transitions[transitionLinks[j].incoming]- if t.alignment == taStart:- track.add dissolveItem(t, "audio", timebase, ntsc)- let src = ptrToMi[aclip.src]-- var startVal = $aclip.start- var endVal = $(aclip.start + aclip.dur)- var inFrame = aclip.offset- var outFrame = aclip.offset + aclip.dur- if transitionLinks[j].incoming >= 0:- let t = transitions[transitionLinks[j].incoming]- if t.alignment == taCenter:- startVal = "-1"- inFrame = max(0'i64, inFrame - t.dur div 2)- elif t.alignment == taStart:- startVal = "-1"- if transitionLinks[j].outgoing >= 0:- let t = transitions[transitionLinks[j].outgoing]- if t.alignment == taCenter:- endVal = "-1"- outFrame += t.dur - t.dur div 2- elif t.alignment == taEnd:- endVal = "-1"- let inVal = $inFrame- let outVal = $outFrame-- let clipitem = newElement("clipitem")- clipitem.attrs = {- "id": &"clipitem-{atrack.firstClipId + j}",- "premiereChannelType": (if atrack.isStereo: "stereo" else: "mono")- }.toXmlAttributes- clipitem.add elem("name", agSplitFile(src.path).name)- clipitem.add elem("enabled", "TRUE")- clipitem.add elem("start", startVal)- clipitem.add elem("end", endVal)- clipitem.add elem("in", inVal)- clipitem.add elem("out", outVal)- clipitem.addTicks(tl.effects[aclip.effects], aclip, inFrame, outFrame, tl.tb, false)-- files.makeFiledef(clipitem, src, tl, timebase, ntsc)-- let sourcetrack = newElement("sourcetrack")- sourcetrack.add elem("mediatype", "audio")- sourcetrack.add elem("trackindex", $atrack.sourceTrackIndex)- clipitem.add sourcetrack-- let labels = newElement("labels")- labels.add elem("label2", "Iris")- clipitem.add labels-- for f in clipFilters(tl.effects[aclip.effects], aclip, false, inFrame,- outFrame, aclip.dur, tl.tb.float64):- clipitem.add f-- track.add clipitem- if transitionLinks[j].outgoing >= 0:- track.add dissolveItem(transitions[transitionLinks[j].outgoing],- "audio", timebase, ntsc)+ if aclip.src != nil:+ if transitionLinks[j].incoming >= 0:+ let t = transitions[transitionLinks[j].incoming]+ if t.alignment == taStart:+ track.add dissolveItem(t, "audio", timebase, ntsc)+ let src = ptrToMi[aclip.src]++ var startVal = $aclip.start+ var endVal = $(aclip.start + aclip.dur)+ var inFrame = aclip.offset+ var outFrame = aclip.offset + aclip.dur+ if transitionLinks[j].incoming >= 0:+ let t = transitions[transitionLinks[j].incoming]+ if t.alignment == taCenter:+ startVal = "-1"+ inFrame = max(0'i64, inFrame - t.dur div 2)+ elif t.alignment == taStart:+ startVal = "-1"+ if transitionLinks[j].outgoing >= 0:+ let t = transitions[transitionLinks[j].outgoing]+ if t.alignment == taCenter:+ endVal = "-1"+ outFrame += t.dur - t.dur div 2+ elif t.alignment == taEnd:+ endVal = "-1"+ let inVal = $inFrame+ let outVal = $outFrame++ let clipitem = newElement("clipitem")+ clipitem.attrs = {+ "id": &"clipitem-{atrack.firstClipId + j}",+ "premiereChannelType": (if atrack.isStereo: "stereo" else: "mono")+ }.toXmlAttributes+ clipitem.add elem("name", agSplitFile(src.path).name)+ clipitem.add elem("enabled", "TRUE")+ clipitem.add elem("start", startVal)+ clipitem.add elem("end", endVal)+ clipitem.add elem("in", inVal)+ clipitem.add elem("out", outVal)+ clipitem.addTicks(tl.effects[aclip.effects], aclip, inFrame, outFrame, tl.tb, false)++ files.makeFiledef(clipitem, src, tl, timebase, ntsc)++ let sourcetrack = newElement("sourcetrack")+ sourcetrack.add elem("mediatype", "audio")+ sourcetrack.add elem("trackindex", $atrack.sourceTrackIndex)+ clipitem.add sourcetrack++ let labels = newElement("labels")+ labels.add elem("label2", "Iris")+ clipitem.add labels++ for f in clipFilters(tl.effects[aclip.effects], aclip, false, inFrame,+ outFrame, aclip.dur, tl.tb.float64):+ clipitem.add f++ track.add clipitem+ if transitionLinks[j].outgoing >= 0:+ track.add dissolveItem(transitions[transitionLinks[j].outgoing],+ "audio", timebase, ntsc)audio.add trackproc handlePath(src: string): string =@@ -624,96 +622,93 @@ proc fcp7WriteXml*(name, output: string, resolve: bool, tl: v3) =# Premiere gets the overlay tracks (v[1..]).if resolve and vIdx > 0:break- if vlayer.len == 0:- continue- let track = newElement("track")- let trackStart = videoTrackStart[vIdx]- let transitions = (if vIdx < tl.vt.len: tl.vt[vIdx] else: @[])- let transitionLinks = transitionPlan(vlayer, transitions)-- for j, clip in vlayer.pairs:- # An audio-only timeline that gained `add:` overlays has a synthesized- # base track with no source file (just a render canvas); there is nothing- # to write for Premiere, so skip it (and drop a track left empty).- if clip.src == nil:- continue-- if transitionLinks[j].incoming >= 0:- let t = transitions[transitionLinks[j].incoming]- if t.alignment == taStart:- track.add dissolveItem(t, "video", timebase, ntsc)- let mi = ptrToMi[clip.src]- let still = mi.isStill- var startVal = $clip.start- var endVal = $(clip.start + clip.dur)- # A still is the same frame at every offset, so read `dur` frames from 0;- # real media keeps its true source in/out.- var inFrame = clip.offset- var outFrame = clip.offset + clip.dur- if transitionLinks[j].incoming >= 0:- let t = transitions[transitionLinks[j].incoming]- if t.alignment == taCenter:- startVal = "-1"- inFrame = max(0'i64, inFrame - t.dur div 2)- elif t.alignment == taStart:- startVal = "-1"- if transitionLinks[j].outgoing >= 0:- let t = transitions[transitionLinks[j].outgoing]- if t.alignment == taCenter:- endVal = "-1"- outFrame += t.dur - t.dur div 2- elif t.alignment == taEnd:- endVal = "-1"- let inVal = (if still: "0" else: $inFrame)- let outVal = (if still: $clip.dur else: $outFrame)-- let thisClipid = &"clipitem-{trackStart + j}"- let clipitem = <>clipitem(id = thisClipid)- clipitem.add elem("name", agSplitFile(clip.src[]).name)- clipitem.add elem("enabled", "TRUE")- clipitem.add elem("start", startVal)- clipitem.add elem("end", endVal)- clipitem.add elem("in", inVal)- clipitem.add elem("out", outVal)- if still: clipitem.addTicks(tl.effects[clip.effects], clip, 0, clip.dur, tl.tb, true)- else: clipitem.addTicks(tl.effects[clip.effects], clip, inFrame, outFrame, tl.tb, true)-- files.makeFiledef(clipitem, mi, tl, timebase, ntsc)-- clipitem.add elem("compositemode", "normal")-- for f in clipFilters(tl.effects[clip.effects], clip, true,- (if still: 0'i64 else: inFrame), (if still: clip.dur else: outFrame),- clip.dur, tl.tb.float64):- clipitem.add f-- if resolve:- clipitem.addResolveLinks(tl, resolveAudio, j)- elif vIdx == 0:- # Base track: link the clip to itself and to its aligned audio clips so- # they move together. Overlay tracks (v[1..]) carry no audio, so they- # stay standalone rather than forming a one-member self-link group.- let vlink = newElement("link")- vlink.add elem("linkclipref", thisClipid)- vlink.add elem("mediatype", "video")- vlink.add elem("trackindex", "1")- vlink.add elem("clipindex", $(j + 1))- clipitem.add vlink- for k, atrack in audioPlan:- if j >= tl.a[atrack.layerIdx].len: continue- let link = newElement("link")- link.add elem("linkclipref", &"clipitem-{atrack.firstClipId + j}")- link.add elem("mediatype", "audio")- link.add elem("trackindex", $(k + 1))- link.add elem("clipindex", $(j + 1))- clipitem.add link-- track.add clipitem- if transitionLinks[j].outgoing >= 0:- track.add dissolveItem(transitions[transitionLinks[j].outgoing],- "video", timebase, ntsc)- if track.len > 0:- video.add track+ if vlayer.len != 0:+ let track = newElement("track")+ let trackStart = videoTrackStart[vIdx]+ let transitions = (if vIdx < tl.vt.len: tl.vt[vIdx] else: @[])+ let transitionLinks = transitionPlan(vlayer, transitions)++ for j, clip in vlayer.pairs:+ # An audio-only timeline that gained `add:` overlays has a synthesized+ # base track with no source file (just a render canvas); there is nothing+ # to write for Premiere, so skip it (and drop a track left empty).+ if clip.src != nil:+ if transitionLinks[j].incoming >= 0:+ let t = transitions[transitionLinks[j].incoming]+ if t.alignment == taStart:+ track.add dissolveItem(t, "video", timebase, ntsc)+ let mi = ptrToMi[clip.src]+ let still = mi.isStill+ var startVal = $clip.start+ var endVal = $(clip.start + clip.dur)+ # A still is the same frame at every offset, so read `dur` frames from 0;+ # real media keeps its true source in/out.+ var inFrame = clip.offset+ var outFrame = clip.offset + clip.dur+ if transitionLinks[j].incoming >= 0:+ let t = transitions[transitionLinks[j].incoming]+ if t.alignment == taCenter:+ startVal = "-1"+ inFrame = max(0'i64, inFrame - t.dur div 2)+ elif t.alignment == taStart:+ startVal = "-1"+ if transitionLinks[j].outgoing >= 0:+ let t = transitions[transitionLinks[j].outgoing]+ if t.alignment == taCenter:+ endVal = "-1"+ outFrame += t.dur - t.dur div 2+ elif t.alignment == taEnd:+ endVal = "-1"+ let inVal = (if still: "0" else: $inFrame)+ let outVal = (if still: $clip.dur else: $outFrame)++ let thisClipid = &"clipitem-{trackStart + j}"+ let clipitem = <>clipitem(id = thisClipid)+ clipitem.add elem("name", agSplitFile(clip.src[]).name)+ clipitem.add elem("enabled", "TRUE")+ clipitem.add elem("start", startVal)+ clipitem.add elem("end", endVal)+ clipitem.add elem("in", inVal)+ clipitem.add elem("out", outVal)+ if still: clipitem.addTicks(tl.effects[clip.effects], clip, 0, clip.dur, tl.tb, true)+ else: clipitem.addTicks(tl.effects[clip.effects], clip, inFrame, outFrame, tl.tb, true)++ files.makeFiledef(clipitem, mi, tl, timebase, ntsc)++ clipitem.add elem("compositemode", "normal")++ for f in clipFilters(tl.effects[clip.effects], clip, true,+ (if still: 0'i64 else: inFrame), (if still: clip.dur else: outFrame),+ clip.dur, tl.tb.float64):+ clipitem.add f++ if resolve:+ clipitem.addResolveLinks(tl, resolveAudio, j)+ elif vIdx == 0:+ # Base track: link the clip to itself and to its aligned audio clips so+ # they move together. Overlay tracks (v[1..]) carry no audio, so they+ # stay standalone rather than forming a one-member self-link group.+ let vlink = newElement("link")+ vlink.add elem("linkclipref", thisClipid)+ vlink.add elem("mediatype", "video")+ vlink.add elem("trackindex", "1")+ vlink.add elem("clipindex", $(j + 1))+ clipitem.add vlink+ for k, atrack in audioPlan:+ if j < tl.a[atrack.layerIdx].len:+ let link = newElement("link")+ link.add elem("linkclipref", &"clipitem-{atrack.firstClipId + j}")+ link.add elem("mediatype", "audio")+ link.add elem("trackindex", $(k + 1))+ link.add elem("clipindex", $(j + 1))+ clipitem.add link++ track.add clipitem+ if transitionLinks[j].outgoing >= 0:+ track.add dissolveItem(transitions[transitionLinks[j].outgoing],+ "video", timebase, ntsc)+ if track.len > 0:+ video.add trackmedia.add videodiff --git a/src/exports/otio.nim b/src/exports/otio.nimindex 9c7878ef..2fb7646c 100644--- a/src/exports/otio.nim+++ b/src/exports/otio.nim@@ -548,38 +548,36 @@ proc otioWrite*(name, output: string, tl: v3) =# An audio-only timeline that gained `add:` overlays has a synthesized base# track with no source file; it exists only as a render canvas, so there is# nothing to reference here. Skip it (and any track left empty).- if clip.src == nil:- continue- if transitionLinks[j].incoming >= 0:- let t = transitions[transitionLinks[j].incoming]- if t.alignment == taStart:- clipArr.add gapNode(rate, 0)+ if clip.src != nil:+ if transitionLinks[j].incoming >= 0:+ let t = transitions[transitionLinks[j].incoming]+ if t.alignment == taStart:+ clipArr.add gapNode(rate, 0)+ clipArr.add transitionNode(rate, t, true)+ if clip.start > cursor: clipArr.add gapNode(rate, clip.start - cursor)+ let actions = tl.effects[clip.effects]+ clipArr.add buildClip(clip, actions, ptrToMi[clip.src], urls[clip.src],+ rate, tb = tl.tb, isVideo = true, linkId = linkIdFor(clip), nbCh = nbCh,+ res = tl.res)+ cursor = clip.start + clip.dur+ if transitionLinks[j].outgoing >= 0:+ let t = transitions[transitionLinks[j].outgoing]clipArr.add transitionNode(rate, t, true)- if clip.start > cursor: clipArr.add gapNode(rate, clip.start - cursor)- let actions = tl.effects[clip.effects]- clipArr.add buildClip(clip, actions, ptrToMi[clip.src], urls[clip.src],- rate, tb = tl.tb, isVideo = true, linkId = linkIdFor(clip), nbCh = nbCh,- res = tl.res)- cursor = clip.start + clip.dur- if transitionLinks[j].outgoing >= 0:- let t = transitions[transitionLinks[j].outgoing]- clipArr.add transitionNode(rate, t, true)- if t.alignment == taEnd:- clipArr.add gapNode(rate, 0)- if clipArr.len == 0:- continue- videoTrackNum += 1- children.add %*{- "OTIO_SCHEMA": "Track.1",- "metadata": newJObject(),- "name": "Video " & $videoTrackNum,- "source_range": nil,- "effects": newJArray(),- "markers": newJArray(),- "enabled": true,- "children": clipArr,- "kind": "Video"- }+ if t.alignment == taEnd:+ clipArr.add gapNode(rate, 0)+ if clipArr.len != 0:+ videoTrackNum += 1+ children.add %*{+ "OTIO_SCHEMA": "Track.1",+ "metadata": newJObject(),+ "name": "Video " & $videoTrackNum,+ "source_range": nil,+ "effects": newJArray(),+ "markers": newJArray(),+ "enabled": true,+ "children": clipArr,+ "kind": "Video"+ }for i, track in tl.a:let clipArr = newJArray()@@ -587,24 +585,23 @@ proc otioWrite*(name, output: string, tl: v3) =let transitionLinks = transitionPlan(track, transitions)var cursor = 0'i64for j, clip in track:- if clip.src == nil:- continue- if transitionLinks[j].incoming >= 0:- let t = transitions[transitionLinks[j].incoming]- if t.alignment == taStart:- clipArr.add gapNode(rate, 0)+ if clip.src != nil:+ if transitionLinks[j].incoming >= 0:+ let t = transitions[transitionLinks[j].incoming]+ if t.alignment == taStart:+ clipArr.add gapNode(rate, 0)+ clipArr.add transitionNode(rate, t, false)+ if clip.start > cursor: clipArr.add gapNode(rate, clip.start - cursor)+ let actions = tl.effects[clip.effects]+ clipArr.add buildClip(clip, actions, ptrToMi[clip.src], urls[clip.src],+ rate, tb = tl.tb, isVideo = false, linkId = linkIdFor(clip), nbCh = nbCh,+ res = tl.res)+ cursor = clip.start + clip.dur+ if transitionLinks[j].outgoing >= 0:+ let t = transitions[transitionLinks[j].outgoing]clipArr.add transitionNode(rate, t, false)- if clip.start > cursor: clipArr.add gapNode(rate, clip.start - cursor)- let actions = tl.effects[clip.effects]- clipArr.add buildClip(clip, actions, ptrToMi[clip.src], urls[clip.src],- rate, tb = tl.tb, isVideo = false, linkId = linkIdFor(clip), nbCh = nbCh,- res = tl.res)- cursor = clip.start + clip.dur- if transitionLinks[j].outgoing >= 0:- let t = transitions[transitionLinks[j].outgoing]- clipArr.add transitionNode(rate, t, false)- if t.alignment == taEnd:- clipArr.add gapNode(rate, 0)+ if t.alignment == taEnd:+ clipArr.add gapNode(rate, 0)children.add %*{"OTIO_SCHEMA": "Track.1","metadata": {"PremierePro_OTIO": {"AudioChannels": {diff --git a/src/exports/shotcut.nim b/src/exports/shotcut.nimindex 65d33f9b..ec7829ad 100644--- a/src/exports/shotcut.nim+++ b/src/exports/shotcut.nim@@ -281,59 +281,59 @@ proc shotcutWriteMlt*(output: string, tl: v3) =# because the MLT XML parser cannot resolve forward references.var transitionTags = newSeq[string](layer.len)for i, clip in layer:- if plans[i].outCenter == -1: continue- let t = transitions[plans[i].outCenter]- let next = layer[i + 1]- let h = min(t.dur div 2, next.offset)- let h2 = t.dur - t.dur div 2-- let tag = &"transition{i}"- transitionTags[i] = tag- let tagA = tag & "a"- let tagB = tag & "b"- mlt.addSourceProducer(tl, tagA, clip,- clip.offset + clip.dur + plans[i].postroll, 0, 0)- mlt.addSourceProducer(tl, tagB, next, next.offset + next.dur, 0, 0)-- let tr = newElement("tractor")- tr.attrs = {"id": tag, "in": "00:00:00.000",- "out": tc(h + h2 - 1, tb)}.toXmlAttributes()- tr.addProp("shotcut:transition", "lumaMix")-- var track = newElement("track")- track.attrs = {"producer": tagA,- "in": tc(clip.offset + clip.dur - h, tb),- "out": tc(clip.offset + clip.dur + h2 - 1, tb)}.toXmlAttributes()- tr.add(track)- track = newElement("track")- track.attrs = {"producer": tagB,- "in": tc(next.offset - h, tb),- "out": tc(next.offset + h2 - 1, tb)}.toXmlAttributes()- tr.add(track)-- # Frames inside the sub-tractor carry 0-based positions. A transition- # without explicit in/out computes its progress against the b-producer's- # full source range instead, which breaks the fade ramp.- let trIo = {"in": "00:00:00.000",- "out": tc(h + h2 - 1, tb)}.toXmlAttributes()- if tl.v.len > 0:- let luma = newElement("transition")- luma.attrs = trIo- luma.addProp("a_track", "0")- luma.addProp("b_track", "1")- luma.addProp("factory", "loader")- luma.addProp("mlt_service", "luma")- tr.add(luma)- if tl.a.len > 0:- let mix = newElement("transition")- mix.attrs = trIo- mix.addProp("a_track", "0")- mix.addProp("b_track", "1")- mix.addProp("start", "-1")- mix.addProp("accepts_blanks", "1")- mix.addProp("mlt_service", "mix")- tr.add(mix)- mlt.add(tr)+ if plans[i].outCenter != -1:+ let t = transitions[plans[i].outCenter]+ let next = layer[i + 1]+ let h = min(t.dur div 2, next.offset)+ let h2 = t.dur - t.dur div 2++ let tag = &"transition{i}"+ transitionTags[i] = tag+ let tagA = tag & "a"+ let tagB = tag & "b"+ mlt.addSourceProducer(tl, tagA, clip,+ clip.offset + clip.dur + plans[i].postroll, 0, 0)+ mlt.addSourceProducer(tl, tagB, next, next.offset + next.dur, 0, 0)++ let tr = newElement("tractor")+ tr.attrs = {"id": tag, "in": "00:00:00.000",+ "out": tc(h + h2 - 1, tb)}.toXmlAttributes()+ tr.addProp("shotcut:transition", "lumaMix")++ var track = newElement("track")+ track.attrs = {"producer": tagA,+ "in": tc(clip.offset + clip.dur - h, tb),+ "out": tc(clip.offset + clip.dur + h2 - 1, tb)}.toXmlAttributes()+ tr.add(track)+ track = newElement("track")+ track.attrs = {"producer": tagB,+ "in": tc(next.offset - h, tb),+ "out": tc(next.offset + h2 - 1, tb)}.toXmlAttributes()+ tr.add(track)++ # Frames inside the sub-tractor carry 0-based positions. A transition+ # without explicit in/out computes its progress against the b-producer's+ # full source range instead, which breaks the fade ramp.+ let trIo = {"in": "00:00:00.000",+ "out": tc(h + h2 - 1, tb)}.toXmlAttributes()+ if tl.v.len > 0:+ let luma = newElement("transition")+ luma.attrs = trIo+ luma.addProp("a_track", "0")+ luma.addProp("b_track", "1")+ luma.addProp("factory", "loader")+ luma.addProp("mlt_service", "luma")+ tr.add(luma)+ if tl.a.len > 0:+ let mix = newElement("transition")+ mix.attrs = trIo+ mix.addProp("a_track", "0")+ mix.addProp("b_track", "1")+ mix.addProp("start", "-1")+ mix.addProp("accepts_blanks", "1")+ mix.addProp("mlt_service", "mix")+ tr.add(mix)+ mlt.add(tr)let main_playlist = newElement("playlist")main_playlist.attrs = {"id": "playlist0"}.toXmlAttributes()diff --git a/src/imports/edl.nim b/src/imports/edl.nimindex 670776b6..3216f3c7 100644--- a/src/imports/edl.nim+++ b/src/imports/edl.nim@@ -166,85 +166,81 @@ proc parse(text: string): Parsed =var unknown = 0for raw in text.splitLines:let l = raw.strip()- if l.len == 0: continue- let upper = l.toUpperAscii- if upper.startsWith("TITLE:"): continue- if upper.startsWith("FCM:"):- drop = "DROP" in upper and "NON" notin upper- result.anyDrop = result.anyDrop or drop- continue- var mark: Loc- if parseResolveMarker(l, mark):- if result.events.len > 0 and not skipMetadata:- mark.tc = result.events[^1].lines[0].tcs[2]- mark.drop = result.events[^1].drop- result.locs.add mark- result.events[^1].marks = true- continue- if skipMetadata and (l[0] == '*' or upper.startsWith("M2") or- upper.startsWith("AUD")):- continue- if l[0] == '*':- if result.events.len == 0: continue- let c = l[1 .. ^1].strip()- let cu = c.toUpperAscii- template value(prefix: string): string = c[prefix.len .. ^1].strip()- if cu.startsWith("FROM CLIP NAME:"):- result.events[^1].fromClip = value("FROM CLIP NAME:")- elif cu.startsWith("TO CLIP NAME:"):- result.events[^1].toClip = value("TO CLIP NAME:")- elif cu.startsWith("SOURCE FILE:"):- result.events[^1].files.add value("SOURCE FILE:")- elif cu.startsWith("EFFECT NAME:"):- result.events[^1].effect = value("EFFECT NAME:")- elif cu.startsWith("LOC:"):- var loc: Loc- if parseLoc(value("LOC:"), drop, loc): result.locs.add loc- continue- if upper.startsWith("M2"):- # `M2 REEL fps source-in`; a reel with spaces is joined back.- let toks = l.splitWhitespace()- if toks.len >= 3 and result.events.len > 0:- var fpsAt = -1- var tc: Timecode- for i in countdown(toks.len - 1, 2):- if not parseTimecode(toks[i], tc):- try:- discard parseFloat(toks[i])- fpsAt = i- break- except ValueError: discard- if fpsAt >= 2:- let fps = (try: parseFloat(toks[fpsAt]) except ValueError: 0.0)- result.events[^1].m2.add (toks[1 ..< fpsAt].join(" "), fps)- continue- if upper.startsWith("AUD"):- if result.events.len > 0 and result.events[^1].lines.len > 0:- for tok in l.splitWhitespace()[1 .. ^1]:- var n: int64- if parseInt64(tok, n) and n in 1 .. 99:- result.events[^1].lines[^1].audio.add n.int- continue- if upper.startsWith(">>>") or upper.startsWith("REM"): continue- var line: Line- if parseEventLine(l, line):- for tc in line.tcs:- result.maxFrame = max(result.maxFrame, tc.f)- result.anyDrop = result.anyDrop or tc.drop- if result.events.len > 0 and not skipMetadata and- result.events[^1].lines[^1].num == line.num:- result.events[^1].lines.add line+ if l.len > 0:+ let upper = l.toUpperAscii+ var mark: Loc+ var line: Line+ if upper.startsWith("TITLE:"):+ discard+ elif upper.startsWith("FCM:"):+ drop = "DROP" in upper and "NON" notin upper+ result.anyDrop = result.anyDrop or drop+ elif parseResolveMarker(l, mark):+ if result.events.len > 0 and not skipMetadata:+ mark.tc = result.events[^1].lines[0].tcs[2]+ mark.drop = result.events[^1].drop+ result.locs.add mark+ result.events[^1].marks = true+ elif skipMetadata and (l[0] == '*' or upper.startsWith("M2") or+ upper.startsWith("AUD")):+ discard+ elif l[0] == '*':+ if result.events.len > 0:+ let c = l[1 .. ^1].strip()+ let cu = c.toUpperAscii+ template value(prefix: string): string = c[prefix.len .. ^1].strip()+ if cu.startsWith("FROM CLIP NAME:"):+ result.events[^1].fromClip = value("FROM CLIP NAME:")+ elif cu.startsWith("TO CLIP NAME:"):+ result.events[^1].toClip = value("TO CLIP NAME:")+ elif cu.startsWith("SOURCE FILE:"):+ result.events[^1].files.add value("SOURCE FILE:")+ elif cu.startsWith("EFFECT NAME:"):+ result.events[^1].effect = value("EFFECT NAME:")+ elif cu.startsWith("LOC:"):+ var loc: Loc+ if parseLoc(value("LOC:"), drop, loc): result.locs.add loc+ elif upper.startsWith("M2"):+ # `M2 REEL fps source-in`; a reel with spaces is joined back.+ let toks = l.splitWhitespace()+ if toks.len >= 3 and result.events.len > 0:+ var fpsAt = -1+ var tc: Timecode+ for i in countdown(toks.len - 1, 2):+ if not parseTimecode(toks[i], tc):+ try:+ discard parseFloat(toks[i])+ fpsAt = i+ break+ except ValueError: discard+ if fpsAt >= 2:+ let fps = (try: parseFloat(toks[fpsAt]) except ValueError: 0.0)+ result.events[^1].m2.add (toks[1 ..< fpsAt].join(" "), fps)+ elif upper.startsWith("AUD"):+ if result.events.len > 0 and result.events[^1].lines.len > 0:+ for tok in l.splitWhitespace()[1 .. ^1]:+ var n: int64+ if parseInt64(tok, n) and n in 1 .. 99:+ result.events[^1].lines[^1].audio.add n.int+ elif upper.startsWith(">>>") or upper.startsWith("REM"):+ discard+ elif parseEventLine(l, line):+ for tc in line.tcs:+ result.maxFrame = max(result.maxFrame, tc.f)+ result.anyDrop = result.anyDrop or tc.drop+ if result.events.len > 0 and not skipMetadata and+ result.events[^1].lines[^1].num == line.num:+ result.events[^1].lines.add line+ else:+ result.events.add Event(lines: @[line], drop: drop)+ skipMetadata = false+ elif upper.startsWith("SPLIT:"):+ warning "EDL split (L-cut/J-cut) lines are not supported; the split was ignored"else:- result.events.add Event(lines: @[line], drop: drop)- skipMetadata = false- continue- if upper.startsWith("SPLIT:"):- warning "EDL split (L-cut/J-cut) lines are not supported; the split was ignored"- continue- if l[0] in Digits:- # Comments after a rejected event aren't the previous event's.- skipMetadata = true- inc unknown+ if l[0] in Digits:+ # Comments after a rejected event aren't the previous event's.+ skipMetadata = true+ inc unknownif unknown > 0:warning &"Ignored {unknown} unrecognised EDL line(s)"@@ -283,17 +279,17 @@ proc overwrite(track: var Track, clip: Clip) =let cEnd = c.start + c.durif cEnd <= lo or c.start >= hi:kept.add c- continue- if c.start < lo:- var left = c- left.dur = lo - c.start- kept.add left- if cEnd > hi:- var right = c- right.start = hi- right.offset = c.offset + (hi - c.start)- right.dur = cEnd - hi- kept.add right+ else:+ if c.start < lo:+ var left = c+ left.dur = lo - c.start+ kept.add left+ if cEnd > hi:+ var right = c+ right.start = hi+ right.offset = c.offset + (hi - c.start)+ right.dur = cEnd - hi+ kept.add rightkept.add clipkept.sort(proc (a, b: Clip): int = cmp(a.start, b.start))track.clips.setLen(first)@@ -321,17 +317,17 @@ proc speedOf(im: var Importer, ev: Event, reel: string): float64 =## what v3 can't play.result = 1.0for (r, fps) in ev.m2:- if r != reel: continue- if fps == 0.0:- im.dropped.inc "freeze frame"- return- let speed = abs(fps) / im.base.float64- if speed != speed or speed < 0.0001 or speed > 1000.0:- warning &"EDL motion line for reel {reel} has an unusable speed ({fps}); " &- "the clip keeps normal speed"- return- if fps < 0: im.dropped.inc "reversed clip"- return speed+ if r == reel:+ if fps == 0.0:+ im.dropped.inc "freeze frame"+ return+ let speed = abs(fps) / im.base.float64+ if speed != speed or speed < 0.0001 or speed > 1000.0:+ warning &"EDL motion line for reel {reel} has an unusable speed ({fps}); " &+ "the clip keeps normal speed"+ return+ if fps < 0: im.dropped.inc "reversed clip"+ return speedproc effectsFor(im: var Importer, speed: float64): uint32 =var acts: seq[Action]@@ -439,15 +435,15 @@ proc importEvent(im: var Importer, ev: Event) =for line in ev.lines:if line.trans == trKey:im.dropped.inc "keyed clip"- continue- if line.trans != trCut:- warning &"EDL event {line.num}: transition without an outgoing source line imported as a cut"- if line.reel.toUpperAscii == "BL": continue- let t0 = im.rec(line.tcs[2], drop)- let t1 = im.rec(line.tcs[3], drop)- let speed = im.speedOf(ev, line.reel)- im.lay(line, t0, t1 - t0, im.frames(line.tcs[0], drop), speed,- im.effectsFor(speed))+ else:+ if line.trans != trCut:+ warning &"EDL event {line.num}: transition without an outgoing source line imported as a cut"+ if line.reel.toUpperAscii != "BL":+ let t0 = im.rec(line.tcs[2], drop)+ let t1 = im.rec(line.tcs[3], drop)+ let speed = im.speedOf(ev, line.reel)+ im.lay(line, t0, t1 - t0, im.frames(line.tcs[0], drop), speed,+ im.effectsFor(speed))proc resolvePath(name, edlDir: string): string {.inline.} =if name.isAbsolute: name else: edlDir / name@@ -457,18 +453,18 @@ proc resolveSources(p: var Parsed, edlDir: string, interner: var StringInterner)## relative to the EDL.for ev in p.events.mitems:# A marker list's events name no media.- if ev.marks and ev.fromClip == "" and ev.files.len == 0: continue- for i, line in ev.lines.mpairs:- if line.reel.toUpperAscii == "BL": continue- let incoming = i > 0 and line.trans in {trDissolve, trWipe}- var name = ""- if ev.files.len > 0:- name = (if incoming and ev.files.len > 1: ev.files[1] else: ev.files[0])- elif incoming and ev.toClip != "": name = ev.toClip- elif ev.fromClip != "": name = ev.fromClip- elif incoming and ev.toClip != "": name = ev.toClip- else: name = line.reel- line.src = interner.intern(resolvePath(name, edlDir))+ if not (ev.marks and ev.fromClip == "" and ev.files.len == 0):+ for i, line in ev.lines.mpairs:+ if line.reel.toUpperAscii != "BL":+ let incoming = i > 0 and line.trans in {trDissolve, trWipe}+ var name = ""+ if ev.files.len > 0:+ name = (if incoming and ev.files.len > 1: ev.files[1] else: ev.files[0])+ elif incoming and ev.toClip != "": name = ev.toClip+ elif ev.fromClip != "": name = ev.fromClip+ elif incoming and ev.toClip != "": name = ev.toClip+ else: name = line.reel+ line.src = interner.intern(resolvePath(name, edlDir))proc edlRead*(path: string, interner: var StringInterner,frameRate: AVRational): v3 =diff --git a/src/imports/fcp11.nim b/src/imports/fcp11.nimindex 26b3d224..6fe07357 100644--- a/src/imports/fcp11.nim+++ b/src/imports/fcp11.nim@@ -93,25 +93,25 @@ proc clipEffects(r: var Reader, n: XmlNode, inSecs: float64, dur: int64,offset: var int64): uint32 =var acts: seq[Action]for c in n:- if c.kind != xnElement: continue- case c.tag- of "timeMap":- let speed = r.speedOf(c, inSecs, dur, offset)- if speed.val != 1.0'f32 or speed.sKf.len > 0: acts.add speed- of "adjust-volume":- let amount = c.attr("amount")- if amount.endsWith("dB"):- var db: float64- try:- db = parseFloat(amount[0 ..< ^2])- except ValueError:- error &"Invalid adjust-volume amount: '{amount}'"- if db.isNaN:- error &"Invalid adjust-volume amount: '{amount}'"- let gain = clamp(pow(10.0, db / 20.0), 0.0, 3.98109)- if gain != 1.0:- acts.add Action(kind: actVolume, kf: @[gain.float32])- else: discard+ if c.kind == xnElement:+ case c.tag+ of "timeMap":+ let speed = r.speedOf(c, inSecs, dur, offset)+ if speed.val != 1.0'f32 or speed.sKf.len > 0: acts.add speed+ of "adjust-volume":+ let amount = c.attr("amount")+ if amount.endsWith("dB"):+ var db: float64+ try:+ db = parseFloat(amount[0 ..< ^2])+ except ValueError:+ error &"Invalid adjust-volume amount: '{amount}'"+ if db.isNaN:+ error &"Invalid adjust-volume amount: '{amount}'"+ let gain = clamp(pow(10.0, db / 20.0), 0.0, 3.98109)+ if gain != 1.0:+ acts.add Action(kind: actVolume, kf: @[gain.float32])+ else: discardr.effectIndex.intern(r.effects, newActions(acts))proc place(r: var Reader, n: XmlNode, start: int64): (bool, Placed) =@@ -134,11 +134,13 @@ proc place(r: var Reader, n: XmlNode, start: int64): (bool, Placed) =var media: XmlNode = nilvar hasVideo, hasAudio = falsefor c in n:- if c.kind != xnElement or c.attr("ref") == "": continue- if c.tag == "video": hasVideo = true- elif c.tag == "audio": hasAudio = true- else: continue- if media == nil or c.tag == "video": media = c+ if c.kind == xnElement and c.attr("ref") != "":+ if c.tag == "video":+ hasVideo = true+ media = c+ elif c.tag == "audio":+ hasAudio = true+ if media == nil: media = cif media == nil:r.dropped.inc "empty clip"return@@ -222,43 +224,43 @@ proc readMarkers(r: var Reader, n: XmlNode, start: int64) =## its own time, and one outside the part of it that plays isn't shown.let length = r.frames(n.attrSeconds("duration"))for c in n:- if c.kind != xnElement or c.tag notin ["marker", "chapter-marker"]: continue- let local = r.frames(c.attrSeconds("start") - n.attrSeconds("start"))- if local < 0 or local >= length or start + local < 0: continue- # Final Cut Pro's markers are a frame long: only a longer one is a span.- let dur = r.frames(c.attrSeconds("duration"))- # A marker's kind is told apart by color in Final Cut Pro, so keep that.- let color =- if c.tag == "chapter-marker": mcOrange- elif c.attr("completed") == "0": mcRed- elif c.attr("completed") == "1": mcGreen- else: mcBlue- r.markers.add Marker(start: start + local, dur: (if dur > 1: dur else: 0),- name: c.attr("value"), note: c.attr("note"), color: color)+ if c.kind == xnElement and c.tag in ["marker", "chapter-marker"]:+ let local = r.frames(c.attrSeconds("start") - n.attrSeconds("start"))+ if local >= 0 and local < length and start + local >= 0:+ # Final Cut Pro's markers are a frame long: only a longer one is a span.+ let dur = r.frames(c.attrSeconds("duration"))+ # A marker's kind is told apart by color in Final Cut Pro, so keep that.+ let color =+ if c.tag == "chapter-marker": mcOrange+ elif c.attr("completed") == "0": mcRed+ elif c.attr("completed") == "1": mcGreen+ else: mcBlue+ r.markers.add Marker(start: start + local, dur: (if dur > 1: dur else: 0),+ name: c.attr("value"), note: c.attr("note"), color: color)proc readConnected(r: var Reader, parent: XmlNode, parentStart: int64) =## Clips connected to `parent`, which starts at timeline frame `parentStart`.## Their offsets are in the parent's own time, which begins at its start.let origin = parent.attrSeconds("start")for c in parent:- if c.kind != xnElement or c.attr("lane") == "": continue- var lane: int- try:- lane = parseInt(c.attr("lane"))- except ValueError:- error "Invalid lane: '" & c.attr("lane") & "'"- if c.tag == "spine":- r.dropped.inc "connected storyline"- continue- let start = parentStart + r.frames(c.attrSeconds("offset") - origin)- r.readMarkers(c, start)- if c.attr("enabled") == "0": continue- if c.tag == "caption":- r.readCaption(c, start)- continue- let (ok, placed) = r.place(c, start)- if ok:- r.lanes.mgetOrPut(lane, @[]).add placed+ if c.kind == xnElement and c.attr("lane") != "":+ var lane: int+ try:+ lane = parseInt(c.attr("lane"))+ except ValueError:+ error "Invalid lane: '" & c.attr("lane") & "'"+ if c.tag == "spine":+ r.dropped.inc "connected storyline"+ else:+ let start = parentStart + r.frames(c.attrSeconds("offset") - origin)+ r.readMarkers(c, start)+ if c.attr("enabled") != "0":+ if c.tag == "caption":+ r.readCaption(c, start)+ else:+ let (ok, placed) = r.place(c, start)+ if ok:+ r.lanes.mgetOrPut(lane, @[]).add placedfunc layered(clips: seq[Clip]): seq[seq[Clip]] =## `clips` as few layers as hold them without overlap, in start order.@@ -278,32 +280,32 @@ proc readAssets(r: var Reader, resources: XmlNode,interner: var StringInterner): Table[string, XmlNode] =## Fill `r.assets`; return the formats by id.for n in resources:- if n.kind != xnElement: continue- case n.tag- of "format":- result[n.attr("id")] = n- of "asset":- var src = ""- for c in n:- if c.kind == xnElement and c.tag == "media-rep" and- c.attr("kind") in ["", "original-media"]:- src = uriToPath(c.attr("src"))- break- if src == "" and n.attr("src") != "": # FCPXML 1.8 and earlier- src = uriToPath(n.attr("src"))- if src == "":- error &"asset '{n.attr(\"id\")}' has no media"- r.assets[n.attr("id")] = Asset(src: interner.intern(src),- start: n.attrSeconds("start"), hasVideo: n.attr("hasVideo") == "1",- hasAudio: n.attr("hasAudio") == "1")- else: discard+ if n.kind == xnElement:+ case n.tag+ of "format":+ result[n.attr("id")] = n+ of "asset":+ var src = ""+ for c in n:+ if c.kind == xnElement and c.tag == "media-rep" and+ c.attr("kind") in ["", "original-media"]:+ src = uriToPath(c.attr("src"))+ break+ if src == "" and n.attr("src") != "": # FCPXML 1.8 and earlier+ src = uriToPath(n.attr("src"))+ if src == "":+ error &"asset '{n.attr(\"id\")}' has no media"+ r.assets[n.attr("id")] = Asset(src: interner.intern(src),+ start: n.attrSeconds("start"), hasVideo: n.attr("hasVideo") == "1",+ hasAudio: n.attr("hasAudio") == "1")+ else: discardproc findFirst(n: XmlNode, tag: string): XmlNode =for c in n:- if c.kind != xnElement: continue- if c.tag == tag: return c- let found = c.findFirst(tag)- if found != nil: return found+ if c.kind == xnElement:+ if c.tag == tag: return c+ let found = c.findFirst(tag)+ if found != nil: return foundnilproc parseSampleRate(s: string): cint =@@ -374,58 +376,58 @@ proc fcp11ReadXml*(path: string, interner: var StringInterner): v3 =var video, audio: seq[Clip]var story: seq[StoryItem]for n in spine:- if n.kind != xnElement: continue- let start = r.frames(n.attrSeconds("offset") - tcStart)- if n.tag != "transition": r.readMarkers(n, start)- case n.tag- of "asset-clip", "clip":- var item = StoryItem(kind: skGap)- if n.attr("enabled") != "0":- let (ok, placed) = r.place(n, start)- if ok:- if placed.video: video.add placed.clip- if placed.audio: audio.add placed.clip- item = StoryItem(kind: skClip, start: start,- stop: start + placed.clip.dur)- story.add item- r.readConnected(n, start)- of "gap":- story.add StoryItem(kind: skGap)- r.readConnected(n, start)- of "transition":- let stop = n.attrSeconds("offset") + n.attrSeconds("duration") - tcStart- var kind = tkDissolve- if not kindFromName(n.attr("name"), true, kind):- for f in n:- if f.kind == xnElement and f.tag == "filter-video" and- kindFromName(f.attr("name"), true, kind):- break- story.add StoryItem(kind: skTransition, start: start, stop: r.frames(stop),- transition: kind)- else:- r.dropped.inc uiName(n.tag)- # It still holds its place: a transition beside it isn't beside the- # clip before it.- story.add StoryItem(kind: skGap)+ if n.kind == xnElement:+ let start = r.frames(n.attrSeconds("offset") - tcStart)+ if n.tag != "transition": r.readMarkers(n, start)+ case n.tag+ of "asset-clip", "clip":+ var item = StoryItem(kind: skGap)+ if n.attr("enabled") != "0":+ let (ok, placed) = r.place(n, start)+ if ok:+ if placed.video: video.add placed.clip+ if placed.audio: audio.add placed.clip+ item = StoryItem(kind: skClip, start: start,+ stop: start + placed.clip.dur)+ story.add item+ r.readConnected(n, start)+ of "gap":+ story.add StoryItem(kind: skGap)+ r.readConnected(n, start)+ of "transition":+ let stop = n.attrSeconds("offset") + n.attrSeconds("duration") - tcStart+ var kind = tkDissolve+ if not kindFromName(n.attr("name"), true, kind):+ for f in n:+ if f.kind == xnElement and f.tag == "filter-video" and+ kindFromName(f.attr("name"), true, kind):+ break+ story.add StoryItem(kind: skTransition, start: start, stop: r.frames(stop),+ transition: kind)+ else:+ r.dropped.inc uiName(n.tag)+ # It still holds its place: a transition beside it isn't beside the+ # clip before it.+ story.add StoryItem(kind: skGap)# A transition sits between the story items it joins; where it starts# against their edit point gives its alignment.var transitions: seq[Transition]for k, item in story:- if item.kind != skTransition: continue- let hasPrev = k > 0 and story[k - 1].kind == skClip- let hasNext = k + 1 < story.len and story[k + 1].kind == skClip- let dur = item.stop - item.start- if dur <= 0 or not (hasPrev or hasNext):- r.dropped.inc "transition"- continue- let at = (if hasNext: story[k + 1].start else: story[k - 1].stop)- let alignment =- if not hasPrev or item.start == at: taStart- elif not hasNext or item.stop == at: taEnd- else: taCenter- transitions.add Transition(kind: item.transition, at: at, dur: dur,- alignment: alignment)+ if item.kind == skTransition:+ let hasPrev = k > 0 and story[k - 1].kind == skClip+ let hasNext = k + 1 < story.len and story[k + 1].kind == skClip+ let dur = item.stop - item.start+ if dur <= 0 or not (hasPrev or hasNext):+ r.dropped.inc "transition"+ else:+ let at = (if hasNext: story[k + 1].start else: story[k - 1].stop)+ let alignment =+ if not hasPrev or item.start == at: taStart+ elif not hasNext or item.stop == at: taEnd+ else: taCenter+ transitions.add Transition(kind: item.transition, at: at, dur: dur,+ alignment: alignment)result.tb = r.tbresult.res = (int32(w), int32(h))@@ -444,11 +446,11 @@ proc fcp11ReadXml*(path: string, interner: var StringInterner): v3 =laneKeys.sort()# Above the storyline, each lane is a video layer over the last.for lane in laneKeys:- if lane < 0: continue- var laneVideo: seq[Clip]- for p in r.lanes[lane]:- if p.video: laneVideo.add p.clip- for layer in layered(laneVideo): result.v.add layer+ if lane >= 0:+ var laneVideo: seq[Clip]+ for p in r.lanes[lane]:+ if p.video: laneVideo.add p.clip+ for layer in layered(laneVideo): result.v.add layer# Every lane's audio mixes in; nearest the storyline first.for lane in laneKeys.sortedByIt(abs(it)):var laneAudio: seq[Clip]diff --git a/src/imports/fcp7.nim b/src/imports/fcp7.nimindex d97912de..bf8a9b97 100644--- a/src/imports/fcp7.nim+++ b/src/imports/fcp7.nim@@ -36,11 +36,11 @@ proc readRate(rateNode: XmlNode): AVRational =var timebase = 30var ntsc = falsefor rc in rateNode:- if rc.kind != xnElement: continue- if rc.tag == "timebase":- timebase = xmlInt(rc, 1, high(cint)).int- elif rc.tag == "ntsc":- ntsc = rc.innerText.strip() == "TRUE"+ if rc.kind == xnElement:+ if rc.tag == "timebase":+ timebase = xmlInt(rc, 1, high(cint)).int+ elif rc.tag == "ntsc":+ ntsc = rc.innerText.strip() == "TRUE"readTbNtsc(timebase, ntsc)func num(s: string): (bool, float) =@@ -54,24 +54,24 @@ func num(s: string): (bool, float) =func readParam(parmNode: XmlNode): (string, seq[(float, float)]) =for c in parmNode:- if c.kind != xnElement: continue- case c.tag- of "parameterid":- result[0] = c.innerText.strip()- of "value":- let (ok, v) = num(c.innerText)- if ok: result[1].add (0.0, v)- of "keyframe":- var timeOk, valOk = false- var time, value = 0.0- for kc in c:- if kc.kind != xnElement: continue- case kc.tag- of "when": (timeOk, time) = num(kc.innerText)- of "value": (valOk, value) = num(kc.innerText)- else: discard- if timeOk and valOk: result[1].add (time, value)- else: discard+ if c.kind == xnElement:+ case c.tag+ of "parameterid":+ result[0] = c.innerText.strip()+ of "value":+ let (ok, v) = num(c.innerText)+ if ok: result[1].add (0.0, v)+ of "keyframe":+ var timeOk, valOk = false+ var time, value = 0.0+ for kc in c:+ if kc.kind == xnElement:+ case kc.tag+ of "when": (timeOk, time) = num(kc.innerText)+ of "value": (valOk, value) = num(kc.innerText)+ else: discard+ if timeOk and valOk: result[1].add (time, value)+ else: discardfunc addFixed(acts: var seq[Action], act: Action) =for a in acts:@@ -128,54 +128,53 @@ proc readFilters(filterNode: XmlNode, acts: var seq[Action], remap: var Remap,returnfor effectTag in filterNode:- if effectTag.kind != xnElement or effectTag.tag != "effect": continue-- var effectId = ""- var params: Table[string, seq[(float, float)]]- for effectChild in effectTag:- if effectChild.kind != xnElement: continue- if effectChild.tag == "effectid":- effectId = effectChild.innerText.strip()- elif effectChild.tag == "parameter":- let (id, vals) = readParam(effectChild)- if id != "" and vals.len > 0:- params[id] = vals-- case effectId- of "timeremap":- let speeds = params.getOrDefault("speed")- if speeds.len > 0:- let speed = speeds[0][1] / 100.0- remap.speed = abs(speed)- remap.freeze = speed == 0.0- remap.reverse = speed < 0.0- remap.ramp = speeds.anyIt(it[1] != speeds[0][1])- for v in params.getOrDefault("variablespeed"):- if v[1] != 0.0: remap.ramp = true- for v in params.getOrDefault("reverse"):- if v[1] != 0.0: remap.reverse = true- for p in effectTag:- if p.kind != xnElement or p.tag != "parameter": continue- let (id, _) = readParam(p)- if id != "graphdict": continue- for kf in p:- if kf.kind != xnElement or kf.tag != "keyframe": continue- var timeOk, valOk = false- var time, value = 0.0- for kc in kf:- if kc.kind != xnElement: continue- if kc.tag == "when": (timeOk, time) = num(kc.innerText)- elif kc.tag == "value": (valOk, value) = num(kc.innerText)- if timeOk and valOk: remap.graph.add (time, value)- of "opacity":- let kf = kfSeq(params.getOrDefault("opacity"), srcIn, srcOut, 0.01, 0.0, 1.0)- if kf.len > 0:- acts.addFixed Action(kind: actOpacity, kf: kf)- of "audiolevels":- let kf = kfSeq(params.getOrDefault("level"), srcIn, srcOut, 1.0, 0.0, 3.98109)- if kf.len > 0:- acts.addFixed Action(kind: actVolume, kf: kf)- else: discard+ if effectTag.kind == xnElement and effectTag.tag == "effect":+ var effectId = ""+ var params: Table[string, seq[(float, float)]]+ for effectChild in effectTag:+ if effectChild.kind == xnElement:+ if effectChild.tag == "effectid":+ effectId = effectChild.innerText.strip()+ elif effectChild.tag == "parameter":+ let (id, vals) = readParam(effectChild)+ if id != "" and vals.len > 0:+ params[id] = vals++ case effectId+ of "timeremap":+ let speeds = params.getOrDefault("speed")+ if speeds.len > 0:+ let speed = speeds[0][1] / 100.0+ remap.speed = abs(speed)+ remap.freeze = speed == 0.0+ remap.reverse = speed < 0.0+ remap.ramp = speeds.anyIt(it[1] != speeds[0][1])+ for v in params.getOrDefault("variablespeed"):+ if v[1] != 0.0: remap.ramp = true+ for v in params.getOrDefault("reverse"):+ if v[1] != 0.0: remap.reverse = true+ for p in effectTag:+ if p.kind != xnElement or p.tag != "parameter": continue+ let (id, _) = readParam(p)+ if id != "graphdict": continue+ for kf in p:+ if kf.kind != xnElement or kf.tag != "keyframe": continue+ var timeOk, valOk = false+ var time, value = 0.0+ for kc in kf:+ if kc.kind != xnElement: continue+ if kc.tag == "when": (timeOk, time) = num(kc.innerText)+ elif kc.tag == "value": (valOk, value) = num(kc.innerText)+ if timeOk and valOk: remap.graph.add (time, value)+ of "opacity":+ let kf = kfSeq(params.getOrDefault("opacity"), srcIn, srcOut, 0.01, 0.0, 1.0)+ if kf.len > 0:+ acts.addFixed Action(kind: actOpacity, kf: kf)+ of "audiolevels":+ let kf = kfSeq(params.getOrDefault("level"), srcIn, srcOut, 1.0, 0.0, 3.98109)+ if kf.len > 0:+ acts.addFixed Action(kind: actVolume, kf: kf)+ else: discardtype FileInfo = objectsrc: ptr string@@ -188,17 +187,17 @@ proc resolveFile(fileNode: XmlNode, files: var Table[string, FileInfo],if fileId != "" and fileId in files:return files[fileId]for fc in fileNode:- if fc.kind != xnElement: continue- if fc.tag == "pathurl":- result.src = interner.intern(uriToPath(fc.innerText.strip()))- elif fc.tag == "media":- for m in fc:- if m.kind != xnElement or m.tag != "audio": continue- var channels = 2- for a in m:- if a.kind == xnElement and a.tag == "channelcount":- channels = int(xmlInt(a, 1, 64))- result.channels.add channels+ if fc.kind == xnElement:+ if fc.tag == "pathurl":+ result.src = interner.intern(uriToPath(fc.innerText.strip()))+ elif fc.tag == "media":+ for m in fc:+ if m.kind == xnElement and m.tag == "audio":+ var channels = 2+ for a in m:+ if a.kind == xnElement and a.tag == "channelcount":+ channels = int(xmlInt(a, 1, 64))+ result.channels.add channelsif result.src != nil and fileId != "":files[fileId] = result@@ -217,37 +216,37 @@ proc readTransition(node: XmlNode, audio: bool): Transition =var alignment = taCentervar kind = tkDissolvefor c in node:- if c.kind != xnElement: continue- case c.tag- of "start": startVal = xmlInt(c, 0, maxFrames)- of "end": endVal = xmlInt(c, 0, maxFrames)- of "effect":- # An unknown transition plays as a dissolve.- for f in c:- if f.kind == xnElement and f.tag in ["effectid", "name"] and- kindFromName(f.innerText.strip(), not audio, kind):- break- if kind == tkDipToBlackLegacy:- # A light dip color dips to white.- var total, count = 0+ if c.kind == xnElement:+ case c.tag+ of "start": startVal = xmlInt(c, 0, maxFrames)+ of "end": endVal = xmlInt(c, 0, maxFrames)+ of "effect":+ # An unknown transition plays as a dissolve.for f in c:- if f.kind != xnElement or f.tag != "parameter": continue- for v in f:- if v.kind != xnElement or v.tag != "value": continue- for ch in v:- if ch.kind == xnElement and ch.tag in ["red", "green", "blue"]:- let (ok, n) = num(ch.innerText)- if ok:- total += int(n)- inc count- if count > 0 and total div count > 127: kind = tkDipToWhiteLegacy- of "alignment":- alignment = case c.innerText.strip()- of "start", "start-black": taStart- of "center": taCenter- of "end", "end-black": taEnd- else: error &"Unsupported transition alignment: '{c.innerText.strip()}'"- else: discard+ if f.kind == xnElement and f.tag in ["effectid", "name"] and+ kindFromName(f.innerText.strip(), not audio, kind):+ break+ if kind == tkDipToBlackLegacy:+ # A light dip color dips to white.+ var total, count = 0+ for f in c:+ if f.kind != xnElement or f.tag != "parameter": continue+ for v in f:+ if v.kind != xnElement or v.tag != "value": continue+ for ch in v:+ if ch.kind == xnElement and ch.tag in ["red", "green", "blue"]:+ let (ok, n) = num(ch.innerText)+ if ok:+ total += int(n)+ inc count+ if count > 0 and total div count > 127: kind = tkDipToWhiteLegacy+ of "alignment":+ alignment = case c.innerText.strip()+ of "start", "start-black": taStart+ of "center": taCenter+ of "end", "end-black": taEnd+ else: error &"Unsupported transition alignment: '{c.innerText.strip()}'"+ else: discardif startVal < 0 or endVal <= startVal:error "Invalid transitionitem: <start> must come before <end>"let dur = endVal - startVal@@ -263,26 +262,26 @@ proc generatorColor(effect: XmlNode): (bool, RGBColor) =var name, id: stringvar color = RGBColor(red: 0, green: 0, blue: 0)for c in effect:- if c.kind != xnElement: continue- case c.tag- of "name": name = c.innerText.strip().toLowerAscii()- of "effectid": id = c.innerText.strip().toLowerAscii()- of "parameter":- var isFill = false- var value: XmlNode = nil- for pc in c:- if pc.kind != xnElement: continue- if pc.tag == "parameterid": isFill = pc.innerText.strip() == "fillcolor"- elif pc.tag == "value": value = pc- if isFill and value != nil:- for ch in value:- if ch.kind != xnElement or ch.tag notin ["red", "green", "blue"]: continue- let v = uint8(xmlInt(ch, 0, 255))- case ch.tag- of "red": color.red = v- of "green": color.green = v- else: color.blue = v- else: discard+ if c.kind == xnElement:+ case c.tag+ of "name": name = c.innerText.strip().toLowerAscii()+ of "effectid": id = c.innerText.strip().toLowerAscii()+ of "parameter":+ var isFill = false+ var value: XmlNode = nil+ for pc in c:+ if pc.kind != xnElement: continue+ if pc.tag == "parameterid": isFill = pc.innerText.strip() == "fillcolor"+ elif pc.tag == "value": value = pc+ if isFill and value != nil:+ for ch in value:+ if ch.kind != xnElement or ch.tag notin ["red", "green", "blue"]: continue+ let v = uint8(xmlInt(ch, 0, 255))+ case ch.tag+ of "red": color.red = v+ of "green": color.green = v+ else: color.blue = v+ else: discardif id == "slug" or name in ["slug", "black video"]: return (true, color)if id == "color" or name in ["color", "color matte", "colour matte"]:return (true, color)@@ -309,14 +308,14 @@ proc readMarker(node: XmlNode): (bool, Marker) =var stop = -1'i64marker.start = -1for c in node:- if c.kind != xnElement: continue- case c.tag- of "name": marker.name = c.innerText.strip()- of "comment": marker.note = c.innerText.strip()- of "in": marker.start = xmlInt(c, -1, maxFrames)- of "out": stop = xmlInt(c, -1, maxFrames)- of "pproColor": marker.color = fromPproColor(xmlInt(c, 0, high(uint32).int64))- else: discard+ if c.kind == xnElement:+ case c.tag+ of "name": marker.name = c.innerText.strip()+ of "comment": marker.note = c.innerText.strip()+ of "in": marker.start = xmlInt(c, -1, maxFrames)+ of "out": stop = xmlInt(c, -1, maxFrames)+ of "pproColor": marker.color = fromPproColor(xmlInt(c, 0, high(uint32).int64))+ else: discardmarker.dur = max(0'i64, stop - marker.start)(marker.start >= 0, marker)@@ -342,159 +341,159 @@ proc parseTrack(trackNode: XmlNode, files: var Table[string, FileInfo],result.transitions.add parsed[k]for k, trackChild in items:- if trackChild.tag == "transitionitem": continue- let generator = trackChild.tag == "generatoritem"-- var startVal = 0i64- var endVal = 0i64- var inVal = 0i64- var outVal = -1i64- var ticksIn, ticksOut = -1'i64- var fileNode, effectNode: XmlNode = nil- var nested = false- var enabled = true- var trackIndex = 1'i64- var clipTb = tb- var acts: seq[Action]- var filterNodes, markerNodes: seq[XmlNode]-- for ci in trackChild:- if ci.kind != xnElement: continue- case ci.tag- # -1 marks a start or end inside a transition.- of "start": startVal = xmlInt(ci, -1, maxFrames)- of "end": endVal = xmlInt(ci, -1, maxFrames)- of "in": inVal = xmlInt(ci, 0, maxFrames)- of "out": outVal = xmlInt(ci, -1, maxFrames)- of "pproTicksIn": ticksIn = xmlInt(ci, lo = 0)- of "pproTicksOut": ticksOut = xmlInt(ci, lo = 0)- of "file": fileNode = ci- of "effect": effectNode = ci- of "sequence": nested = true- of "enabled": enabled = ci.innerText.strip() != "FALSE"- of "filter": filterNodes.add ci- of "marker": markerNodes.add ci- of "rate": clipTb = readRate(ci)- of "sourcetrack":- for st in ci:- if st.kind == xnElement and st.tag == "trackindex":- trackIndex = xmlInt(st, 1, high(int32))- else: discard-- if not enabled: continue- # <in>, <out> and the filters' keyframes count frames at the clip's own- # rate, which can differ from the sequence's (Premiere's ticks show it).- let scale = tb.float64 / clipTb.float64- proc toSeqFrames(v: int64): int64 =- let f = round(v.float64 * scale)- if not (f <= maxFrames.float64):- error "Invalid clipitem: <in> or <out> is too far into its media"- int64(f)- if scale != 1.0:- inVal = toSeqFrames(inVal)- if outVal >= 0: outVal = toSeqFrames(outVal)- var fill: RGBColor- var file: FileInfo- if generator:- var known = false- if effectNode != nil: (known, fill) = generatorColor(effectNode)- if not known or audio:- dropped.inc "generated clip"- continue- elif fileNode == nil:- if nested: dropped.inc "nested sequence"- continue- else:- file = resolveFile(fileNode, files, interner)- if file.src == nil: continue-- # An edge inside a transition is the transition's edit point. A centered- # transition also extends the clip's media by its half on that side.- var inExt, outExt = 0'i64- if startVal == -1:- if k == 0 or items[k - 1].tag != "transitionitem":- error "clipitem <start> of -1 has no transition before it"- let t = parsed[k - 1]- startVal = t.at- if t.alignment == taCenter: inExt = t.dur div 2- if endVal == -1:- if k + 1 >= items.len or items[k + 1].tag != "transitionitem":- error "clipitem <end> of -1 has no transition after it"- let t = parsed[k + 1]- endVal = t.at- if t.alignment == taCenter: outExt = t.dur - t.dur div 2- if endVal <= startVal:- error "Invalid clipitem: <start> must come before <end>"- let dur = endVal - startVal- if generator:- # A source-less clip paints its effects on the canvas.- let box = Action(kind: actDrawbox, dbX: 0, dbY: 0, dbW: res[0], dbH: res[1],- dbColor: fill)- result.clips.add Clip(src: nil, start: startVal, dur: dur,- effects: effectIndex.intern(effects, newActions(@[box])))- continue- if outVal <= inVal: outVal = inVal + dur + inExt + outExt- var remap = Remap()- for fn in filterNodes:- readFilters(fn, acts, remap, inVal.float / scale, outVal.float / scale)- for point in remap.graph.mitems:- point = (point[0] * scale, point[1] * scale)- let ticksPerFrame = pproTicksPerSecond.float / tb.float- var speed = remap.speed- if remap.freeze:- dropped.inc "freeze frame"- speed = 1.0- if remap.reverse: dropped.inc "reversed clip"- var rampOffset = -1'i64- if remap.ramp and not remap.reverse and remap.graph.len >= 2:- # The time remap graph gives the source frame at each frame of the- # clip, which a ramp follows.- let (s, mediaIn, ok) = speedFromMap(remap.graph, float(inVal + inExt),- dur.float)- if ok and s.sKf.len > 0:- acts.addFixed s- rampOffset = int64(round(mediaIn / s.val))- elif ok:- speed = s.val- remap.ramp = not ok- if remap.ramp:- # Played at its average speed, which keeps the clip's length and the- # media it covers. Premiere's ticks give the media exactly; without- # them only the first keyframe's speed is known.- dropped.inc "speed ramp"- if ticksOut > ticksIn and ticksIn >= 0:- speed = (ticksOut - ticksIn).float / ticksPerFrame /- float(dur + inExt + outExt)- if rampOffset < 0 and speed > 0.0 and speed < 99999.0 and speed != 1.0:- acts.addFixed Action(kind: actSpeed, val: speed.float32)- # <in> is clamped at 0 when the handle runs past the media start, so take- # the offset from <out> instead. Premiere's ticks give the source time- # exactly, where <in> is rounded to a frame after the speed change.- let offset =- if rampOffset >= 0: rampOffset- elif inExt > 0: max(0'i64, outVal - outExt - dur)- elif ticksIn >= 0: int64(round(ticksIn.float / ticksPerFrame / speed))- else: inVal- # A clip carries all of its media's markers, in the media's frames:- # those in the part it plays show on the timeline. A ramp or a reversed- # clip moves through its media unevenly, so theirs are left out.- if rampOffset < 0 and not remap.ramp and not remap.reverse and speed > 0.0:- for mn in markerNodes:- let (ok, m) = readMarker(mn)- if not ok: continue- let at = startVal + int64(round(m.start.float64 * scale / speed)) - offset- if at < startVal or at >= endVal: continue- let span = int64(round(m.dur.float64 * scale / speed))- result.markers.add Marker(start: at, dur: min(span, endVal - at),- name: m.name, note: m.note, color: m.color)- let e = effectIndex.intern(effects, newActions(acts))- var stream = 0'i16- if audio:- let (s, firstChannel) = file.streamOf(trackIndex)- stream = s- if firstChannel: result.laterChannels = false- result.clips.add Clip(src: file.src, start: startVal, dur: dur,- offset: offset, effects: e, stream: stream)+ if trackChild.tag != "transitionitem":+ let generator = trackChild.tag == "generatoritem"++ var startVal = 0i64+ var endVal = 0i64+ var inVal = 0i64+ var outVal = -1i64+ var ticksIn, ticksOut = -1'i64+ var fileNode, effectNode: XmlNode = nil+ var nested = false+ var enabled = true+ var trackIndex = 1'i64+ var clipTb = tb+ var acts: seq[Action]+ var filterNodes, markerNodes: seq[XmlNode]++ for ci in trackChild:+ if ci.kind == xnElement:+ case ci.tag+ # -1 marks a start or end inside a transition.+ of "start": startVal = xmlInt(ci, -1, maxFrames)+ of "end": endVal = xmlInt(ci, -1, maxFrames)+ of "in": inVal = xmlInt(ci, 0, maxFrames)+ of "out": outVal = xmlInt(ci, -1, maxFrames)+ of "pproTicksIn": ticksIn = xmlInt(ci, lo = 0)+ of "pproTicksOut": ticksOut = xmlInt(ci, lo = 0)+ of "file": fileNode = ci+ of "effect": effectNode = ci+ of "sequence": nested = true+ of "enabled": enabled = ci.innerText.strip() != "FALSE"+ of "filter": filterNodes.add ci+ of "marker": markerNodes.add ci+ of "rate": clipTb = readRate(ci)+ of "sourcetrack":+ for st in ci:+ if st.kind == xnElement and st.tag == "trackindex":+ trackIndex = xmlInt(st, 1, high(int32))+ else: discard++ if enabled:+ # <in>, <out> and the filters' keyframes count frames at the clip's own+ # rate, which can differ from the sequence's (Premiere's ticks show it).+ let scale = tb.float64 / clipTb.float64+ proc toSeqFrames(v: int64): int64 =+ let f = round(v.float64 * scale)+ if not (f <= maxFrames.float64):+ error "Invalid clipitem: <in> or <out> is too far into its media"+ int64(f)+ if scale != 1.0:+ inVal = toSeqFrames(inVal)+ if outVal >= 0: outVal = toSeqFrames(outVal)+ var fill: RGBColor+ var file: FileInfo+ if generator:+ var known = false+ if effectNode != nil: (known, fill) = generatorColor(effectNode)+ if not known or audio:+ dropped.inc "generated clip"+ continue+ elif fileNode == nil:+ if nested: dropped.inc "nested sequence"+ continue+ else:+ file = resolveFile(fileNode, files, interner)+ if file.src == nil: continue++ # An edge inside a transition is the transition's edit point. A centered+ # transition also extends the clip's media by its half on that side.+ var inExt, outExt = 0'i64+ if startVal == -1:+ if k == 0 or items[k - 1].tag != "transitionitem":+ error "clipitem <start> of -1 has no transition before it"+ let t = parsed[k - 1]+ startVal = t.at+ if t.alignment == taCenter: inExt = t.dur div 2+ if endVal == -1:+ if k + 1 >= items.len or items[k + 1].tag != "transitionitem":+ error "clipitem <end> of -1 has no transition after it"+ let t = parsed[k + 1]+ endVal = t.at+ if t.alignment == taCenter: outExt = t.dur - t.dur div 2+ if endVal <= startVal:+ error "Invalid clipitem: <start> must come before <end>"+ let dur = endVal - startVal+ if generator:+ # A source-less clip paints its effects on the canvas.+ let box = Action(kind: actDrawbox, dbX: 0, dbY: 0, dbW: res[0], dbH: res[1],+ dbColor: fill)+ result.clips.add Clip(src: nil, start: startVal, dur: dur,+ effects: effectIndex.intern(effects, newActions(@[box])))+ else:+ if outVal <= inVal: outVal = inVal + dur + inExt + outExt+ var remap = Remap()+ for fn in filterNodes:+ readFilters(fn, acts, remap, inVal.float / scale, outVal.float / scale)+ for point in remap.graph.mitems:+ point = (point[0] * scale, point[1] * scale)+ let ticksPerFrame = pproTicksPerSecond.float / tb.float+ var speed = remap.speed+ if remap.freeze:+ dropped.inc "freeze frame"+ speed = 1.0+ if remap.reverse: dropped.inc "reversed clip"+ var rampOffset = -1'i64+ if remap.ramp and not remap.reverse and remap.graph.len >= 2:+ # The time remap graph gives the source frame at each frame of the+ # clip, which a ramp follows.+ let (s, mediaIn, ok) = speedFromMap(remap.graph, float(inVal + inExt),+ dur.float)+ if ok and s.sKf.len > 0:+ acts.addFixed s+ rampOffset = int64(round(mediaIn / s.val))+ elif ok:+ speed = s.val+ remap.ramp = not ok+ if remap.ramp:+ # Played at its average speed, which keeps the clip's length and the+ # media it covers. Premiere's ticks give the media exactly; without+ # them only the first keyframe's speed is known.+ dropped.inc "speed ramp"+ if ticksOut > ticksIn and ticksIn >= 0:+ speed = (ticksOut - ticksIn).float / ticksPerFrame /+ float(dur + inExt + outExt)+ if rampOffset < 0 and speed > 0.0 and speed < 99999.0 and speed != 1.0:+ acts.addFixed Action(kind: actSpeed, val: speed.float32)+ # <in> is clamped at 0 when the handle runs past the media start, so take+ # the offset from <out> instead. Premiere's ticks give the source time+ # exactly, where <in> is rounded to a frame after the speed change.+ let offset =+ if rampOffset >= 0: rampOffset+ elif inExt > 0: max(0'i64, outVal - outExt - dur)+ elif ticksIn >= 0: int64(round(ticksIn.float / ticksPerFrame / speed))+ else: inVal+ # A clip carries all of its media's markers, in the media's frames:+ # those in the part it plays show on the timeline. A ramp or a reversed+ # clip moves through its media unevenly, so theirs are left out.+ if rampOffset < 0 and not remap.ramp and not remap.reverse and speed > 0.0:+ for mn in markerNodes:+ let (ok, m) = readMarker(mn)+ if ok:+ let at = startVal + int64(round(m.start.float64 * scale / speed)) - offset+ if at >= startVal and at < endVal:+ let span = int64(round(m.dur.float64 * scale / speed))+ result.markers.add Marker(start: at, dur: min(span, endVal - at),+ name: m.name, note: m.note, color: m.color)+ let e = effectIndex.intern(effects, newActions(acts))+ var stream = 0'i16+ if audio:+ let (s, firstChannel) = file.streamOf(trackIndex)+ stream = s+ if firstChannel: result.laterChannels = false+ result.clips.add Clip(src: file.src, start: startVal, dur: dur,+ offset: offset, effects: e, stream: stream)proc fcp7ReadXml*(path: string, interner: var StringInterner): v3 =let root = parseXmlFile(path, fcp7Tags)@@ -516,16 +515,16 @@ proc fcp7ReadXml*(path: string, interner: var StringInterner): v3 =var markers: seq[Marker]for child in seqNode:- if child.kind != xnElement: continue- case child.tag- of "rate":- tb = readRate(child)- of "media":- mediaNode = child- of "marker":- let (ok, marker) = readMarker(child)- if ok: markers.add marker- else: discard+ if child.kind == xnElement:+ case child.tag+ of "rate":+ tb = readRate(child)+ of "media":+ mediaNode = child+ of "marker":+ let (ok, marker) = readMarker(child)+ if ok: markers.add marker+ else: discardif mediaNode == nil:error "No <media> found in XML"@@ -541,57 +540,57 @@ proc fcp7ReadXml*(path: string, interner: var StringInterner): v3 =var vtrans, atrans: seq[seq[Transition]]for mediaChild in mediaNode:- if mediaChild.kind != xnElement: continue- case mediaChild.tag- of "video":- for vidChild in mediaChild:- if vidChild.kind != xnElement: continue- case vidChild.tag- of "format":- for fc in vidChild:- if fc.kind != xnElement: continue- if fc.tag == "samplecharacteristics":- var w = 1920'i32- var h = 1080'i32- for sc in fc:- if sc.kind != xnElement: continue- if sc.tag == "width": w = xmlInt(sc, 1, high(int32)).int32- elif sc.tag == "height": h = xmlInt(sc, 1, high(int32)).int32- res = (w, h)- of "track":- let (clips, transitions, _, clipMarkers) = parseTrack(vidChild, files,- effects, effectIndex, interner, audio = false, res, tb, dropped)- markers.add clipMarkers- if clips.len > 0:- vobjs.add clips- vtrans.add transitions- else: discard- of "audio":- for audChild in mediaChild:- if audChild.kind != xnElement: continue- case audChild.tag- of "format":- for fc in audChild:- if fc.kind != xnElement: continue- if fc.tag == "samplecharacteristics":- for sc in fc:- if sc.kind != xnElement: continue- if sc.tag == "samplerate":- sr = xmlInt(sc, minSampleRate, maxSampleRate).cint- of "track":- let idx = audChild.attr("currentExplodedTrackIndex")- if idx != "" and idx != "0": continue- let (clips, transitions, laterChannels, clipMarkers) = parseTrack(- audChild, files, effects, effectIndex, interner, audio = true, res, tb,- dropped)- markers.add clipMarkers- # Clips play whole streams, which the stream's first-channel track- # already holds.- if clips.len > 0 and not laterChannels:- aobjs.add clips- atrans.add transitions- else: discard- else: discard+ if mediaChild.kind == xnElement:+ case mediaChild.tag+ of "video":+ for vidChild in mediaChild:+ if vidChild.kind != xnElement: continue+ case vidChild.tag+ of "format":+ for fc in vidChild:+ if fc.kind != xnElement: continue+ if fc.tag == "samplecharacteristics":+ var w = 1920'i32+ var h = 1080'i32+ for sc in fc:+ if sc.kind != xnElement: continue+ if sc.tag == "width": w = xmlInt(sc, 1, high(int32)).int32+ elif sc.tag == "height": h = xmlInt(sc, 1, high(int32)).int32+ res = (w, h)+ of "track":+ let (clips, transitions, _, clipMarkers) = parseTrack(vidChild, files,+ effects, effectIndex, interner, audio = false, res, tb, dropped)+ markers.add clipMarkers+ if clips.len > 0:+ vobjs.add clips+ vtrans.add transitions+ else: discard+ of "audio":+ for audChild in mediaChild:+ if audChild.kind != xnElement: continue+ case audChild.tag+ of "format":+ for fc in audChild:+ if fc.kind != xnElement: continue+ if fc.tag == "samplecharacteristics":+ for sc in fc:+ if sc.kind != xnElement: continue+ if sc.tag == "samplerate":+ sr = xmlInt(sc, minSampleRate, maxSampleRate).cint+ of "track":+ let idx = audChild.attr("currentExplodedTrackIndex")+ if idx == "" or idx == "0":+ let (clips, transitions, laterChannels, clipMarkers) = parseTrack(+ audChild, files, effects, effectIndex, interner, audio = true, res, tb,+ dropped)+ markers.add clipMarkers+ # Clips play whole streams, which the stream's first-channel track+ # already holds.+ if clips.len > 0 and not laterChannels:+ aobjs.add clips+ atrans.add transitions+ else: discard+ else: discardlet bg = RGBColor(red: 0, green: 0, blue: 0)result = v3(tb: tb, bg: bg, sr: sr, res: res, v: vobjs, a: aobjs, effects: effects)diff --git a/src/lib/tinyre.nim b/src/lib/tinyre.nimindex 281ac5b9..7ca6ee38 100644--- a/src/lib/tinyre.nim+++ b/src/lib/tinyre.nim@@ -337,12 +337,12 @@ func addFoldImage(pairs: var seq[int], lo, hi: int, utf8: bool) =image.add c + 32if utf8:for run in foldRuns:- if run.hi < lo or run.lo > hi: continue- var c = int(run.lo)- if c < lo: c += (lo - c + run.step - 1) div run.step * run.step- while c <= min(hi, run.hi):- image.add c + run.delta- c += run.step+ if not (run.hi < lo or run.lo > hi):+ var c = int(run.lo)+ if c < lo: c += (lo - c + run.step - 1) div run.step * run.step+ while c <= min(hi, run.hi):+ image.add c + run.delta+ c += run.stepimage.sortvar k = 0while k < image.len:@@ -530,18 +530,18 @@ func compileCode(re: string, prog: var Prog, utf8, icase: bool,if tok < 0: # \d\D\s\S\w\Wemit -1; emit -tokinc cnt- continue- emit tok- if re.at(i) == ord('-') and re.at(i+1) != ord(']'):- inc i- tok = token(re, i, forward, utf8)- if tok < 0: # a class can't end a range- if re.at(i) == 0 or (re.at(i) == ord('\\') and re.at(i+1) == 0):- fail(reeUnclosedSet, setStart)- fail(if tok == -1: reeBadEscape else: reeBadRange, i)- i += forward- emit tok- inc cnt+ else:+ emit tok+ if re.at(i) == ord('-') and re.at(i+1) != ord(']'):+ inc i+ tok = token(re, i, forward, utf8)+ if tok < 0: # a class can't end a range+ if re.at(i) == 0 or (re.at(i) == ord('\\') and re.at(i+1) == 0):+ fail(reeUnclosedSet, setStart)+ fail(if tok == -1: reeBadEscape else: reeBadRange, i)+ i += forward+ emit tok+ inc cntif icase:var images: seq[int]var k = term + 3@@ -817,7 +817,7 @@ func pikevm(re: Re, s: string, start: int, caps: var seq[int], cont: int,if op >= 0 and op < opWbeg:push(list, count, Thread(pc: pc, sub: sub))break- if op > opJmp or op < 0:+ elif op > opJmp or op < 0:let id = abs(op)if sc.seen[id] == sc.step:decref(sub)@@ -831,8 +831,7 @@ func pikevm(re: Re, s: string, start: int, caps: var seq[int], cont: int,else:pushAlt((pc + 2, sub))pc = target- continue- if op == opSave:+ elif op == opSave:if sc.refs[sub] > 1:dec sc.refs[sub]let copy = newSub()@@ -840,25 +839,24 @@ func pikevm(re: Re, s: string, start: int, caps: var seq[int], cont: int,sub = copysc.pool[sub * nslots + code[pc + 1]] = pospc += 2- continue- if op == opJmp:+ elif op == opJmp:pc += 2 + code[pc + 1]- continue- template wordBefore: bool =- if first: cont >= 0 and isWordAt(s, cont) else: isWordAt(s, prev)- let pass =- case op- of opWb: wordBefore != isWordAt(s, pos)- of opNotb: wordBefore == isWordAt(s, pos)- of opWbeg: not wordBefore and isWordAt(s, pos)- of opWend: wordBefore and not isWordAt(s, pos)- of opBol: first and pos == start and cont < 0- of opEol: pos >= s.len- else: false- if not pass:- decref(sub)- break- inc pc+ else:+ template wordBefore: bool =+ if first: cont >= 0 and isWordAt(s, cont) else: isWordAt(s, prev)+ let pass =+ case op+ of opWb: wordBefore != isWordAt(s, pos)+ of opNotb: wordBefore == isWordAt(s, pos)+ of opWbeg: not wordBefore and isWordAt(s, pos)+ of opWend: wordBefore and not isWordAt(s, pos)+ of opBol: first and pos == start and cont < 0+ of opEol: pos >= s.len+ else: false+ if not pass:+ decref(sub)+ break+ inc pcvar sp = startinc sc.stepdiff --git a/src/main.nim b/src/main.nimindex 5930289a..899bef4d 100644--- a/src/main.nim+++ b/src/main.nim@@ -50,33 +50,31 @@ proc printHelp() {.noreturn.} =var first = truefor opt in mainOptions:- if opt.hidden:- continue-- if opt.c != currentCat or first:- currentCat = opt.c- if first:- first = false+ if not opt.hidden:+ if opt.c != currentCat or first:+ currentCat = opt.c+ if first:+ first = false+ else:+ echo ""+ echo " " & categoryName(currentCat) & ":"++ var optStr = " " & opt.names+ if opt.metavar != "":+ optStr &= " " & opt.metavar++ if optStr.len >= optWidth:+ echo optStr+ let wrapped = wrapText(opt.help, helpWidth, 0)+ for line in wrapped.split("\n"):+ echo " ".repeat(optWidth) & lineelse:- echo ""- echo " " & categoryName(currentCat) & ":"-- var optStr = " " & opt.names- if opt.metavar != "":- optStr &= " " & opt.metavar-- if optStr.len >= optWidth:- echo optStr- let wrapped = wrapText(opt.help, helpWidth, 0)- for line in wrapped.split("\n"):- echo " ".repeat(optWidth) & line- else:- let padding = optWidth - optStr.len- let wrapped = wrapText(opt.help, helpWidth, optWidth)- let helpLines = wrapped.split("\n")- echo optStr & " ".repeat(padding) & helpLines[0]- for i in 1 ..< helpLines.len:- echo helpLines[i]+ let padding = optWidth - optStr.len+ let wrapped = wrapText(opt.help, helpWidth, optWidth)+ let helpLines = wrapped.split("\n")+ echo optStr & " ".repeat(padding) & helpLines[0]+ for i in 1 ..< helpLines.len:+ echo helpLines[i]echo "\n -h, --help" & " ".repeat(optWidth - 14) &wrapText("Show info about this program then exit", helpWidth, optWidth)diff --git a/src/mic.nim b/src/mic.nimindex 3942a247..98e62673 100644--- a/src/mic.nim+++ b/src/mic.nim@@ -125,13 +125,12 @@ elif defined(windows):if device.media_types[j] == AVMEDIA_TYPE_AUDIO:hasAudio = truebreak- if not hasAudio:- continue- if fallback == nil:- fallback = device- let description = $device.device_description- if description.toLowerAscii.contains("usb"):- return ($device.device_name, description, "")+ if hasAudio:+ if fallback == nil:+ fallback = device+ let description = $device.device_description+ if description.toLowerAscii.contains("usb"):+ return ($device.device_name, description, "")if fallback != nil:let description = $fallback.device_description@@ -306,16 +305,16 @@ proc readerLoop(a: ptr MicReaderArgs) {.thread.} =if ret == AVERROR_EAGAIN:# avfoundation never blocks; it just says nothing is ready yet.sleep(2)- continue- if ret < 0:- if not (a.stop[] or a.quit):- a.err = ret- break- if pkt.stream_index != a.streamIndex:- av_packet_unref(pkt)- continue- a.packets.send(pkt) # the consumer frees it- pkt = av_packet_alloc()+ else:+ if ret < 0:+ if not (a.stop[] or a.quit):+ a.err = ret+ break+ if pkt.stream_index == a.streamIndex:+ a.packets.send(pkt) # the consumer frees it+ pkt = av_packet_alloc()+ else:+ av_packet_unref(pkt)if pkt == nil:a.err = AVERROR(ENOMEM)else:diff --git a/src/render/audio.nim b/src/render/audio.nimindex 6e080e2c..acabb4d3 100644--- a/src/render/audio.nim+++ b/src/render/audio.nim@@ -127,14 +127,14 @@ proc toInt16(frame: ptr AVFrame, srcStart, count: int, dst: var seq[int16],template convert(T: typedesc, sample: untyped) =for ch in 0 ..< min(frameChannels, dstChannels):let plane = (if planar: ch else: 0)- if frame.data[plane] == nil: continue- let src = frame.planeAs(plane, T)- let (first, step) =- if planar: (srcStart, 1)- else: (srcStart * frameChannels + ch, frameChannels)- for i in 0 ..< count:- let x {.inject.} = src[first + i * step]- dst[(dstStart + i) * dstChannels + ch] = sample+ if frame.data[plane] != nil:+ let src = frame.planeAs(plane, T)+ let (first, step) =+ if planar: (srcStart, 1)+ else: (srcStart * frameChannels + ch, frameChannels)+ for i in 0 ..< count:+ let x {.inject.} = src[first + i * step]+ dst[(dstStart + i) * dstChannels + ch] = sampleif fmt == AV_SAMPLE_FMT_S16.cint and frameChannels == dstChannels:if count > 0:copyMem(addr dst[dstStart * dstChannels],@@ -180,9 +180,9 @@ func toneTable(wave: Waveform, freq: float, sr: cint): seq[float32] =of wTriangle:if k mod 2 == 0: 0.0else: (if (k div 2) mod 2 == 0: 1.0 else: -1.0) / (k * k).float- if amp == 0.0: continue- for i in 0 ..< toneTableLen:- acc[i] += amp * sin(2.0 * PI * k.float * i.float / toneTableLen.float)+ if amp != 0.0:+ for i in 0 ..< toneTableLen:+ acc[i] += amp * sin(2.0 * PI * k.float * i.float / toneTableLen.float)var peak = 0.0for v in acc:peak = max(peak, abs(v))@@ -328,30 +328,29 @@ proc get(getter: Getter, start, endSample: int, sequential = false): seq[int16]# is already in place, and takes every frame whole.if not sequential and frameSamplePos + samples.int64 <= start.int64:samplesProcessed += samples- continue-- # Calculate how many samples to skip in this frame- let samplesSkippedInFrame =- if sequential: 0 else: max(0, start - frameSamplePos.int)- let samplesInFrame = samples - samplesSkippedInFrame- let samplesToProcess = min(samplesInFrame, targetSamples - totalSamples)-- if not frame.toInt16(samplesSkippedInFrame, samplesToProcess, result,- totalSamples, channels):- error &"Unsupported audio format: {av_get_sample_fmt_name(frame.format)}"-- let left = samplesInFrame - samplesToProcess- if left > 0:- let at = getter.carry.len div channels- getter.carry.setLen((at + left) * channels)- discard frame.toInt16(samplesSkippedInFrame + samplesToProcess, left,- getter.carry, at, channels)-- totalSamples += samplesToProcess- samplesProcessed += samples+ else:+ # Calculate how many samples to skip in this frame+ let samplesSkippedInFrame =+ if sequential: 0 else: max(0, start - frameSamplePos.int)+ let samplesInFrame = samples - samplesSkippedInFrame+ let samplesToProcess = min(samplesInFrame, targetSamples - totalSamples)++ if not frame.toInt16(samplesSkippedInFrame, samplesToProcess, result,+ totalSamples, channels):+ error &"Unsupported audio format: {av_get_sample_fmt_name(frame.format)}"++ let left = samplesInFrame - samplesToProcess+ if left > 0:+ let at = getter.carry.len div channels+ getter.carry.setLen((at + left) * channels)+ discard frame.toInt16(samplesSkippedInFrame + samplesToProcess, left,+ getter.carry, at, channels)++ totalSamples += samplesToProcess+ samplesProcessed += samplestemplate processDecoded() =- # `processFrame` may `continue` the loop, so free after it.+ # Every converted frame is freed in its own pass below, after processing.let converted = getter.resampler.resample(frame)for f in converted:processFrame(f)@@ -515,11 +514,10 @@ proc applyVolume(data: var seq[int16], act: Action, channels: int, sr: cint,perFrame: sr.float64 / fps))for i in 0 ..< frames:let gain = ramp.at(i)- if gain == 1.0'f32:- continue- for ch in 0 ..< channels:- let idx = i * channels + ch- data[idx] = clamp16(int32(round(data[idx].float32 * gain)))+ if gain != 1.0'f32:+ for ch in 0 ..< channels:+ let idx = i * channels + ch+ data[idx] = clamp16(int32(round(data[idx].float32 * gain)))const rampBlock = 1024 # input samples between tempo changes in a ramp@@ -839,9 +837,9 @@ proc mixClipPart(acc: var seq[int32], data: openArray[int16],let dg = (if duckEnv.len > 0: duckEnv[i] else: 1.0'f32)for ch in 0 ..< targetChannels:let sc = sourceChannel(sourceChannels, ch)- if sc < 0: continue- acc[baseIndex + ch] += int32(round(data[- (i - first) * sourceChannels + sc].float32 * gain * dg))+ if sc >= 0:+ acc[baseIndex + ch] += int32(round(data[+ (i - first) * sourceChannels + sc].float32 * gain * dg))if duckEnv.len > 0:for i in lo ..< hi:@@ -970,11 +968,10 @@ proc makeAudioFrames*(fmt: AVSampleFormat, tl: v3, frameSize: int, layerIndices:for layerIndex in layerIndices:if layerIndex < tl.a.len:for clip in tl.a[layerIndex]:- if clip.src == nil:- continue- let key = (clip.src, clip.stream)- if key notin samples:- samples[key] = newGetter(clip.src[], clip.stream, sr)+ if clip.src != nil:+ let key = (clip.src, clip.stream)+ if key notin samples:+ samples[key] = newGetter(clip.src[], clip.stream, sr)# A low note sums thousands of harmonics per table point, and a timeline can# hold hundreds of tone clips (one per kept section), so build each table once.diff --git a/src/render/format.nim b/src/render/format.nimindex 1898a9d9..f6a5ca7f 100644--- a/src/render/format.nim+++ b/src/render/format.nim@@ -115,17 +115,17 @@ proc dropUndecodableAudio*(tl: var v3, cache: MediaCache) =for clip in layer:if clip.src == nil:kept.add clip- continue- let container = cache.getContainer(clip.src)- if clip.stream.int >= container.audio.len:- kept.add clip- continue- let codecId = container.audio[clip.stream.int].codecpar.codec_id- if canDecode(codecId):- kept.add clip- elif not reported.containsOrIncl((clip.src, clip.stream)):- warning &"Skipping audio stream {clip.stream}: no decoder for " &- $avcodec_get_name(codecId)+ else:+ let container = cache.getContainer(clip.src)+ if clip.stream.int >= container.audio.len:+ kept.add clip+ else:+ let codecId = container.audio[clip.stream.int].codecpar.codec_id+ if canDecode(codecId):+ kept.add clip+ elif not reported.containsOrIncl((clip.src, clip.stream)):+ warning &"Skipping audio stream {clip.stream}: no decoder for " &+ $avcodec_get_name(codecId)layer = keptproc makeMedia*(args: mainArgs, inputVideo: VideoSettings, audio: AudioSettings,@@ -216,11 +216,7 @@ proc makeMedia*(args: mainArgs, inputVideo: VideoSettings, audio: AudioSettings,if includeAudio and args.mixAudioStreams and tl.a.len > 0:# Create a single audio stream for mixed output- var hasAnyClips = false- for i in 0..<tl.a.len:- if tl.a[i].len > 0:- hasAnyClips = true- break+ let hasAnyClips = tl.a.anyIt(it.len > 0)if hasAnyClips:let rate = AVRational(num: tl.sr, den: 1)@@ -540,11 +536,8 @@ proc makeMedia*(args: mainArgs, inputVideo: VideoSettings, audio: AudioSettings,index = max(index, audioIndex)# Break if no more frames- var hasFrames = videoFrame != nil or videoPacket != nil- for audioFrame in audioFrames:- if audioFrame != nil:- hasFrames = true- break+ var hasFrames = videoFrame != nil or videoPacket != nil or+ audioFrames.anyIt(it != nil)for i, e in asyncAudio:if e != nil and not audioDone[i]:hasFrames = true@@ -622,13 +615,12 @@ proc makeMedia*(args: mainArgs, inputVideo: VideoSettings, audio: AudioSettings,av_packet_unref(outPacket)for i, aEncCtx in audioEncoders:- if asyncAudio[i] != nil:- continue # flushed above- for outPacket in aEncCtx.encode(nil, outPacket):- outPacket.stream_index = audioStreams[i].index- av_packet_rescale_ts(outPacket, aEncCtx.time_base, audioStreams[i].time_base)- output.mux(outPacket[])- av_packet_unref(outPacket)+ if asyncAudio[i] == nil: # otherwise it was already flushed above+ for outPacket in aEncCtx.encode(nil, outPacket):+ outPacket.stream_index = audioStreams[i].index+ av_packet_rescale_ts(outPacket, aEncCtx.time_base, audioStreams[i].time_base)+ output.mux(outPacket[])+ av_packet_unref(outPacket)# Copy embedded imagesfor (outStream, cachedPkt) in imageStreams:diff --git a/src/render/h264.nim b/src/render/h264.nimindex 6d5b34e2..9311e660 100644--- a/src/render/h264.nim+++ b/src/render/h264.nim@@ -43,11 +43,11 @@ func h264IsCopyBoundary*(data: ptr uint8, size: int): bool =let codeLen = startCodeLen(bytes, size, pos)if codeLen == 0:inc pos- continue- let nal = pos + codeLen- if nal < size and (bytes[nal] and 0x1f) == 5:- return true- pos = nal + 1+ else:+ let nal = pos + codeLen+ if nal < size and (bytes[nal] and 0x1f) == 5:+ return true+ pos = nal + 1else:if pos + 4 > size:breakdiff --git a/src/render/hevc.nim b/src/render/hevc.nimindex 812cdd07..539015a4 100644--- a/src/render/hevc.nim+++ b/src/render/hevc.nim@@ -12,14 +12,14 @@ proc annexBParameterSets(data: ptr uint8, size: int): seq[uint8] =let codeLen = startCodeLen(bytes, size, pos)if codeLen == 0:inc pos- continue- let nalStart = pos + codeLen- var next = nalStart- while next < size and startCodeLen(bytes, size, next) == 0:- inc next- if bytes.nalType(nalStart, size) in 32..34:- result.appendNal(bytes, nalStart, next)- pos = next+ else:+ let nalStart = pos + codeLen+ var next = nalStart+ while next < size and startCodeLen(bytes, size, next) == 0:+ inc next+ if bytes.nalType(nalStart, size) in 32..34:+ result.appendNal(bytes, nalStart, next)+ pos = nextproc parameterSetsToHvcc*(data: ptr uint8, size: int): seq[uint8] =## Return VPS/SPS/PPS NAL units with four-byte lengths. Encoder extradata is@@ -129,9 +129,9 @@ proc annexBToHvcC*(data: ptr uint8, size: int): seq[uint8] =for b in sps[2 .. ^1]: # drop emulation prevention bytesif zeros >= 2 and b == 3:zeros = 0- continue- zeros = (if b == 0: zeros + 1 else: 0)- r.data.add b+ else:+ zeros = (if b == 0: zeros + 1 else: 0)+ r.data.add bif r.data.len < 13:returntry:@@ -190,12 +190,12 @@ func hevcIsCopyBoundary*(data: ptr uint8, size: int): bool =let codeLen = startCodeLen(bytes, size, pos)if codeLen == 0:inc pos- continue- let nal = pos + codeLen- let typ = bytes.nalType(nal, size)- if typ.hevcNalIsCopyBoundary:- return true- pos = nal + 1+ else:+ let nal = pos + codeLen+ let typ = bytes.nalType(nal, size)+ if typ.hevcNalIsCopyBoundary:+ return true+ pos = nal + 1else:if pos + 4 > size:breakdiff --git a/src/render/partialplan.nim b/src/render/partialplan.nimindex 57c1add9..c2cf8bf6 100644--- a/src/render/partialplan.nim+++ b/src/render/partialplan.nim@@ -369,12 +369,12 @@ proc makePartialLossless*(output: var OutputContainer, tl: v3, video: VideoSetti# Runs of consecutive encode spans: each one's first and last span.var runFirst, runLast: seq[int]for i, span in spans:- if span.kind != ssEncode: continue- if i > 0 and spans[i - 1].kind == ssEncode:- runLast[^1] = i- else:- runFirst.add i- runLast.add i+ if span.kind == ssEncode:+ if i > 0 and spans[i - 1].kind == ssEncode:+ runLast[^1] = i+ else:+ runFirst.add i+ runLast.add i# The range each fed run's packets take among all the encoded packets.var runStart, runEnd: seq[int64]diff --git a/src/render/smart.nim b/src/render/smart.nimindex edd702c9..277ac37a 100644--- a/src/render/smart.nim+++ b/src/render/smart.nim@@ -44,11 +44,11 @@ func smartRenderPlan*(clips: openArray[Clip], keyframes: openArray[int64],let finalGopNeedsHold = i + 1 == keyframes.len and clipSrcEnd > sourceEndif gopEnd > clipSrcEnd or gopEnd <= keyframe or finalGopNeedsHold:inc i- continue- result.addSpan(ssEncode, cursor, keyframe, clip.start + cursor - clip.offset)- result.addSpan(ssCopy, keyframe, gopEnd, clip.start + keyframe - clip.offset)- cursor = gopEnd- inc i+ else:+ result.addSpan(ssEncode, cursor, keyframe, clip.start + cursor - clip.offset)+ result.addSpan(ssCopy, keyframe, gopEnd, clip.start + keyframe - clip.offset)+ cursor = gopEnd+ inc iresult.addSpan(ssEncode, cursor, clipSrcEnd, clip.start + cursor - clip.offset)func smartPlanStats*(spans: openArray[SmartSpan]): SmartPlanStats =@@ -152,13 +152,13 @@ proc annexBToLengthPrefixed*(data: ptr uint8, size: int): seq[uint8] =let codeLen = startCodeLen(bytes, size, pos)if codeLen == 0:inc pos- continue- let nalStart = pos + codeLen- var next = nalStart- while next < size and startCodeLen(bytes, size, next) == 0:- inc next- result.appendNal(bytes, nalStart, next)- pos = next+ else:+ let nalStart = pos + codeLen+ var next = nalStart+ while next < size and startCodeLen(bytes, size, next) == 0:+ inc next+ result.appendNal(bytes, nalStart, next)+ pos = nextproc normalizeLengthPrefixed*(packet: ptr AVPacket,parameterSets: openArray[uint8], label: string, annexB: bool) =diff --git a/src/render/subtitle.nim b/src/render/subtitle.nimindex 0242236f..68b494e9 100644--- a/src/render/subtitle.nim+++ b/src/render/subtitle.nim@@ -172,20 +172,18 @@ proc writeCaptions*(track: CaptionTrack, ctx: ptr AVCodecContext,let size = avcodec_encode_subtitle(ctx, addr buf[0], buf.len.cint, addr sub)if size < 0:error "Could not encode caption: " & av_err2str(size)- if size == 0:- continue-- var packet: AVPacket- if av_new_packet(addr packet, size) < 0:- error "Could not allocate caption packet"- copyMem(packet.data, addr buf[0], size)- packet.stream_index = outputStream.index- packet.time_base = ctx.time_base- packet.pts = pts- packet.dts = pts- packet.duration = dur- output.mux(packet)- av_packet_unref(addr packet)+ if size != 0:+ var packet: AVPacket+ if av_new_packet(addr packet, size) < 0:+ error "Could not allocate caption packet"+ copyMem(packet.data, addr buf[0], size)+ packet.stream_index = outputStream.index+ packet.time_base = ctx.time_base+ packet.pts = pts+ packet.dts = pts+ packet.duration = dur+ output.mux(packet)+ av_packet_unref(addr packet)proc makeAlteredSubtitle*(sourcePath, outputPath: string, layer: seq[Clip],effects: seq[Actions], timelineTb: AVRational) =diff --git a/src/render/video.nim b/src/render/video.nimindex aef7cb93..e0ae8079 100644--- a/src/render/video.nim+++ b/src/render/video.nim@@ -733,21 +733,20 @@ proc fillChip(frame: ptr AVFrame, poly: Chip, color: RGBColor) =else:row[x] = uint8(float32(row[x]) * (1.0'f32 - c) +float32(yv) * c + 0.5'f32)- if rgba or not hit:- continue- # Chroma is half resolution, so one sample stands for a 2x2 luma block. Take- # the block's strongest coverage, or a thin sliver would lose its color.- let uRow = frame.planeRow(1, cy)- let vRow = frame.planeRow(2, cy)- for cx in (x0 div 2) .. ((x1 - 1) div 2):- var c = 0.0'f32- for k in (cx * 2 - x0) .. (cx * 2 + 1 - x0):- if k >= 0 and k < n:- c = max(c, max(cov[0][k], cov[1][k]))- if c <= 0.002'f32:- continue- uRow[cx] = uint8(float32(uRow[cx]) * (1.0'f32 - c) + float32(uv) * c + 0.5'f32)- vRow[cx] = uint8(float32(vRow[cx]) * (1.0'f32 - c) + float32(vv) * c + 0.5'f32)+ if not rgba and hit:+ # Chroma is half resolution, so one sample stands for a 2x2 luma block. Take+ # the block's strongest coverage, or a thin sliver would lose its color.+ let uRow = frame.planeRow(1, cy)+ let vRow = frame.planeRow(2, cy)+ for cx in (x0 div 2) .. ((x1 - 1) div 2):+ var c = 0.0'f32+ for k in (cx * 2 - x0) .. (cx * 2 + 1 - x0):+ if k >= 0 and k < n:+ c = max(c, max(cov[0][k], cov[1][k]))+ if c <= 0.002'f32:+ continue+ uRow[cx] = uint8(float32(uRow[cx]) * (1.0'f32 - c) + float32(uv) * c + 0.5'f32)+ vRow[cx] = uint8(float32(vRow[cx]) * (1.0'f32 - c) + float32(vv) * c + 0.5'f32)proc drawConfetti(frame: ptr AVFrame, act: Action, local: int, fps: float) =## One frame of the confetti animation.@@ -824,54 +823,50 @@ proc drawConfetti(frame: ptr AVFrame, act: Action, local: int, fps: float) =# Fired once per section, nothing replaced after it falls out. The stagger is# short against the whole burst, so it rips out but still reads as one pop.let t = t0 - uWhen * 0.4'f32- if t <= 0.0'f32:- continue-- let decay = (1.0'f32 - exp(-k * t)) / k- let sway = h * (0.010'f32 + 0.020'f32 * uSway)- let freq = 0.5'f32 + uSpin- let px = x0 + vx0 * decay * h + sway * sin(tau * freq * t + uSway * tau)- let py = y0 + (vt * t + (vy0 - vt) * decay) * h-- let size = h * (0.024'f32 + 0.024'f32 * uSize)-- # Phrased positively so a non-finite piece is dropped rather than reaching- # an unchecked float -> int conversion. `size` bounds the outline.- if not (px + size >= 0.0'f32 and px - size <= w and- py + size >= 0.0'f32 and py - size <= h):- continue-- # Spin in-plane (Rz) while tumbling end over end (Rx) and edge to edge (Ry).- # The chip is flat, so local z = 0 collapses the three matrices to this;- # dropping z projects it, foreshortening a chip that turns away.- let spinZ = (1.5'f32 + 4.0'f32 * uSpin) * t + uPhase * tau- let turnX = (2.0'f32 + 5.0'f32 * uTumble) * t + uSize * tau- let turnY = (1.5'f32 + 4.0'f32 * uRoll) * t + uAim * tau- let ca = cos(spinZ)- let sa = sin(spinZ)- let cb = cos(turnX)- let sb = sin(turnX)- let cc = cos(turnY)- let sc = sin(turnY)-- var poly: Chip # uShape sets the proportions: narrow strip to near-square- chipOutline(n, size * 0.5'f32, size * (0.22'f32 + 0.28'f32 * uShape), poly)- for j in 0 ..< 4:- let lx = poly[j].x * ca - poly[j].y * sa- let ly = poly[j].x * sa + poly[j].y * ca- poly[j] = (px + lx * cc + ly * sb * sc, py + ly * cb)-- let idx = min(palette.len - 1, int(hashUnit(n, 8) * float32(palette.len)))- var color = unpackRGB(palette[idx])- if act.cShimmer:- # cb*cc is how square-on the chip is to the viewer, so near 0 is edge-on:- # the angle that catches a light off to the side. Ramped, so the glint- # rolls through the turn.- const glintBelow = 0.25'f32- let facing = abs(cb * cc)- if facing < glintBelow:- color = towardWhite(color, (glintBelow - facing) / glintBelow)- fillChip(frame, poly, color)+ if t > 0.0'f32:+ let decay = (1.0'f32 - exp(-k * t)) / k+ let sway = h * (0.010'f32 + 0.020'f32 * uSway)+ let freq = 0.5'f32 + uSpin+ let px = x0 + vx0 * decay * h + sway * sin(tau * freq * t + uSway * tau)+ let py = y0 + (vt * t + (vy0 - vt) * decay) * h++ let size = h * (0.024'f32 + 0.024'f32 * uSize)++ # Phrased positively so a non-finite piece is dropped rather than reaching+ # an unchecked float -> int conversion. `size` bounds the outline.+ if px + size >= 0.0'f32 and px - size <= w and+ py + size >= 0.0'f32 and py - size <= h:+ # Spin in-plane (Rz) while tumbling end over end (Rx) and edge to edge (Ry).+ # The chip is flat, so local z = 0 collapses the three matrices to this;+ # dropping z projects it, foreshortening a chip that turns away.+ let spinZ = (1.5'f32 + 4.0'f32 * uSpin) * t + uPhase * tau+ let turnX = (2.0'f32 + 5.0'f32 * uTumble) * t + uSize * tau+ let turnY = (1.5'f32 + 4.0'f32 * uRoll) * t + uAim * tau+ let ca = cos(spinZ)+ let sa = sin(spinZ)+ let cb = cos(turnX)+ let sb = sin(turnX)+ let cc = cos(turnY)+ let sc = sin(turnY)++ var poly: Chip # uShape sets the proportions: narrow strip to near-square+ chipOutline(n, size * 0.5'f32, size * (0.22'f32 + 0.28'f32 * uShape), poly)+ for j in 0 ..< 4:+ let lx = poly[j].x * ca - poly[j].y * sa+ let ly = poly[j].x * sa + poly[j].y * ca+ poly[j] = (px + lx * cc + ly * sb * sc, py + ly * cb)++ let idx = min(palette.len - 1, int(hashUnit(n, 8) * float32(palette.len)))+ var color = unpackRGB(palette[idx])+ if act.cShimmer:+ # cb*cc is how square-on the chip is to the viewer, so near 0 is edge-on:+ # the angle that catches a light off to the side. Ramped, so the glint+ # rolls through the turn.+ const glintBelow = 0.25'f32+ let facing = abs(cb * cc)+ if facing < glintBelow:+ color = towardWhite(color, (glintBelow - facing) / glintBelow)+ fillChip(frame, poly, color)proc scaleWithPad(src: ptr AVFrame, targetW, targetH: int32,bg: RGBColor, tag: YuvTag, swsCtx: var ptr SwsContext): ptr AVFrame =@@ -986,22 +981,20 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,# Audio-only sources (e.g. the .mp3 behind a synthesized video canvas) have# no video stream to decode.- if myCache.cns[src].video.len == 0:- continue-- let decoderCtx = initDecoder(myCache.cns[src].video[0].codecpar)- decoderCtx.thread_type = FF_THREAD_FRAME or FF_THREAD_SLICE- srcs[src].decoders.add newDecState(myCache.cns[src], decoderCtx, false)-- # An image source is a single still: an image codec read by an image- # demuxer, or a stream that reports exactly one frame. The demuxer check- # matters because these codecs also carry real video (MJPEG in avi/mov).- let vstream = myCache.cns[src].video[0]- let imageCodecs = [ID_PNG, ID_JPEG, ID_WEBP, ID_BMP, ID_TIFF]- let demuxer = $myCache.cns[src].formatContext.iformat.name- srcs[src].isStill = vstream.nb_frames == 1 or- (vstream.codecpar.codec_id in imageCodecs and- (demuxer == "image2" or demuxer.endsWith("_pipe")))+ if myCache.cns[src].video.len > 0:+ let decoderCtx = initDecoder(myCache.cns[src].video[0].codecpar)+ decoderCtx.thread_type = FF_THREAD_FRAME or FF_THREAD_SLICE+ srcs[src].decoders.add newDecState(myCache.cns[src], decoderCtx, false)++ # An image source is a single still: an image codec read by an image+ # demuxer, or a stream that reports exactly one frame. The demuxer check+ # matters because these codecs also carry real video (MJPEG in avi/mov).+ let vstream = myCache.cns[src].video[0]+ let imageCodecs = [ID_PNG, ID_JPEG, ID_WEBP, ID_BMP, ID_TIFF]+ let demuxer = $myCache.cns[src].formatContext.iformat.name+ srcs[src].isStill = vstream.nb_frames == 1 or+ (vstream.codecpar.codec_id in imageCodecs and+ (demuxer == "image2" or demuxer.endsWith("_pipe")))let (targetWidth, targetHeight) = scaledVideoResolution(tl.res, video.scale)var fxGraph: Graph = nil@@ -1462,22 +1455,22 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,actHighpass, actLowpass, actDehum, actPos, actRotate, actLoop: discardof actScale, actTurn:# An overlay is scaled and turned where it's placed, about its center.- if isOverlay or placeDone: continue- placeDone = true- let (sx, sy, deg) = scaleTurnOf(effects)- if sx == 1.0'f32 and sy == 1.0'f32 and mod360(deg) == 0: continue- let w = frame.width- let h = frame.height- let sw = max(2.cint, cint(round(w.float32 * sx))) and not 1.cint- let sh = max(2.cint, cint(round(h.float32 * sy))) and not 1.cint- runFx(fxId(actScale, frame, f0 = sx, f1 = deg, f2 = sy)):- # rotate turns about the center of a frame of the canvas's size,- # cropping what's past it and filling what's uncovered with bg.- let nodes = @[fxGraph.add("buffer", bufArgsOf(frame)),- fxGraph.add("scale", &"{sw}:{sh}"),- fxGraph.add("rotate", &"a={deg}*PI/180:ow={w}:oh={h}:c={bg}"),- fxGraph.add("buffersink")]- fxGraph.linkNodes(nodes).configure()+ if not (isOverlay or placeDone):+ placeDone = true+ let (sx, sy, deg) = scaleTurnOf(effects)+ if not (sx == 1.0'f32 and sy == 1.0'f32 and mod360(deg) == 0):+ let w = frame.width+ let h = frame.height+ let sw = max(2.cint, cint(round(w.float32 * sx))) and not 1.cint+ let sh = max(2.cint, cint(round(h.float32 * sy))) and not 1.cint+ runFx(fxId(actScale, frame, f0 = sx, f1 = deg, f2 = sy)):+ # rotate turns about the center of a frame of the canvas's size,+ # cropping what's past it and filling what's uncovered with bg.+ let nodes = @[fxGraph.add("buffer", bufArgsOf(frame)),+ fxGraph.add("scale", &"{sw}:{sh}"),+ fxGraph.add("rotate", &"a={deg}*PI/180:ow={w}:oh={h}:c={bg}"),+ fxGraph.add("buffersink")]+ fxGraph.linkNodes(nodes).configure()of actSpin:let rate = effect.sRatelet startDeg = rotDeg(effect.sStart)@@ -1510,56 +1503,55 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,frame = fittedof actZoom:let z = sample(effect, effect.kf, effect.kt)- if z == 1.0'f32:- continue- let origW = frame.width- let origH = frame.height- if zoomCtx == nil:- zoomCtx = sws_alloc_context()+ if z != 1.0'f32:+ let origW = frame.width+ let origH = frame.heightif zoomCtx == nil:- error "Failed to allocate zoom sws context"- zoomCtx.setOpt("threads", 0)- let scaledW = max(cint(float(origW) * z), 2)- let scaledH = max(cint(float(origH) * z), 2)- if z > 1.0:- # Scale only the source region that stays visible instead of the whole- # frame, which at z=3 is 9x the pixels. The window is then placed- # where the full-frame scale would have put it, in output pixels, so- # an animated zoom doesn't step by whole source pixels.- if AVPixelFormat(frame.format).isBitstream:- # Cropping moves data pointers, which can't land mid-byte, so- # FFmpeg skips the left and top crop for 1-bit formats.- let gray = frame.reformat(AV_PIX_FMT_GRAY8)- av_frame_free(addr frame)- frame = gray- let d = av_pix_fmt_desc_get(AVPixelFormat(frame.format))- let hstep = 1.cint shl d.log2_chroma_w- let vstep = 1.cint shl d.log2_chroma_h- let x = zoomSpan(origW, scaledW, hstep)- let y = zoomSpan(origH, scaledH, vstep)- cropView(frame, x.start, y.start, origW - x.start - x.len,- origH - y.start - y.len)- let scaledFrame = frame.reformat(AVPixelFormat(frame.format),- x.scaledLen, y.scaledLen, zoomCtx)- if scaledFrame != frame:- av_frame_free(addr frame)- frame = scaledFrame- let cx = clamp(cint(round(x.offset / float(hstep))) * hstep, 0,- (x.scaledLen - origW) div hstep * hstep)- let cy = clamp(cint(round(y.offset / float(vstep))) * vstep, 0,- (y.scaledLen - origH) div vstep * vstep)- cropView(frame, cx, cy, x.scaledLen - origW - cx, y.scaledLen - origH - cy)- else:- let scaledFrame = frame.reformat(AVPixelFormat(frame.format), scaledW,- scaledH, zoomCtx)- if scaledFrame != frame:- av_frame_free(addr frame)- frame = scaledFrame- runFx(fxId(actZoom, frame, i0 = origW.int32, i1 = origH.int32)):- let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))- let pad = fxGraph.add("pad", &"{origW}:{origH}:-1:-1:color={bg}")- let bufferSink = fxGraph.add("buffersink")- fxGraph.linkNodes(bufferSrc, pad, bufferSink).configure()+ zoomCtx = sws_alloc_context()+ if zoomCtx == nil:+ error "Failed to allocate zoom sws context"+ zoomCtx.setOpt("threads", 0)+ let scaledW = max(cint(float(origW) * z), 2)+ let scaledH = max(cint(float(origH) * z), 2)+ if z > 1.0:+ # Scale only the source region that stays visible instead of the whole+ # frame, which at z=3 is 9x the pixels. The window is then placed+ # where the full-frame scale would have put it, in output pixels, so+ # an animated zoom doesn't step by whole source pixels.+ if AVPixelFormat(frame.format).isBitstream:+ # Cropping moves data pointers, which can't land mid-byte, so+ # FFmpeg skips the left and top crop for 1-bit formats.+ let gray = frame.reformat(AV_PIX_FMT_GRAY8)+ av_frame_free(addr frame)+ frame = gray+ let d = av_pix_fmt_desc_get(AVPixelFormat(frame.format))+ let hstep = 1.cint shl d.log2_chroma_w+ let vstep = 1.cint shl d.log2_chroma_h+ let x = zoomSpan(origW, scaledW, hstep)+ let y = zoomSpan(origH, scaledH, vstep)+ cropView(frame, x.start, y.start, origW - x.start - x.len,+ origH - y.start - y.len)+ let scaledFrame = frame.reformat(AVPixelFormat(frame.format),+ x.scaledLen, y.scaledLen, zoomCtx)+ if scaledFrame != frame:+ av_frame_free(addr frame)+ frame = scaledFrame+ let cx = clamp(cint(round(x.offset / float(hstep))) * hstep, 0,+ (x.scaledLen - origW) div hstep * hstep)+ let cy = clamp(cint(round(y.offset / float(vstep))) * vstep, 0,+ (y.scaledLen - origH) div vstep * vstep)+ cropView(frame, cx, cy, x.scaledLen - origW - cx, y.scaledLen - origH - cy)+ else:+ let scaledFrame = frame.reformat(AVPixelFormat(frame.format), scaledW,+ scaledH, zoomCtx)+ if scaledFrame != frame:+ av_frame_free(addr frame)+ frame = scaledFrame+ runFx(fxId(actZoom, frame, i0 = origW.int32, i1 = origH.int32)):+ let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))+ let pad = fxGraph.add("pad", &"{origW}:{origH}:-1:-1:color={bg}")+ let bufferSink = fxGraph.add("buffersink")+ fxGraph.linkNodes(bufferSrc, pad, bufferSink).configure()of actHflip, actVflip, actInvert, actErosion:runFx(fxId(effect.kind, frame)):let filterName = case effect.kind@@ -1573,134 +1565,127 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,fxGraph.linkNodes(bufferSrc, filt, bufferSink).configure()of actBlur:let sigma = sample(effect, effect.kf, effect.kt)- if sigma <= 0.0'f32:- continue- runFx(fxId(actBlur, frame, f0 = sigma)):- let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))- let filt = fxGraph.add("gblur", &"sigma={sigma}")- let bufferSink = fxGraph.add("buffersink")- fxGraph.linkNodes(bufferSrc, filt, bufferSink).configure()+ if sigma > 0.0'f32:+ runFx(fxId(actBlur, frame, f0 = sigma)):+ let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))+ let filt = fxGraph.add("gblur", &"sigma={sigma}")+ let bufferSink = fxGraph.add("buffersink")+ fxGraph.linkNodes(bufferSrc, filt, bufferSink).configure()of actBrightness:let b = sample(effect, effect.kf, effect.kt)- if b == 0.0'f32:- continue- let shift = b * 255.0'f32- runFx(fxId(actBrightness, frame, f0 = shift)):- let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))- let toRgb = fxGraph.add("format", "pix_fmts=rgb24")- let expr = brightnessLutExpr(b)- let lut = fxGraph.add("lutrgb", &"r={expr}:g={expr}:b={expr}")- let toOrig = fxGraph.add("format", &"pix_fmts={$AVPixelFormat(frame.format)}")- let bufferSink = fxGraph.add("buffersink")- fxGraph.linkNodes(bufferSrc, toRgb, lut, toOrig, bufferSink).configure()+ if b != 0.0'f32:+ let shift = b * 255.0'f32+ runFx(fxId(actBrightness, frame, f0 = shift)):+ let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))+ let toRgb = fxGraph.add("format", "pix_fmts=rgb24")+ let expr = brightnessLutExpr(b)+ let lut = fxGraph.add("lutrgb", &"r={expr}:g={expr}:b={expr}")+ let toOrig = fxGraph.add("format", &"pix_fmts={$AVPixelFormat(frame.format)}")+ let bufferSink = fxGraph.add("buffersink")+ fxGraph.linkNodes(bufferSrc, toRgb, lut, toOrig, bufferSink).configure()of actLuv:- if (effect.brighthue == luvBrighthueId and+ if not (effect.brighthue == luvBrighthueId andeffect.contrast == luvContrastId andeffect.saturation == luvSaturationId):- continue-- let b = effect.brighthue- let c = effect.contrast- let s = effect.saturation- runFx(fxId(actLuv, frame, f0 = b, f1 = c, f2 = s)):- let expr = luvLutExprs(b, c, s)- let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))- let toYuv = fxGraph.add("format", "pix_fmts=yuv444p")- let lut = fxGraph.add("lutyuv", &"y={expr.y}:u={expr.u}:v={expr.v}")- let toOrig = fxGraph.add("format", &"pix_fmts={$AVPixelFormat(frame.format)}")- let bufferSink = fxGraph.add("buffersink")- fxGraph.linkNodes(bufferSrc, toYuv, lut, toOrig, bufferSink).configure()- of actOpacity:- let o = sample(effect, effect.kf, effect.kt)- if o >= 1.0'f32:- continue- if isOverlay:- runFx(fxId(actOpacity, frame, overlay = true, f0 = o)):+ let b = effect.brighthue+ let c = effect.contrast+ let s = effect.saturation+ runFx(fxId(actLuv, frame, f0 = b, f1 = c, f2 = s)):+ let expr = luvLutExprs(b, c, s)let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))- let toRgba = fxGraph.add("format", "pix_fmts=rgba")- let lut = fxGraph.add("lutrgb", &"a=val*{o}")+ let toYuv = fxGraph.add("format", "pix_fmts=yuv444p")+ let lut = fxGraph.add("lutyuv", &"y={expr.y}:u={expr.u}:v={expr.v}")+ let toOrig = fxGraph.add("format", &"pix_fmts={$AVPixelFormat(frame.format)}")let bufferSink = fxGraph.add("buffersink")- fxGraph.linkNodes(bufferSrc, toRgba, lut, bufferSink).configure()- else:- runFx(fxId(actOpacity, frame, f0 = o)):- let bgR = (1.0'f32 - o) * float32(bgRgb.red)- let bgG = (1.0'f32 - o) * float32(bgRgb.green)- let bgB = (1.0'f32 - o) * float32(bgRgb.blue)- let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))- let toRgb = fxGraph.add("format", "pix_fmts=rgb24")- let lut = fxGraph.add("lutrgb",- &"r=val*{o}+{bgR}:g=val*{o}+{bgG}:b=val*{o}+{bgB}")- let toOrig = fxGraph.add("format",- &"pix_fmts={$AVPixelFormat(frame.format)}")- let bufferSink = fxGraph.add("buffersink")- fxGraph.linkNodes(bufferSrc, toRgb, lut, toOrig, bufferSink).configure()+ fxGraph.linkNodes(bufferSrc, toYuv, lut, toOrig, bufferSink).configure()+ of actOpacity:+ let o = sample(effect, effect.kf, effect.kt)+ if o < 1.0'f32:+ if isOverlay:+ runFx(fxId(actOpacity, frame, overlay = true, f0 = o)):+ let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))+ let toRgba = fxGraph.add("format", "pix_fmts=rgba")+ let lut = fxGraph.add("lutrgb", &"a=val*{o}")+ let bufferSink = fxGraph.add("buffersink")+ fxGraph.linkNodes(bufferSrc, toRgba, lut, bufferSink).configure()+ else:+ runFx(fxId(actOpacity, frame, f0 = o)):+ let bgR = (1.0'f32 - o) * float32(bgRgb.red)+ let bgG = (1.0'f32 - o) * float32(bgRgb.green)+ let bgB = (1.0'f32 - o) * float32(bgRgb.blue)+ let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))+ let toRgb = fxGraph.add("format", "pix_fmts=rgb24")+ let lut = fxGraph.add("lutrgb",+ &"r=val*{o}+{bgR}:g=val*{o}+{bgG}:b=val*{o}+{bgB}")+ let toOrig = fxGraph.add("format",+ &"pix_fmts={$AVPixelFormat(frame.format)}")+ let bufferSink = fxGraph.add("buffersink")+ fxGraph.linkNodes(bufferSrc, toRgb, lut, toOrig, bufferSink).configure()of actLens:let k1 = effect.k1let k2 = effect.k2- if k1 == 0.0'f32 and k2 == 0.0'f32:- continue- runFx(fxId(actLens, frame, f0 = k1, f1 = k2)):- let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))- let filt = fxGraph.add("lenscorrection", &"k1={k1}:k2={k2}:fc={bg}")- let bufferSink = fxGraph.add("buffersink")- fxGraph.linkNodes(bufferSrc, filt, bufferSink).configure()+ if not (k1 == 0.0'f32 and k2 == 0.0'f32):+ runFx(fxId(actLens, frame, f0 = k1, f1 = k2)):+ let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))+ let filt = fxGraph.add("lenscorrection", &"k1={k1}:k2={k2}:fc={bg}")+ let bufferSink = fxGraph.add("buffersink")+ fxGraph.linkNodes(bufferSrc, filt, bufferSink).configure()of actDrawbox:if effect.dbColor.yuv and AVPixelFormat(frame.format) in[AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVJ420P]:if av_frame_make_writable(frame) < 0:error "Can't make frame writable"fillBox(frame, effect.dbX, effect.dbY, effect.dbW, effect.dbH, effect.dbColor)- continue- runFx(fxId(actDrawbox, frame, i0 = effect.dbX, i1 = effect.dbY,- i2 = effect.dbW, i3 = effect.dbH, col = packRGB(effect.dbColor))):- let col = effect.dbColor.toRgb(frame.colorspace.int,- frame.color_range.int == 2).toString- let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))- let filt = fxGraph.add("drawbox",- # replace=1: on a generator/keyed layer the canvas alpha is 0, and- # compositing an opaque box over it would leave it invisible.- &"x={effect.dbX}:y={effect.dbY}:w={effect.dbW}:h={effect.dbH}" &- &":color={col}:t=fill:replace=1")- let bufferSink = fxGraph.add("buffersink")- fxGraph.linkNodes(bufferSrc, filt, bufferSink).configure()+ else:+ runFx(fxId(actDrawbox, frame, i0 = effect.dbX, i1 = effect.dbY,+ i2 = effect.dbW, i3 = effect.dbH, col = packRGB(effect.dbColor))):+ let col = effect.dbColor.toRgb(frame.colorspace.int,+ frame.color_range.int == 2).toString+ let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))+ let filt = fxGraph.add("drawbox",+ # replace=1: on a generator/keyed layer the canvas alpha is 0, and+ # compositing an opaque box over it would leave it invisible.+ &"x={effect.dbX}:y={effect.dbY}:w={effect.dbW}:h={effect.dbH}" &+ &":color={col}:t=fill:replace=1")+ let bufferSink = fxGraph.add("buffersink")+ fxGraph.linkNodes(bufferSrc, filt, bufferSink).configure()of actColorKey, actChromaKey:if not isOverlay:# Base layer: no lower track to reveal, so replace the keyed color with# the timeline background instead of making it transparent.frame = keyOverBg(frame, effect)- continue- runFx(fxId(effect.kind, frame, f0 = effect.similar, f1 = effect.blend,- col = packRGB(effect.color))):- let col = keyColor(effect, frame)- var nodes = @[fxGraph.add("buffer", bufArgsOf(frame))]- if effect.kind == actChromaKey:- # chromakey keys in YUV-with-alpha; convert in, then back to rgba so- # the composited overlay keeps its alpha channel.- nodes.add fxGraph.add("format", "pix_fmts=yuva420p")- nodes.add fxGraph.add("chromakey", &"{col}:{effect.similar}:{effect.blend}")- nodes.add fxGraph.add("format", "pix_fmts=rgba")- else:- nodes.add fxGraph.add("colorkey", &"{col}:{effect.similar}:{effect.blend}")- nodes.add fxGraph.add("buffersink")- fxGraph.linkNodes(nodes).configure()+ else:+ runFx(fxId(effect.kind, frame, f0 = effect.similar, f1 = effect.blend,+ col = packRGB(effect.color))):+ let col = keyColor(effect, frame)+ var nodes = @[fxGraph.add("buffer", bufArgsOf(frame))]+ if effect.kind == actChromaKey:+ # chromakey keys in YUV-with-alpha; convert in, then back to rgba so+ # the composited overlay keeps its alpha channel.+ nodes.add fxGraph.add("format", "pix_fmts=yuva420p")+ nodes.add fxGraph.add("chromakey", &"{col}:{effect.similar}:{effect.blend}")+ nodes.add fxGraph.add("format", "pix_fmts=rgba")+ else:+ nodes.add fxGraph.add("colorkey", &"{col}:{effect.similar}:{effect.blend}")+ nodes.add fxGraph.add("buffersink")+ fxGraph.linkNodes(nodes).configure()of actChoke:# Choke (shrink) the alpha matte a key produced, to cut off the spill# fringe. Only overlay layers carry alpha; the base track keys over bg# (no matte), so there is nothing to choke there.- if not isOverlay or not hasAlpha(AVPixelFormat(frame.format)):- continue- let n = max(1, int(effect.chokeN))- runFx(fxId(actChoke, frame, i0 = n.int32)):- var nodes = @[fxGraph.add("buffer", bufArgsOf(frame))]- # Erode only the alpha plane: in gbrap the color planes are 0=G, 1=B,- # 2=R, so threshold0..2=0 freezes them and only plane 3 (alpha) erodes.- # Each pass pulls the matte edge inward by 1px.- nodes.add fxGraph.add("format", "pix_fmts=gbrap")- for _ in 0 ..< n:- nodes.add fxGraph.add("erosion", "threshold0=0:threshold1=0:threshold2=0")- nodes.add fxGraph.add("format", &"pix_fmts={$AVPixelFormat(frame.format)}")- nodes.add fxGraph.add("buffersink")- fxGraph.linkNodes(nodes).configure()+ if isOverlay and hasAlpha(AVPixelFormat(frame.format)):+ let n = max(1, int(effect.chokeN))+ runFx(fxId(actChoke, frame, i0 = n.int32)):+ var nodes = @[fxGraph.add("buffer", bufArgsOf(frame))]+ # Erode only the alpha plane: in gbrap the color planes are 0=G, 1=B,+ # 2=R, so threshold0..2=0 freezes them and only plane 3 (alpha) erodes.+ # Each pass pulls the matte edge inward by 1px.+ nodes.add fxGraph.add("format", "pix_fmts=gbrap")+ for _ in 0 ..< n:+ nodes.add fxGraph.add("erosion", "threshold0=0:threshold1=0:threshold2=0")+ nodes.add fxGraph.add("format", &"pix_fmts={$AVPixelFormat(frame.format)}")+ nodes.add fxGraph.add("buffersink")+ fxGraph.linkNodes(nodes).configure()of actAberration:# Fake chromatic aberration: slide each color channel by its own offset,# so the gaps show up as colored fringing. Via rgba so an overlay layer's@@ -1732,13 +1717,12 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,# block larger than the plane; 1x1 blocks are a no-op.let w = min(int(round(sample(effect, effect.pixWKf, effect.pixWKt))), frame.width)let h = min(int(round(sample(effect, effect.pixHKf, effect.pixHKt))), frame.height)- if w <= 1 and h <= 1:- continue- runFx(fxId(actPixelate, frame, i0 = w.int32, i1 = h.int32)):- let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))- let filt = fxGraph.add("pixelize", &"width={w}:height={h}")- let bufferSink = fxGraph.add("buffersink")- fxGraph.linkNodes(bufferSrc, filt, bufferSink).configure()+ if w > 1 or h > 1:+ runFx(fxId(actPixelate, frame, i0 = w.int32, i1 = h.int32)):+ let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))+ let filt = fxGraph.add("pixelize", &"width={w}:height={h}")+ let bufferSink = fxGraph.add("buffersink")+ fxGraph.linkNodes(bufferSrc, filt, bufferSink).configure()of actConfetti:# In the layer's own format so an overlay's alpha survives; fillRect only# writes yuv420p and rgba, so convert anything else first.@@ -1784,15 +1768,15 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,## not yet used this timeline frame. When all are, opens another.var bestCost = high(int)for d in ss.decoders:- if d.usedAt == frameNo: continue- let pos = d.loopBase + d.frameIndex- let cost =- if d.held != nil and obj.index >= d.lastReqIndex and obj.index <= pos: 0- elif obj.index >= pos: obj.index - pos- else: high(int) div 2 # behind it: a backward seek- if cost < bestCost:- bestCost = cost- result = d+ if d.usedAt != frameNo:+ let pos = d.loopBase + d.frameIndex+ let cost =+ if d.held != nil and obj.index >= d.lastReqIndex and obj.index <= pos: 0+ elif obj.index >= pos: obj.index - pos+ else: high(int) div 2 # behind it: a backward seek+ if cost < bestCost:+ bestCost = cost+ result = dif result == nil:if ss.decoders.len < maxDecoders:let cn = (try: av.open(src[]) except IOError as e: error e.msg)@@ -1945,41 +1929,38 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,if lastGood != nil: av_frame_free(addr lastGood)lastGood = av_frame_clone(frame)- if not foundFrame:- if looping and frameIndex >= 0:- loopBase += frameIndex + 1- target = obj.index - loopBase- st.cn.seek(0, stream = myStream)- avcodec_flush_buffers(st.decoder)- st.resetDeint()- st.lastSeekTarget = -1- frameIndex = -1- continue-- if holdPastEnd and (lastGood != nil or st.held != nil):- av_frame_free(addr frame)- if lastGood != nil:- frame = lastGood- lastGood = nil- didDecode = true- else:- frame = av_frame_clone(st.held)- fromHeld = true- break-+ if foundFrame:+ didDecode = true++ if hasSeekFrame:+ let framesAvoided = frameIndex - seekFrame+ debug &"Seek landed at frame {frameIndex}, avoided decoding {framesAvoided} frames"+ framesSaved += framesAvoided+ hasSeekFrame = false+ elif looping and frameIndex >= 0:+ loopBase += frameIndex + 1+ target = obj.index - loopBase+ st.cn.seek(0, stream = myStream)+ avcodec_flush_buffers(st.decoder)+ st.resetDeint()+ st.lastSeekTarget = -1+ frameIndex = -1+ elif holdPastEnd and (lastGood != nil or st.held != nil):+ av_frame_free(addr frame)+ if lastGood != nil:+ frame = lastGood+ lastGood = nil+ didDecode = true+ else:+ frame = av_frame_clone(st.held)+ fromHeld = true+ break+ else:didDecode = falseav_frame_free(addr frame)frame = av_frame_clone(nullFrame)break- didDecode = true-- if hasSeekFrame:- let framesAvoided = frameIndex - seekFrame- debug &"Seek landed at frame {frameIndex}, avoided decoding {framesAvoided} frames"- framesSaved += framesAvoided- hasSeekFrame = false-if didDecode:# Another layer sharing this (src, index) reuses it this timeline frame.decodedCache[cacheKey] = av_frame_clone(frame)@@ -2378,48 +2359,47 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,av_frame_free(addr acc)acc = newAccinc k- continue-- # A transition: the picture with the clip going out, blended into- # the one with the clip coming in, both over what's below.- var j = k- while j < objList.len and objList[j].layer == o.layer and- objList[j].win == o.win:- inc j- let isBase = acc == nil- let below =- if isBase: makeSolid(tl.res[0], tl.res[1], tl.bg, solidTag) else: acc- var fromF, toF: ptr AVFrame = nil- for m in k ..< j:- var f =- if isBase: baseFrame(objList[m])- else: overlayObj(below, objList[m])- if f == nil: f = av_frame_clone(below)- if objList[m].incoming:- if toF != nil: av_frame_free(addr toF)- toF = f- else:- if fromF != nil: av_frame_free(addr fromF)- fromF = f- if fromF == nil: fromF = av_frame_clone(below)- if toF == nil: toF = av_frame_clone(below)- let w = tl.windows[o.layer][o.win]- let local = index - w.start- # As Premiere: the first frame is all the outgoing picture.- let p = float32(local.float / w.dur.float)- let seed = uint32(w.start and 0xffffffff) xor (uint32(o.layer) * 2654435761'u32)- let dip: tuple[r, g, b: float32] = (bgRgb.red.float32, bgRgb.green.float32,- bgRgb.blue.float32)- let toRgb = lazyCtx(toRgbCtx)- let img = render(w.kind, fromF.toImg(toRgb), toF.toImg(toRgb),- below.toImg(toRgb), p, local.int, w.dur.int, seed, dip, w.easeIn,- w.easeOut)- acc = img.fromImg(fromF, lazyCtx(fromRgbCtx))- av_frame_free(addr fromF)- av_frame_free(addr toF)- var b = below- av_frame_free(addr b)- k = j+ else:+ # A transition: the picture with the clip going out, blended into+ # the one with the clip coming in, both over what's below.+ var j = k+ while j < objList.len and objList[j].layer == o.layer and+ objList[j].win == o.win:+ inc j+ let isBase = acc == nil+ let below =+ if isBase: makeSolid(tl.res[0], tl.res[1], tl.bg, solidTag) else: acc+ var fromF, toF: ptr AVFrame = nil+ for m in k ..< j:+ var f =+ if isBase: baseFrame(objList[m])+ else: overlayObj(below, objList[m])+ if f == nil: f = av_frame_clone(below)+ if objList[m].incoming:+ if toF != nil: av_frame_free(addr toF)+ toF = f+ else:+ if fromF != nil: av_frame_free(addr fromF)+ fromF = f+ if fromF == nil: fromF = av_frame_clone(below)+ if toF == nil: toF = av_frame_clone(below)+ let w = tl.windows[o.layer][o.win]+ let local = index - w.start+ # As Premiere: the first frame is all the outgoing picture.+ let p = float32(local.float / w.dur.float)+ let seed = uint32(w.start and 0xffffffff) xor (uint32(o.layer) * 2654435761'u32)+ let dip: tuple[r, g, b: float32] = (bgRgb.red.float32, bgRgb.green.float32,+ bgRgb.blue.float32)+ let toRgb = lazyCtx(toRgbCtx)+ let img = render(w.kind, fromF.toImg(toRgb), toF.toImg(toRgb),+ below.toImg(toRgb), p, local.int, w.dur.int, seed, dip, w.easeIn,+ w.easeOut)+ acc = img.fromImg(fromF, lazyCtx(fromRgbCtx))+ av_frame_free(addr fromF)+ av_frame_free(addr toF)+ var b = below+ av_frame_free(addr b)+ k = jlet scaledAcc = scaleProxyFrame(acc)if scaledAcc != acc:@@ -2452,23 +2432,22 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,lastProcessedFrame != nil:av_frame_free(addr frame)frame = av_frame_clone(lastProcessedFrame)- continue-- var (decoded, didDecode) = decodeClipFrame(obj)- if didDecode:- av_frame_free(addr frame)- frame = decoded- # decodeClipFrame returns native resolution; scale the final frame to- # the canvas (intermediate seek frames never reach here, so the resize- # costs one sws_scale rather than one per decoded frame).- if (frame.width.int32, frame.height.int32) != tl.res:- let oldFrame = frame- frame = scaleWithPad(frame, tl.res[0], tl.res[1], tl.bg, solidTag, padCtx)- av_frame_free(addr oldFrame)else:- # No new frame decoded: keep the pre-initialized `frame` (nullFrame, or- # the last frame for RGB8 palette persistence) and drop the fallback.- av_frame_free(addr decoded)+ var (decoded, didDecode) = decodeClipFrame(obj)+ if didDecode:+ av_frame_free(addr frame)+ frame = decoded+ # decodeClipFrame returns native resolution; scale the final frame to+ # the canvas (intermediate seek frames never reach here, so the resize+ # costs one sws_scale rather than one per decoded frame).+ if (frame.width.int32, frame.height.int32) != tl.res:+ let oldFrame = frame+ frame = scaleWithPad(frame, tl.res[0], tl.res[1], tl.bg, solidTag, padCtx)+ av_frame_free(addr oldFrame)+ else:+ # No new frame decoded: keep the pre-initialized `frame` (nullFrame, or+ # the last frame for RGB8 palette persistence) and drop the fallback.+ av_frame_free(addr decoded)# Effects take canvas pixels, so they run at the canvas size and the# proxy scale comes after, as when compositing. A clip with no framediff --git a/src/timeline.nim b/src/timeline.nimindex d7792200..68c209a2 100644--- a/src/timeline.nim+++ b/src/timeline.nim@@ -154,14 +154,14 @@ proc rescale*(self: var v3, tb: AVRational) {.raises: [ActionParseError].} =var repacked: seq[(int, Actions)]try:for i, e in self.effects:- if e.isCut or e.isEmpty: continue- var list: seq[Action]- var changed = false- for a in e:- var a = a- changed = rescaleAction(a, k) or changed- list.add a- if changed: repacked.add (i, newActions(list))+ if not (e.isCut or e.isEmpty):+ var list: seq[Action]+ var changed = false+ for a in e:+ var a = a+ changed = rescaleAction(a, k) or changed+ list.add a+ if changed: repacked.add (i, newActions(list))except ActionParseError as err:for (_, e) in repacked: free(e)raise err@@ -289,12 +289,10 @@ proc linearClips(src: ptr string, effects: seq[Actions], actionIndex: seq[int],if speed != 99999.0:let (offset, dur) = clipBounds(chunk[0], chunk[1], speed)- if dur == 0:- continue-- result.add Clip(src: src, start: timelineStart, dur: dur,- offset: offset, effects: e)- timelineStart += dur+ if dur != 0:+ result.add Clip(src: src, start: timelineStart, dur: dur,+ offset: offset, effects: e)+ timelineStart += durproc initLinearTimeline*(src: ptr string, tb: AVRational, bg: RGBColor,mi: MediaInfo, effects: seq[Actions], actionIndex: seq[int]): v3 =@@ -377,14 +375,14 @@ proc mapMarkers*(tl: var v3, markers: openArray[SourceMarker]) =# nothing is kept from there on. `moved` tells which.proc place(u: int64, moved: var bool): int64 =for k, sp in spans:- if u >= sp.hi: continue- if sp.kept and u >= sp.lo:- let f = sp.clip.clipFrameAt(sp.map, float64(u - sp.inputStart))- return clamp(f, sp.clip.start, sp.clip.start + sp.clip.dur - 1)- moved = true- for later in spans.toOpenArray(k, spans.high):- if later.kept: return later.clip.start- return -1+ if u < sp.hi:+ if sp.kept and u >= sp.lo:+ let f = sp.clip.clipFrameAt(sp.map, float64(u - sp.inputStart))+ return clamp(f, sp.clip.start, sp.clip.start + sp.clip.dur - 1)+ moved = true+ for later in spans.toOpenArray(k, spans.high):+ if later.kept: return later.clip.start+ return -1moved = true-1@@ -397,17 +395,17 @@ proc mapMarkers*(tl: var v3, markers: openArray[SourceMarker]) =let at = place(start, moved)if at < 0:inc leftOut- continue- if moved: inc movedCount- var dur = 0'i64- if stop > start:- # Its end point, the frame after it: in a cut, that's the cut's place- # on the timeline; past every kept frame, the timeline's end.- var endMoved = false- let endAt = place(stop, endMoved)- dur = (if endAt >= 0: endAt else: timelineStart) - at- tl.markers.add Marker(start: at, dur: max(0'i64, dur), name: m.name,- note: m.note, color: m.color)+ else:+ if moved: inc movedCount+ var dur = 0'i64+ if stop > start:+ # Its end point, the frame after it: in a cut, that's the cut's place+ # on the timeline; past every kept frame, the timeline's end.+ var endMoved = false+ let endAt = place(stop, endMoved)+ dur = (if endAt >= 0: endAt else: timelineStart) - at+ tl.markers.add Marker(start: at, dur: max(0'i64, dur), name: m.name,+ note: m.note, color: m.color)if movedCount > 0:warning &"{movedCount} marker(s) in cut-out sections moved to the next kept frame"if leftOut > 0:@@ -420,21 +418,18 @@ proc initNonLinear(src: ptr string, tb: AVRational, mi: MediaInfo,for clip2 in clips2:let effectGroup = effects[clip2.effect]- if effectGroup.isCut:- continue- var speed = 1.0- for effect in effectGroup:- if effect.kind == actSpeed:- speed *= effect.val-- let (offset, dur) = clipBounds(clip2.start, clip2.`end`, speed)- if dur == 0:- continue+ if not effectGroup.isCut:+ var speed = 1.0+ for effect in effectGroup:+ if effect.kind == actSpeed:+ speed *= effect.val- clips.add(Clip(src: src, start: start, dur: dur, offset: offset,- effects: clip2.effect))+ let (offset, dur) = clipBounds(clip2.start, clip2.`end`, speed)+ if dur != 0:+ clips.add(Clip(src: src, start: start, dur: dur, offset: offset,+ effects: clip2.effect))- start += dur+ start += durresult = v3(tb: tb, effects: effects, clips2: clips2, templateFile: src)result.res = mi.getRes()@@ -474,19 +469,17 @@ proc toNonLinear*(src: ptr string, tb: AVRational, mi: MediaInfo,# Check the float32 that gets stored: a tiny float64 underflows to 0.if chunk[2].float32 > 0.0 and chunk[2].float32 < 99999.0:let (offset, dur) = clipBounds(chunk[0], chunk[1], chunk[2])- if dur == 0:- continue-- let action =- if chunk[2] == 1.0:- aNil- else:- try: newActions([Action(kind: actSpeed, val: chunk[2].float32)])- except ActionParseError: error "Too many actions"- let e = effectIndex.intern(effects, action)- clips.add Clip(src: src, start: start, dur: dur, offset: offset, effects: e)- clips2.add Clip2(start: chunk[0], `end`: chunk[1], effect: e)- start += dur+ if dur != 0:+ let action =+ if chunk[2] == 1.0:+ aNil+ else:+ try: newActions([Action(kind: actSpeed, val: chunk[2].float32)])+ except ActionParseError: error "Too many actions"+ let e = effectIndex.intern(effects, action)+ clips.add Clip(src: src, start: start, dur: dur, offset: offset, effects: e)+ clips2.add Clip2(start: chunk[0], `end`: chunk[1], effect: e)+ start += durresult = v3(tb: tb, effects: effects, clips2: clips2, templateFile: src)result.res = mi.getRes()@@ -567,23 +560,22 @@ proc addTransitions*(tl: var v3, kind: TransitionKind, requested: int64,for i in 0 ..< clips.len - 1:let left = clips[i]let right = clips[i + 1]- if left.start + left.dur != right.start: continue- let leftSpeed = speeds[i]- let rightSpeed = speeds[i + 1]- let leftSourceEnd = int64(round((left.offset + left.dur).float64 * leftSpeed))- let rightSourceStart = int64(round(right.offset.float64 * rightSpeed))- let cutDur = max(0'i64, rightSourceStart - leftSourceEnd)- if left.src == right.src and cutDur < minCut:- continue- var half = min(requested div 2, min(left.dur, right.dur))- # Incoming preroll is explicit in offset. For cuts within one source, the- # removed source interval also bounds the outgoing postroll.- half = min(half, int64(rightSourceStart.float64 / rightSpeed))- if left.src != nil and right.src == left.src:- half = min(half, int64(cutDur.float64 / max(leftSpeed, rightSpeed)))- if half > 0:- centers.add Transition(kind: kind, at: right.start,- dur: half * 2, alignment: taCenter)+ if left.start + left.dur == right.start:+ let leftSpeed = speeds[i]+ let rightSpeed = speeds[i + 1]+ let leftSourceEnd = int64(round((left.offset + left.dur).float64 * leftSpeed))+ let rightSourceStart = int64(round(right.offset.float64 * rightSpeed))+ let cutDur = max(0'i64, rightSourceStart - leftSourceEnd)+ if not (left.src == right.src and cutDur < minCut):+ var half = min(requested div 2, min(left.dur, right.dur))+ # Incoming preroll is explicit in offset. For cuts within one source, the+ # removed source interval also bounds the outgoing postroll.+ half = min(half, int64(rightSourceStart.float64 / rightSpeed))+ if left.src != nil and right.src == left.src:+ half = min(half, int64(cutDur.float64 / max(leftSpeed, rightSpeed)))+ if half > 0:+ centers.add Transition(kind: kind, at: right.start,+ dur: half * 2, alignment: taCenter)var firstDur = min(requested, clips[0].dur)if centers.len > 0:@@ -689,31 +681,30 @@ proc placeTransitions*(tl: var v3, placed: seq[PlacedTransition]) =of taStart: c.startof taEnd: c.start + c.durof taCenter: c.start- if align == taCenter and (i == 0 or- clips[i - 1].start + clips[i - 1].dur != c.start):- continue- if abs(edge - p.at) < bestDist:- bestDist = abs(edge - p.at)- best = i- if best < 0: continue- let c = clips[best]- let fits = p.kind in (if video: videoKinds else: audioKinds)- var t = Transition(kind: (if fits: p.kind else: tkDissolve),- alignment: align, dur: p.dur, easeIn: p.easeIn, easeOut: p.easeOut)- case align- of taStart:- t.at = c.start- t.dur = min(t.dur, c.dur)- of taEnd:- t.at = c.start + c.dur- t.dur = min(t.dur, c.dur)- of taCenter:- t.at = c.start- let room = 2 * min(c.dur, clips[best - 1].dur)- t.dur = min(t.dur, room) div 2 * 2- if t.dur <= 0 or t.spanStart < priorEnd: continue- priorEnd = t.spanStart + t.dur- result.add t+ if not (align == taCenter and (i == 0 or+ clips[i - 1].start + clips[i - 1].dur != c.start)):+ if abs(edge - p.at) < bestDist:+ bestDist = abs(edge - p.at)+ best = i+ if best >= 0:+ let c = clips[best]+ let fits = p.kind in (if video: videoKinds else: audioKinds)+ var t = Transition(kind: (if fits: p.kind else: tkDissolve),+ alignment: align, dur: p.dur, easeIn: p.easeIn, easeOut: p.easeOut)+ case align+ of taStart:+ t.at = c.start+ t.dur = min(t.dur, c.dur)+ of taEnd:+ t.at = c.start + c.dur+ t.dur = min(t.dur, c.dur)+ of taCenter:+ t.at = c.start+ let room = 2 * min(c.dur, clips[best - 1].dur)+ t.dur = min(t.dur, room) div 2 * 2+ if not (t.dur <= 0 or t.spanStart < priorEnd):+ priorEnd = t.spanStart + t.dur+ result.add ttl.vt = newSeq[seq[Transition]](tl.v.len)if tl.v.len > 0: tl.vt[0] = place(tl.v[0], true)diff --git a/src/transcribe.nim b/src/transcribe.nimindex 538d20bb..2799d454 100644--- a/src/transcribe.nim+++ b/src/transcribe.nim@@ -494,16 +494,16 @@ proc run*(readPacket: PacketSource, audioStream: ptr AVStream,let ret = readPacket(pkt)if ret == AVERROR_EAGAIN:sleep(5)- continue- if ret < 0:- if ret != AVERROR_EOF:- warning &"Stopped reading audio: {av_err2str(ret)}"- break- if pkt.stream_index == audioStream.index and avcodec_send_packet(dec, pkt) >= 0:- while avcodec_receive_frame(dec, frame) >= 0:- feed(frame)- av_frame_unref(frame)- av_packet_unref(pkt)+ else:+ if ret < 0:+ if ret != AVERROR_EOF:+ warning &"Stopped reading audio: {av_err2str(ret)}"+ break+ if pkt.stream_index == audioStream.index and avcodec_send_packet(dec, pkt) >= 0:+ while avcodec_receive_frame(dec, frame) >= 0:+ feed(frame)+ av_frame_unref(frame)+ av_packet_unref(pkt)# Flush the decoder first: delay codecs (AAC/MP3) still hold the last frames,# which carry the end of the final utterance.diff --git a/src/util/bar.nim b/src/util/bar.nimindex c8d6f575..1ecd3b80 100644--- a/src/util/bar.nim+++ b/src/util/bar.nim@@ -111,40 +111,38 @@ proc progressWorker(data: ThreadData) {.thread.} =if data.paused.load():data.sleeping.store(true)sleep(sleepRate)- continue-- data.sleeping.store(false)-- when not defined(windows) and not defined(emscripten):- if termResized.load():- columns = terminalWidth()- termResized.store(false)- elif defined(windows):- inc widthCounter- if widthCounter >= widthRefreshRate:- columns = terminalWidth()- widthCounter = 0-- let currentProgress = data.progress.load()- if currentProgress == lastProgress:- data.sleeping.store(true)- sleep(sleepRate)- continue-- let total = data.total.load()- let progress = if total == 0: 0.0 else: min(1.0, max(0.0, currentProgress / total))- let rate = if progress == 0: 0.0 else: (epochTime() - data.begin) / progress-- let output = formatProgressOutput(config, data.title, data.lenTitle, columns,- progress, rate, data.begin, currentProgress, total)- when defined(emscripten):- wasmProgressWrite(output.cstring)else:- stderr.write(output & "\r")- stderr.flushFile()-- lastProgress = currentProgress- sleep(sleepRate)+ data.sleeping.store(false)++ when not defined(windows) and not defined(emscripten):+ if termResized.load():+ columns = terminalWidth()+ termResized.store(false)+ elif defined(windows):+ inc widthCounter+ if widthCounter >= widthRefreshRate:+ columns = terminalWidth()+ widthCounter = 0++ let currentProgress = data.progress.load()+ if currentProgress == lastProgress:+ data.sleeping.store(true)+ sleep(sleepRate)+ else:+ let total = data.total.load()+ let progress = if total == 0: 0.0 else: min(1.0, max(0.0, currentProgress / total))+ let rate = if progress == 0: 0.0 else: (epochTime() - data.begin) / progress++ let output = formatProgressOutput(config, data.title, data.lenTitle, columns,+ progress, rate, data.begin, currentProgress, total)+ when defined(emscripten):+ wasmProgressWrite(output.cstring)+ else:+ stderr.write(output & "\r")+ stderr.flushFile()++ lastProgress = currentProgress+ sleep(sleepRate)varprogressHook* {.threadvar.}: ProgressHookdiff --git a/src/util/fun.nim b/src/util/fun.nimindex 43828199..b1a1ee31 100644--- a/src/util/fun.nim+++ b/src/util/fun.nim@@ -37,37 +37,36 @@ func wrapText*(text: string, width, indent: int): string =for line in text.split("\n"):if line.len == 0:outLines.add("")- continue-- # Detect leading whitespace- var leadingSpaces = 0- for c in line:- if c == ' ':- leadingSpaces += 1- else:- break- let lineIndent = " ".repeat(leadingSpaces)- let content = line[leadingSpaces .. ^1]-- var currentLine = ""- for word in content.splitWhitespace():- if currentLine.len == 0:- currentLine = word- elif leadingSpaces + visibleLen(currentLine) + 1 + visibleLen(word) <= width:- currentLine &= " " & word- else:+ else:+ # Detect leading whitespace+ var leadingSpaces = 0+ for c in line:+ if c == ' ':+ leadingSpaces += 1+ else:+ break+ let lineIndent = " ".repeat(leadingSpaces)+ let content = line[leadingSpaces .. ^1]++ var currentLine = ""+ for word in content.splitWhitespace():+ if currentLine.len == 0:+ currentLine = word+ elif leadingSpaces + visibleLen(currentLine) + 1 + visibleLen(word) <= width:+ currentLine &= " " & word+ else:+ if isFirst:+ outLines.add(lineIndent & currentLine)+ isFirst = false+ else:+ outLines.add(indentStr & lineIndent & currentLine)+ currentLine = word+ if currentLine.len > 0:if isFirst:outLines.add(lineIndent & currentLine)isFirst = falseelse:outLines.add(indentStr & lineIndent & currentLine)- currentLine = word- if currentLine.len > 0:- if isFirst:- outLines.add(lineIndent & currentLine)- isFirst = false- else:- outLines.add(indentStr & lineIndent & currentLine)result = outLines.join("\n")