今日已更新 344 条资讯 | 累计 37249 条内容
关于我们

Frame-accurate FFmpeg trimming without re-encoding the whole file

Mason K 2026年08月27日 17:24 1 次阅读 来源:Dev.to

TL;DR -c copy can only cut on keyframes, so your 12.4s trim starts wherever the last keyframe was. We'll build a smart-trim script that probes keyframe positions with ffprobe , re-encodes only the head and tail fragments, stream copies everything between them, and concatenates the three. Frame accurate output, encoding cost proportional to two GOPs instead of the whole file. Tested with FFmpeg 9.0 "Lei" (released 2026-08-04) and Node 22.x. The JS is ESM, so put "type": "module" in your package.json before running any of it. Everything here also works on FFmpeg 7.x and 8.x; nothing we use is new. The problem, in two commands 🎬 # fast, and wrong ffmpeg -ss 12.4 -i input.mp4 -t 20 -c copy fast.mp4 ffprobe -v error -show_entries format = start_time,duration -of default = nw = 1 fast.mp4 # start_time=0.000000 # duration=20.388000 <- we asked for 20, starting at 12.4 The clip is long by the distance from our requested start back to the previous keyframe, and every frame in it is shifted earlier than the user asked for. Stream copy moves compressed packets without decoding them. Most frames in a compressed stream only describe the difference from their neighbors, so the only place you can start is a keyframe. FFmpeg snaps back to the nearest preceding one, and your clip starts early. # accurate, and slow on a long source ffmpeg -ss 12.4 -i input.mp4 -t 20 -c :v libx264 -crf 20 -c :a aac slow.mp4 We want the accuracy of the second and roughly the cost of the first. 1. Look at your keyframes first Before writing any code, find out how bad the problem is for your content: ffprobe -v error -select_streams v:0 \ -show_entries packet = pts_time,flags \ -of csv = print_section = 0 input.mp4 | grep 'K' | head -20 0.000000,K__ 2.002000,K__ 4.004000,K__ 6.006000,K__ Two second GOPs here, so worst-case error is about two seconds. Screen recorders and some camera output emit keyframes on scene change only, and there the gaps can be 30 seconds or more. That distribution is the real spe

本文内容来源于互联网,版权归原作者所有
查看原文