@auscera/cleoedits 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (230) hide show
  1. package/README.md +62 -2
  2. package/cli.mjs +149 -0
  3. package/lib/dependencies.mjs +384 -0
  4. package/lib/run.mjs +114 -0
  5. package/lib/workspace.mjs +167 -0
  6. package/package.json +240 -3
  7. package/workspace/.agents/skills/cleoedits/SKILL.md +29 -0
  8. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/audiogram.json +41 -0
  9. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/facebook.json +48 -0
  10. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/linkedin.json +48 -0
  11. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/podcast.json +23 -0
  12. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/reels.json +48 -0
  13. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/shorts.json +48 -0
  14. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/tiktok.json +48 -0
  15. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/x.json +48 -0
  16. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/youtube-shorts.json +48 -0
  17. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/youtube.json +48 -0
  18. package/workspace/.agents/skills/cleoedits/assets/reel_effects/assets/LICENSE-SimpleIcons +30 -0
  19. package/workspace/.agents/skills/cleoedits/assets/reel_effects/assets/logos.json +1 -0
  20. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Anton-Regular.ttf +0 -0
  21. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/ArchivoBlack-Regular.ttf +0 -0
  22. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/InstrumentSerif-Italic.ttf +0 -0
  23. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Inter.ttf +0 -0
  24. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/LICENSE-PermanentMarker.txt +202 -0
  25. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Montserrat.ttf +0 -0
  26. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Anton.txt +93 -0
  27. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-ArchivoBlack.txt +93 -0
  28. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-InstrumentSerif.txt +93 -0
  29. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Inter.txt +93 -0
  30. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Montserrat.txt +93 -0
  31. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-PlayfairDisplay.txt +93 -0
  32. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Poppins.txt +93 -0
  33. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-SpaceMono.txt +93 -0
  34. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/PermanentMarker-Regular.ttf +0 -0
  35. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/PlayfairDisplay-Italic.ttf +0 -0
  36. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/PlayfairDisplay.ttf +0 -0
  37. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Poppins-Black.ttf +0 -0
  38. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Poppins-Bold.ttf +0 -0
  39. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Poppins-ExtraBold.ttf +0 -0
  40. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/SpaceMono-Bold.ttf +0 -0
  41. package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/LICENSE-MediaPipe +218 -0
  42. package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/LICENSE-YuNet +21 -0
  43. package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/NOTICE.md +4 -0
  44. package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/selfie_segmenter.tflite +0 -0
  45. package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/yunet.onnx +0 -0
  46. package/workspace/.agents/skills/cleoedits/assets/video_styles/LICENSE +21 -0
  47. package/workspace/.agents/skills/cleoedits/assets/video_styles/audio-app-ui/STYLE.md +65 -0
  48. package/workspace/.agents/skills/cleoedits/assets/video_styles/blueprint/STYLE.md +53 -0
  49. package/workspace/.agents/skills/cleoedits/assets/video_styles/blueprint/index.html +328 -0
  50. package/workspace/.agents/skills/cleoedits/assets/video_styles/blueprint/studio.js +57 -0
  51. package/workspace/.agents/skills/cleoedits/assets/video_styles/data-story/STYLE.md +65 -0
  52. package/workspace/.agents/skills/cleoedits/assets/video_styles/data-story/index.html +575 -0
  53. package/workspace/.agents/skills/cleoedits/assets/video_styles/design-app-ui/STYLE.md +68 -0
  54. package/workspace/.agents/skills/cleoedits/assets/video_styles/editor-ui/STYLE.md +73 -0
  55. package/workspace/.agents/skills/cleoedits/assets/video_styles/editorial-paper/STYLE.md +54 -0
  56. package/workspace/.agents/skills/cleoedits/assets/video_styles/editorial-paper/index.html +189 -0
  57. package/workspace/.agents/skills/cleoedits/assets/video_styles/editorial-paper/studio.js +57 -0
  58. package/workspace/.agents/skills/cleoedits/assets/video_styles/explainer-diagram/STYLE.md +64 -0
  59. package/workspace/.agents/skills/cleoedits/assets/video_styles/explainer-diagram/index.html +620 -0
  60. package/workspace/.agents/skills/cleoedits/assets/video_styles/graphite-ui/STYLE.md +55 -0
  61. package/workspace/.agents/skills/cleoedits/assets/video_styles/graphite-ui/index.html +238 -0
  62. package/workspace/.agents/skills/cleoedits/assets/video_styles/graphite-ui/studio.js +57 -0
  63. package/workspace/.agents/skills/cleoedits/assets/video_styles/growing-city/STYLE.md +66 -0
  64. package/workspace/.agents/skills/cleoedits/assets/video_styles/growing-city/index.html +602 -0
  65. package/workspace/.agents/skills/cleoedits/assets/video_styles/ink-line/STYLE.md +66 -0
  66. package/workspace/.agents/skills/cleoedits/assets/video_styles/ink-line/index.html +777 -0
  67. package/workspace/.agents/skills/cleoedits/assets/video_styles/midnight-grid/STYLE.md +56 -0
  68. package/workspace/.agents/skills/cleoedits/assets/video_styles/midnight-grid/index.html +186 -0
  69. package/workspace/.agents/skills/cleoedits/assets/video_styles/midnight-grid/studio.js +57 -0
  70. package/workspace/.agents/skills/cleoedits/assets/video_styles/motion-app-ui/STYLE.md +68 -0
  71. package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-cut/STYLE.md +56 -0
  72. package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-cut/index.html +244 -0
  73. package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-cut/studio.js +57 -0
  74. package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-world/STYLE.md +67 -0
  75. package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-world/index.html +663 -0
  76. package/workspace/.agents/skills/cleoedits/assets/video_styles/particle-field/STYLE.md +59 -0
  77. package/workspace/.agents/skills/cleoedits/assets/video_styles/particle-field/index.html +395 -0
  78. package/workspace/.agents/skills/cleoedits/assets/video_styles/poster-pop/STYLE.md +52 -0
  79. package/workspace/.agents/skills/cleoedits/assets/video_styles/poster-pop/index.html +194 -0
  80. package/workspace/.agents/skills/cleoedits/assets/video_styles/poster-pop/studio.js +57 -0
  81. package/workspace/.agents/skills/cleoedits/assets/video_styles/risograph/STYLE.md +58 -0
  82. package/workspace/.agents/skills/cleoedits/assets/video_styles/risograph/index.html +242 -0
  83. package/workspace/.agents/skills/cleoedits/assets/video_styles/risograph/studio.js +57 -0
  84. package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-grid/STYLE.md +53 -0
  85. package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-grid/index.html +138 -0
  86. package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-grid/studio.js +57 -0
  87. package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-kinetic/STYLE.md +63 -0
  88. package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-kinetic/index.html +599 -0
  89. package/workspace/.agents/skills/cleoedits/assets/video_styles/time-travel/STYLE.md +65 -0
  90. package/workspace/.agents/skills/cleoedits/assets/video_styles/time-travel/index.html +1297 -0
  91. package/workspace/.agents/skills/cleoedits/assets/video_styles/weather-widget/STYLE.md +69 -0
  92. package/workspace/.agents/skills/cleoedits/assets/video_styles/weather-widget/index.html +674 -0
  93. package/workspace/.agents/skills/cleoedits/references/audio-clearervoice-elevenlabs.md +11 -0
  94. package/workspace/.agents/skills/cleoedits/references/ffmpeg-and-reels.md +15 -0
  95. package/workspace/.agents/skills/cleoedits/references/hyperframes-workflows.md +13 -0
  96. package/workspace/.agents/skills/cleoedits/references/kdenlive-cli-and-mcp.md +12 -0
  97. package/workspace/.agents/skills/cleoedits/references/motion-design-pipeline.md +7 -0
  98. package/workspace/.agents/skills/cleoedits/references/motion-taste-emil.md +5 -0
  99. package/workspace/.agents/skills/cleoedits/references/playwright-demo-capture.md +9 -0
  100. package/workspace/.agents/skills/cleoedits/references/remotion-workflows.md +13 -0
  101. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/LICENSE +21 -0
  102. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_ass_overlay.py +399 -0
  103. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/__init__.py +235 -0
  104. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/alpha.py +560 -0
  105. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/asr.py +1237 -0
  106. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/color.py +540 -0
  107. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/decision.py +2452 -0
  108. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/drawtext.py +290 -0
  109. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/emit.py +1309 -0
  110. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/emoji.py +518 -0
  111. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/fonts.py +875 -0
  112. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/pacing.py +263 -0
  113. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/pacing_edit.py +432 -0
  114. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/probe.py +1613 -0
  115. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/runner.py +3994 -0
  116. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/text.py +73 -0
  117. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/timeline.py +721 -0
  118. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/wrap.py +981 -0
  119. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_contract.py +2454 -0
  120. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_platforms.py +258 -0
  121. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_review.html +754 -0
  122. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_review.py +258 -0
  123. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_smartcut.py +450 -0
  124. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/audio.py +867 -0
  125. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/background.py +136 -0
  126. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/batch.py +1409 -0
  127. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/broll.py +282 -0
  128. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/caption.py +2207 -0
  129. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/check.py +815 -0
  130. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/color.py +695 -0
  131. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/crop.py +91 -0
  132. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/cropdetect.py +214 -0
  133. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/cut.py +2076 -0
  134. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/deinterlace.py +90 -0
  135. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/denoise.py +94 -0
  136. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/export.py +1033 -0
  137. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/fit.py +729 -0
  138. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/freeze.py +197 -0
  139. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/graphics.py +920 -0
  140. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/grid.py +235 -0
  141. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/insert.py +142 -0
  142. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/join.py +1083 -0
  143. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/look.py +475 -0
  144. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/loop.py +395 -0
  145. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/loudness.py +397 -0
  146. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/metadata.py +416 -0
  147. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/multicam.py +414 -0
  148. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/overlay.py +766 -0
  149. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/pad.py +121 -0
  150. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/probe.py +145 -0
  151. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/proxy.py +93 -0
  152. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/redact.py +162 -0
  153. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/render.py +2424 -0
  154. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/report.py +354 -0
  155. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/reverse.py +114 -0
  156. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/scenes.py +439 -0
  157. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/sequence.py +285 -0
  158. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/silence.py +945 -0
  159. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/speedramp.py +193 -0
  160. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/sphere.py +137 -0
  161. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/stabilize.py +141 -0
  162. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/straighten.py +120 -0
  163. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/sync.py +500 -0
  164. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/verify.py +411 -0
  165. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/waveform.py +502 -0
  166. package/workspace/.agents/skills/cleoedits/scripts/kdenlive_builder.py +284 -0
  167. package/workspace/.agents/skills/cleoedits/scripts/motion/LICENSE-claude-motion +21 -0
  168. package/workspace/.agents/skills/cleoedits/scripts/motion/LICENSE-motion-design +21 -0
  169. package/workspace/.agents/skills/cleoedits/scripts/motion/_media.py +43 -0
  170. package/workspace/.agents/skills/cleoedits/scripts/motion/pacing_check.py +90 -0
  171. package/workspace/.agents/skills/cleoedits/scripts/motion/storyboard.py +77 -0
  172. package/workspace/.agents/skills/cleoedits/scripts/reel_effects/LICENSE +26 -0
  173. package/workspace/.agents/skills/cleoedits/scripts/reel_effects/fx.py +2717 -0
  174. package/workspace/.agents/skills/cleoedits/scripts/reel_effects/logos.py +194 -0
  175. package/workspace/.agents/skills/cleoedits/scripts/reel_effects/sfx.py +105 -0
  176. package/workspace/.agents/skills/cleoedits/scripts/reel_effects/trim.py +99 -0
  177. package/workspace/.agents/skills/cleoedits/scripts/reel_effects/words.py +60 -0
  178. package/workspace/.claude/commands/blender-3d.md +12 -0
  179. package/workspace/.claude/commands/business-short-form-reels.md +12 -0
  180. package/workspace/.claude/commands/color-grade.md +12 -0
  181. package/workspace/.claude/commands/cutout-grid-reel.md +12 -0
  182. package/workspace/.claude/commands/depth-ui-reel.md +12 -0
  183. package/workspace/.claude/commands/explainer-panel-reel.md +12 -0
  184. package/workspace/.claude/commands/freeze-frame.md +12 -0
  185. package/workspace/.claude/commands/glass-graph.md +12 -0
  186. package/workspace/.claude/commands/over-the-shoulder.md +12 -0
  187. package/workspace/.claude/commands/personal-short-form-reels.md +12 -0
  188. package/workspace/.claude/commands/ranking-format.md +12 -0
  189. package/workspace/.claude/commands/relight.md +12 -0
  190. package/workspace/.claude/commands/reverse-engineer.md +12 -0
  191. package/workspace/.claude/commands/text-behind.md +12 -0
  192. package/workspace/.claude/commands/tier-list.md +12 -0
  193. package/workspace/.claude-plugin/plugin.json +8 -0
  194. package/workspace/.npmignore +15 -0
  195. package/workspace/AGENTS.md +30 -0
  196. package/workspace/README.md +63 -0
  197. package/workspace/assets/fonts/TikTokSans-OFL.txt +93 -0
  198. package/workspace/assets/fonts/TikTokSans-Variable.ttf +0 -0
  199. package/workspace/assets/luts/clean_warm.cube +4917 -0
  200. package/workspace/assets/luts/golden_hour.cube +4917 -0
  201. package/workspace/assets/luts/moody_dark.cube +4917 -0
  202. package/workspace/assets/luts/teal_orange.cube +4917 -0
  203. package/workspace/assets/sfx/NOTICE.txt +1 -0
  204. package/workspace/assets/sfx/click.wav +0 -0
  205. package/workspace/assets/sfx/pop.wav +0 -0
  206. package/workspace/assets/sfx/riser.wav +0 -0
  207. package/workspace/assets/sfx/whoosh.wav +0 -0
  208. package/workspace/generators/hyperframes/index.html +39 -0
  209. package/workspace/generators/hyperframes/package.json +15 -0
  210. package/workspace/generators/hyperframes/pnpm-lock.yaml +1181 -0
  211. package/workspace/generators/hyperframes/pnpm-workspace.yaml +10 -0
  212. package/workspace/generators/remotion/eslint.config.mjs +3 -0
  213. package/workspace/generators/remotion/package.json +36 -0
  214. package/workspace/generators/remotion/pnpm-lock.yaml +4179 -0
  215. package/workspace/generators/remotion/pnpm-workspace.yaml +10 -0
  216. package/workspace/generators/remotion/remotion.config.ts +13 -0
  217. package/workspace/generators/remotion/src/Root.tsx +52 -0
  218. package/workspace/generators/remotion/src/index.css +1 -0
  219. package/workspace/generators/remotion/src/index.ts +4 -0
  220. package/workspace/generators/remotion/tsconfig.json +15 -0
  221. package/workspace/pipeline/scripts/_codec.py +28 -0
  222. package/workspace/pipeline/scripts/ai_media_api.py +109 -0
  223. package/workspace/pipeline/scripts/blender_render.py +166 -0
  224. package/workspace/pipeline/scripts/composite.py +49 -0
  225. package/workspace/pipeline/scripts/melt.sh +68 -0
  226. package/workspace/pipeline/scripts/normalize_audio.py +39 -0
  227. package/workspace/pipeline/scripts/person_matte.py +216 -0
  228. package/workspace/pipeline/scripts/record_demo.py +69 -0
  229. package/workspace/pipeline/scripts/whisper_cut.py +98 -0
  230. package/workspace-manifest.json +908 -0
@@ -0,0 +1,2076 @@
1
+ #!/usr/bin/env python3
2
+ """Cut a clip or several segments out of a video and (optionally) join them.
3
+
4
+ Lossless stream copy (-c copy) is preferred. Cuts snap to keyframes in that
5
+ mode, so if frame accuracy matters pass --accurate to re-encode. Multiple
6
+ segments are cut individually and joined by stream copy when the parts match in their codec
7
+ parameters; otherwise every segment is re-cut from the source into one re-encode.
8
+
9
+ Audio: a stream copy lands on a packet boundary (about 21 ms for AAC, one
10
+ demuxer block for WAV); --accurate decodes and trims to the sample. The output
11
+ extension picks the codec: -o out.wav writes PCM (never an AAC packet inside a
12
+ WAV), -o out.m4a writes AAC; an audio extension on a video input drops the
13
+ picture (mp4 -> wav extraction). The result reports `precision`
14
+ (packet / sample / codec_frame / frame) and the measured duration error, plus
15
+ `mode` (copy / accurate / hybrid -- "hybrid" means a lossless cut silently
16
+ re-encoded because the keyframe snap exceeded --tolerance), `keyframe_snapped` and
17
+ `start_snapped` (measured: a copied start moved past a frame; equal since 3.0.0),
18
+ `reencode_reason`, `requested_start`/`requested_end` (or `requested_segments` for --segments),
19
+ `requested_duration`, `output_duration` and `duration_delta_seconds` -- so a
20
+ caller never has to trust "it probably cut where I asked" on faith.
21
+
22
+ A single-segment .mp4/.mov copy keeps the MP4 edit list (the default since 3.0.0),
23
+ which hides the keyframe's pre-roll so the picture starts at --start; --no-edit-list
24
+ shifts its timestamps to zero instead (-avoid_negative_ts make_zero, every 2.x
25
+ release's default), so the picture starts at the keyframe.
26
+ An --accurate re-encode of a video does not: make_zero moved the picture by the
27
+ AAC priming (about 21 ms, and further when a B-frame's decode time is negative)
28
+ while the sound stayed at 0. A start that lands on a frame keeps that frame at 0.
29
+ A start between frames begins on the next frame and may keep up to one frame of
30
+ timestamp. The MP4 edit list hides the encoder priming, and a source whose audio
31
+ starts late keeps that offset.
32
+
33
+ A re-encode keeps an SDR HEVC source HEVC (x265 8-bit BT.709, or VideoToolbox under --hw;
34
+ the default since 3.0.0), so a trimmed phone clip keeps its codec; --no-keep-hevc uses x264
35
+ as every 2.x release did. Other SDR sources get x264 and an HDR or BT.2020 one x265 Main10,
36
+ as every editing tool does. --codec overrides all of these.
37
+
38
+ The VFR guard samples a video's packet timing (`vfr_check`) and re-encodes, as --accurate,
39
+ only when it is variable or too short to judge (--vfr-guard sampled, the default since
40
+ 3.0.0). --vfr-guard average is every 2.x release's: a source whose nominal and average frame
41
+ rates differ is taken for variable-frame-rate and re-encoded. --vfr-guard off keeps the copy
42
+ with a note.
43
+
44
+ Examples:
45
+ python3 cut.py input.mp4 --start 00:00:10 --end 00:00:25
46
+ python3 cut.py input.mp4 --segments 0:05-0:12,1:00-1:20 -o highlights.mp4
47
+ python3 cut.py input.mp4 --start 3.5 --duration 10 --accurate
48
+ python3 cut.py talk.wav --start 1.2345 --end 2.3456 --accurate -o part.wav # sample-exact
49
+ python3 cut.py talk.mp4 --start 1:00 --end 2:00 -o part.wav # audio extraction
50
+ """
51
+ import argparse
52
+ import contextlib
53
+ import json
54
+ import math
55
+ import os
56
+ import sys
57
+ import tempfile
58
+ import zlib
59
+ from typing import List, Optional, Tuple
60
+
61
+ from _common.runner import ffmpeg_failure_extra, JsonTooDeep, fail_if_classified, read_json
62
+ from _common import (beat_grid, snap_points, decode_pcm_mono, rms_envelope, BEAT_MIN_CONFIDENCE)
63
+ from _common import require_tool
64
+ from _common.probe import PROBED_AUDIO, PROBED_VIDEO, TS_EXTS, probed_maps, several_av_streams, signatures_match, stream_signature
65
+ from _common.runner import subtitle_codec_for, subtitle_container_holds, declare_time_map, segments_map, with_mapped_chapters
66
+ from _common.decision import PAD_SOUND_FROM_ZERO, SEEK_MARGIN, delivered_rate, frame_rate, grid_at_or_after, stream_starts, on_frame as decision_on_frame
67
+ from _common.timeline import output_timecode_args
68
+ from _common.emit import refuse_still
69
+ from _common.decision import UNWRITTEN_AUDIO_EXT
70
+ from _common import refuse_unwritten_output
71
+ from _common import warn, record_fallback, refuse_existing_outputs, sibling_temp, source_codec_video_args, STATE, add_common, apply_common, audio_codec_for, emit, aac_args, cfr_args, cfr_filter, graph_with_cfr, default_output, die, ffmpeg_base, info, is_audio_output, time_arg, probe, run, X264_PRESETS, keyframes_near, concat_list_line, place_output, refuse_output_is_input, fmt_secs, measure_frame_timing, dry_run_input_pending
72
+
73
+ # outputs whose re-encode dropped a subtitle/data stream (reported as dropped_non_av_streams)
74
+ DROPPED_STREAMS: List[str] = []
75
+ # keyframe timestamps found next to a requested cut that the tolerance turned into a re-encode
76
+ # (reported so the caller can choose a lossless cut at one of them next time)
77
+ NEAREST_KEYFRAMES: list = []
78
+ # --keep-hevc: an SDR HEVC source re-encodes as HEVC instead of H.264 (set by main())
79
+ KEEP_HEVC = False
80
+
81
+
82
+ def _t(value: str, fps, flag: str = "--segments") -> float:
83
+ """time_arg() with the input's fps (SMPTE hh:mm:ss:ff, or @fps): the one parser every tool uses (1.9)."""
84
+ return time_arg(value, flag, fps)
85
+
86
+
87
+ def keep_ranges_after_removing(removed: List[Tuple[float, float]], total: float, fps=None,
88
+ picture: Optional[Tuple[float, float]] = None,
89
+ dropped: Optional[List[Tuple[float, float]]] = None) -> List[Tuple[float, float]]:
90
+ """--remove: what is left of [0, total] once `removed` is dropped (merged where they overlap,
91
+ clamped to the file). A leftover shorter than one frame (10 ms without a frame rate) is not a
92
+ piece anyone asked to keep. With `picture` (where the video starts and ends, for a video
93
+ output), neither is a leftover that holds less than one frame of it: sound before the first
94
+ frame or after the last (a track that outlasts its picture) has no picture to cut, and was
95
+ kept and then refused as a segment the caller never gave (#462 A51). Such leftovers are added
96
+ to `dropped`. Refuses a removal that would leave nothing."""
97
+ least = 1.0 / fps if fps else 0.01
98
+ keep, cursor = [], 0.0
99
+
100
+ def add(a: float, b: float) -> None:
101
+ if b - a < least:
102
+ return
103
+ if picture is not None and min(b, picture[1]) - max(a, picture[0]) < least - 1e-6:
104
+ if dropped is not None:
105
+ dropped.append((a, b))
106
+ return
107
+ keep.append((a, b))
108
+ outside = [(s, e) for s, e in removed if min(total, e) <= min(total, max(0.0, s))]
109
+ if outside:
110
+ die("--remove " + ", ".join(f"{s:g}-{e:g}" for s, e in outside) + f" lies outside the file (0-{total:.3f}s), "
111
+ "so it removes nothing; check the units (seconds, mm:ss)")
112
+ for s, e in sorted((min(total, max(0.0, s)), min(total, e)) for s, e in removed):
113
+ if e <= cursor:
114
+ continue
115
+ add(cursor, s)
116
+ cursor = max(cursor, e)
117
+ add(cursor, total)
118
+ if not keep:
119
+ if dropped:
120
+ die(f"--remove leaves only sound with no picture ({', '.join(f'{a:.3f}-{b:.3f}s' for a, b in dropped)}, "
121
+ f"outside the video's {picture[0]:.3f}-{picture[1]:.3f}s); nothing with a picture would be left to keep. "
122
+ "Write the sound out with an audio -o (e.g. -o part.wav) instead", kind="input")
123
+ die(f"--remove drops the whole file ({total:.3f}s); nothing would be left to keep")
124
+ return keep
125
+
126
+
127
+ def parse_segments(spec: str, fps=None, clamp: bool = False) -> List[Tuple[float, float]]:
128
+ """START-END,... as seconds. `clamp` (--remove) lets a range start before 0, since the file
129
+ clamps it; --segments refuses that."""
130
+ segs = []
131
+ for raw in spec.split(","):
132
+ raw = raw.strip()
133
+ if not raw:
134
+ continue
135
+ if "-" not in raw:
136
+ die(f"segment '{raw}' must look like START-END (e.g. 0:05-0:12)")
137
+ a, b = raw.rsplit("-", 1)
138
+ start, end = _t(a, fps), _t(b, fps)
139
+ if start < 0 and not clamp:
140
+ die(f"segment '{raw}': start must be >= 0")
141
+ if end <= start:
142
+ die(f"segment '{raw}': end must be after start")
143
+ segs.append((start, end))
144
+ if not segs:
145
+ die("no segments given")
146
+ return segs
147
+
148
+
149
+ def encode_args(meta: dict, dst: str, crf: int, preset: str) -> List[str]:
150
+ """Codec arguments for a re-encoded cut: video + AAC into a video container, otherwise the codec
151
+ the audio extension names (PCM for .wav, FLAC, MP3, AAC...) with no video stream."""
152
+ if is_audio_output(dst) or not meta.get("video"):
153
+ return ["-vn"] + audio_codec_for(dst)
154
+ return video_encode_args(meta, crf, preset) + aac_args()
155
+
156
+
157
+ def video_encode_args(meta: dict, crf: int, preset: str) -> List[str]:
158
+ return source_codec_video_args(meta, crf, preset, keep_hevc=KEEP_HEVC) + cfr_args(meta)
159
+
160
+
161
+ def copy_args(meta: dict, dst: str) -> List[str]:
162
+ """Stream-copy arguments: everything into a video container, audio only into an audio extension."""
163
+ if is_audio_output(dst) and meta.get("video"):
164
+ return ["-vn", "-c:a", "copy"]
165
+ args = ["-c", "copy"]
166
+ if os.path.splitext(dst)[1].lower() in (".mp4", ".mov", ".m4v"):
167
+ args += ["-movflags", "+faststart"]
168
+ return args
169
+
170
+
171
+ def stream_maps(meta: dict, dst: str, copy: bool) -> List[str]:
172
+ """The -map arguments of a cut: the picture and the sound probe() describes, which every
173
+ measurement here (keyframes, start skew, timecode, length) is taken from. ffmpeg's default
174
+ selection wrote the largest picture and the track with the default disposition or the most
175
+ channels instead (A258). A stream copy of a file with one picture and one sound keeps the
176
+ default selection, command for command (it also carries a subtitle stream into a container
177
+ whose muxer names a subtitle codec, such as Matroska). With several, the first subtitle stream
178
+ is mapped when the container holds it as it is, and is otherwise left out and reported
179
+ (DROPPED_STREAMS)."""
180
+ audio_only = is_audio_output(dst) or not meta.get("video")
181
+ if copy and not several_av_streams(meta):
182
+ return []
183
+ maps = probed_maps(meta, video=not audio_only)
184
+ subs = meta.get("subtitle_stream_details") or []
185
+ if copy and not audio_only and subs:
186
+ codec, ext = subs[0].get("codec") or "", os.path.splitext(dst)[1].lstrip(".").lower()
187
+ if subtitle_container_holds(codec, ext) and subtitle_codec_for(codec, ext) == "copy":
188
+ maps += ["-map", "0:s:0"]
189
+ else:
190
+ DROPPED_STREAMS.append(dst)
191
+ return maps
192
+
193
+
194
+ LOSSLESS_AUDIO = {"pcm_s16le", "pcm_s16be", "pcm_s24le", "pcm_s32le", "pcm_f32le", "flac"} # pcm_s16be: .aif/.aiff/.caf (#517)
195
+
196
+
197
+ def precision_of(meta: dict, dst: str, reencoded: bool) -> str:
198
+ """How exact the cut is, measured on what was written:
199
+
200
+ packet stream copy; the cut lands on a packet (audio) or keyframe (video) boundary
201
+ sample decoded audio trimmed to the sample and written losslessly (PCM / FLAC)
202
+ codec_frame decoded audio trimmed to the sample, then framed by a lossy encoder (AAC 1024,
203
+ MP3 1152, Opus 960 samples) which also adds its priming delay to the reported length
204
+ frame re-encoded video: the picture is frame-exact, the audio underneath is sample-trimmed
205
+ """
206
+ if not reencoded:
207
+ return "packet"
208
+ if is_audio_output(dst) or not meta.get("video"):
209
+ codec = audio_codec_for(dst)[1]
210
+ return "sample" if codec in LOSSLESS_AUDIO else "codec_frame"
211
+ return "frame"
212
+
213
+
214
+ # The order `precision` values rank in, least exact first. It is a conservative order for this
215
+ # tool's segments (all cut from one source into one container), not a universal scale.
216
+ PRECISION_ORDER = ("packet", "codec_frame", "frame", "sample")
217
+
218
+
219
+ def least_exact(precisions: List[str]) -> str:
220
+ return min(precisions, key=PRECISION_ORDER.index)
221
+
222
+
223
+ def report_precision(meta: dict, dst: str, reencoded: bool, outcomes: List[dict]) -> dict:
224
+ """The run's precision keys from its segments' outcomes.
225
+
226
+ precision since 3.0.0, the least exact segment's precision (least_exact_precision);
227
+ 2.x reported precision_of() for the whole run
228
+ keyframe_snapped since 3.0.0, start_snapped (a copied start really moved); 2.x reported
229
+ "the run is a stream copy end to end" (precision_of() == "packet")
230
+ start_snapped measured: true when a copied segment's picture starts more than a frame from
231
+ its requested start; false when every start is where asked (an edit list, a
232
+ start on a keyframe, an audio-only copy's packet seek) or everything
233
+ re-encoded; null when a copied start was not measured (--dry-run)
234
+ least_exact_precision the least exact segment's precision; differs from `precision` only for
235
+ an audio-only --segments join of copied and re-encoded parts (a video join
236
+ re-cuts every segment when any part re-encodes)
237
+ segment_precision each segment's, for --segments (null for one segment)"""
238
+ snaps = [o.get("start_snapped") for o in outcomes]
239
+ if any(s is True for s in snaps):
240
+ start_snapped = True
241
+ elif any(s is None for s in snaps):
242
+ start_snapped = None
243
+ else:
244
+ start_snapped = False
245
+ least = least_exact([o["precision"] for o in outcomes])
246
+ # 3.0.0: `precision` is the least exact segment's and `keyframe_snapped` says whether a copied
247
+ # start really moved (2.x: the run-level formula, and "the run is a stream copy end to end")
248
+ return {"precision": least, "keyframe_snapped": start_snapped, "start_snapped": start_snapped,
249
+ "least_exact_precision": least,
250
+ "segment_precision": [o["precision"] for o in outcomes] if len(outcomes) > 1 else None}
251
+
252
+
253
+ def _outcome(meta: dict, dst: str, reencoded: bool, reasons: List[str], **copy) -> dict:
254
+ """One segment's outcome. start_snapped defaults to false: a re-encode starts where asked, and
255
+ an audio-only copy seeks on the output side, to the packet; a video copy passes the measured
256
+ value (copy_presentation), a --dry-run copy None."""
257
+ out = {"reencoded": reencoded, "reasons": reasons, "precision": precision_of(meta, dst, reencoded),
258
+ "start_snapped": False, "edit_list": False, "stored_preroll_seconds": None}
259
+ out.update(copy)
260
+ return out
261
+
262
+
263
+ EDIT_LIST_EXTS = (".mp4", ".mov", ".m4v")
264
+
265
+
266
+ def possible_reencode_reason(mode: str, outcomes: List[dict], segments: int) -> List[str]:
267
+ """Under --dry-run, the reencode_reason values a real run may still add to a plan of mode copy
268
+ or smart, which would then report hybrid or accurate (#510): the dry run reads no packets for a
269
+ single copy, so where its copy lands, and every check a real run makes on the written file,
270
+ are not known yet. [] for a real run and for a plan that already re-encodes."""
271
+ if not STATE.dry_run:
272
+ return []
273
+ if mode == "smart":
274
+ return ["smart_fallback"] # the checks run on the written file (smart.checks is null)
275
+ if mode != "copy":
276
+ return []
277
+ possible = ["copy_failed", "stream_lost"]
278
+ if any(o.get("length_unjudged") for o in outcomes):
279
+ possible.append("tolerance")
280
+ if segments > 1:
281
+ possible.append("concat_fallback")
282
+ return possible
283
+
284
+
285
+ def possible_reencode_note(mode: str, possible: List[str], tolerance: float) -> str:
286
+ """The plan's notes line for possible_reencode_reason."""
287
+ if mode == "smart":
288
+ return ("planned as a smart cut: a real run checks the written cut against the source and re-encodes "
289
+ "the whole cut instead (mode accurate, reencode_reason smart_fallback) when a check fails")
290
+ why = ("planned as a stream copy: a real run may re-encode it instead (mode hybrid, reencode_reason "
291
+ + ", ".join(possible) + ")")
292
+ if "tolerance" in possible:
293
+ why += (f"; where the copy lands is measured only from the written file, and a copy that lands "
294
+ f"{tolerance:.2f}s (--tolerance) or more from the requested cut is re-encoded")
295
+ return why
296
+
297
+
298
+ def _with_notes(outcome: dict, notes: List[str]) -> dict:
299
+ """An outcome with the notes of the attempt that led to it put first."""
300
+ outcome["notes"] = list(notes) + list(outcome.get("notes") or [])
301
+ return outcome
302
+
303
+
304
+ _ORIGINS: dict = {}
305
+
306
+
307
+ def file_origin(src: str) -> float:
308
+ """The file's format start_time: the zero that -ss and segment times count from. Stream
309
+ start_times are absolute, so subtract this to put them on the cut's clock. One probe per source."""
310
+ if src not in _ORIGINS:
311
+ proc = run([require_tool("ffprobe"), "-v", "error", "-show_entries", "format=start_time", "-of", "csv=p=0", src],
312
+ quiet=True, check=False)
313
+ try:
314
+ _ORIGINS[src] = float((proc.stdout or "").strip() or 0.0)
315
+ except ValueError:
316
+ _ORIGINS[src] = 0.0
317
+ return _ORIGINS[src]
318
+
319
+
320
+ def source_skew(src: str, meta: dict, t: float) -> float:
321
+ """How far the source's audio starts after its video at `t` on the cut's clock: a cut from
322
+ `t` that keeps both streams where they were starts them this far apart (0 once both run)."""
323
+ v, a = meta.get("video") or {}, meta.get("audio") or {}
324
+ if v.get("start_time") is None or a.get("start_time") is None:
325
+ return 0.0
326
+ origin = file_origin(src)
327
+ return max(a["start_time"] - origin, t) - max(v["start_time"] - origin, t)
328
+
329
+
330
+ def video_end(src: str, meta: dict):
331
+ """Where the video stream ends on the cut's clock (seconds from the file's start), or None when
332
+ the stream's length is unknown. A Matroska/WebM stream states no duration, only its DURATION
333
+ tag, which is already that end (own_end()); read from `duration` alone, a .mkv had no picture
334
+ end and --remove kept a sound-only leftover past it."""
335
+ from _common.emit import own_end
336
+ end = own_end(meta.get("video"))
337
+ return None if end is None else end - file_origin(src)
338
+
339
+
340
+ _SEEK_SHIFTS: dict = {}
341
+ # ffmpeg's dts heuristic: before a demuxer that does not seek by presentation time, an input -ss
342
+ # seeks this much earlier when a stream has a decode delay (B-frames); fftools ffmpeg_demux.c
343
+ DTS_HEURISTIC = 3.0 / 23
344
+
345
+
346
+ def seek_shift(src: str) -> float:
347
+ """How much earlier than `-ss t` ffmpeg's input seek asks the demuxer for: DTS_HEURISTIC for a
348
+ demuxer that does not seek by pts (Matroska, MPEG-TS...) when a stream has a decode delay, 0
349
+ for MP4/MOV and MXF (AVFMT_SEEK_TO_PTS) or a source with no delay. One probe per source."""
350
+ if src not in _SEEK_SHIFTS:
351
+ proc = run([require_tool("ffprobe"), "-v", "error", "-show_entries", "format=format_name:stream=has_b_frames",
352
+ "-of", "json", src], quiet=True, check=False)
353
+ try:
354
+ doc = json.loads(proc.stdout or "") if proc.returncode == 0 else {}
355
+ name = str((doc.get("format") or {}).get("format_name") or "")
356
+ delay = any(int(st.get("has_b_frames") or 0) > 0 for st in doc.get("streams") or [])
357
+ except (ValueError, TypeError, AttributeError):
358
+ name, delay = "", False
359
+ _SEEK_SHIFTS[src] = 0.0 if ({"mov", "mxf"} & set(name.split(",")) or not delay) else DTS_HEURISTIC
360
+ return _SEEK_SHIFTS[src]
361
+
362
+
363
+ _LANDINGS: dict = {}
364
+
365
+
366
+ def seek_keyframe(src: str, t: float):
367
+ """The keyframe a stream copy starting at `-ss t` begins from, as (pts, dts, first presented
368
+ pts at or after t) in seconds on the cut's clock, or None when it cannot be read.
369
+
370
+ Measured, not modelled: ffprobe -read_intervals seeks with the same avformat_seek_file call as
371
+ ffmpeg's input -ss (to the file's start_time + t, less seek_shift()), and the copy starts at
372
+ the first keyframe read after it, as ffmpeg drops the packets before it. A model ("the
373
+ keyframe with the largest dts at or before t") was wrong both ways: the MP4 demuxer seeks
374
+ over its raw decode times, ffprobe's dts plus the reorder delay, so on B-frame H.264 -ss 3.99
375
+ landed on the keyframe at 2.0, not on the one at 4.0 (dts 3.933), while on a keyint-60 HEVC
376
+ file -ss 9.9 began at the keyframe at 10.0 (dts 9.833). The read does not seek earlier than
377
+ ffmpeg does: a seek before the file's start skips an edit-listed MP4's negative-pts keyframe.
378
+ Cached on (src, t)."""
379
+ key = (src, round(t, 6))
380
+ if key in _LANDINGS:
381
+ return _LANDINGS[key]
382
+ origin = file_origin(src)
383
+ target = origin + t - seek_shift(src)
384
+ proc = run([require_tool("ffprobe"), "-v", "error", "-select_streams", "v:0", "-show_entries",
385
+ "packet=pts_time,dts_time,flags", "-of", "json", "-read_intervals",
386
+ f"{target:.6f}%{origin + t + 1.0:.6f}", src], quiet=True, check=False)
387
+ try:
388
+ packets = json.loads(proc.stdout or "")["packets"] if proc.returncode == 0 else []
389
+ except (ValueError, KeyError, TypeError):
390
+ packets = []
391
+ landed, pts_all = None, []
392
+ for p in packets if isinstance(packets, list) else []:
393
+ try:
394
+ pts = float(p["pts_time"]) - origin
395
+ except (KeyError, TypeError, ValueError):
396
+ continue
397
+ if landed is None:
398
+ if "K" not in str(p.get("flags", "")):
399
+ continue # ffmpeg's copy drops what comes before the first keyframe
400
+ try:
401
+ landed = (pts, float(p.get("dts_time", p["pts_time"])) - origin)
402
+ except (TypeError, ValueError):
403
+ landed = (pts, pts)
404
+ pts_all.append(pts)
405
+ if landed is None:
406
+ _LANDINGS[key] = None
407
+ return None
408
+ # the first picture an edit list starting at t presents: the first frame at or after t
409
+ later = [x for x in pts_all if x >= t - 1e-6]
410
+ _LANDINGS[key] = (landed[0], landed[1], min(later) if later else None)
411
+ return _LANDINGS[key]
412
+
413
+
414
+ def copy_presentation(t: float, key, edit_list: bool, fps) -> dict:
415
+ """What a stream copy starting at `t` presents, from the keyframe it began at (seek_keyframe).
416
+ With an MP4 edit list a keyframe at or before t is decoded but hidden (stored pre-roll) and the
417
+ picture starts at t; a keyframe after t starts the picture late. Without one (Matroska, or a
418
+ concat part cut with make_zero) the picture starts at the keyframe. start_snapped: the
419
+ presented start is more than a frame from t (an unmeasured start counts as snapped)."""
420
+ frame = 1.0 / fps if fps else 0.0
421
+ if key is None:
422
+ return {"start_snapped": True, "stored_preroll_seconds": None}
423
+ k_pts, first = key[0], key[2]
424
+ if first is None:
425
+ # no packet at or after t in the probed window: where the picture starts is unmeasured
426
+ return {"start_snapped": True, "stored_preroll_seconds": None}
427
+ if edit_list and k_pts <= t + 1e-6:
428
+ # hidden: the pictures decoded from the keyframe up to the first one presented
429
+ return {"start_snapped": False, "stored_preroll_seconds": round(max(0.0, first - k_pts), 6)}
430
+ return {"start_snapped": abs(k_pts - t) > frame + 1e-6, "stored_preroll_seconds": None}
431
+
432
+
433
+ def first_frame_from(src: str, meta: dict, start: float, reencode: bool, edit_list: bool):
434
+ """Seconds from the source picture's first frame to the frame a cut from `start` begins on,
435
+ for its start timecode: the first frame at or after `start` for a re-encode and an edit-listed
436
+ copy that hides its keyframe's pre-roll, the keyframe for any other copy (it shows the
437
+ pre-roll). None when where a copy lands cannot be read."""
438
+ v0, rate = stream_starts(meta)[0], frame_rate(meta)
439
+ if reencode:
440
+ # a start before the picture's first frame (a video that starts after the file's origin)
441
+ # begins on that first frame, not on a grid frame before it
442
+ return grid_at_or_after(max(start, v0), v0, rate) - v0
443
+ key = seek_keyframe(src, start)
444
+ if key is None:
445
+ return None
446
+ if edit_list and key[0] <= start + 1e-6:
447
+ return None if key[2] is None else key[2] - v0
448
+ return key[0] - v0
449
+
450
+
451
+ def copied_lead(meta: dict, start: float, end: float) -> Optional[float]:
452
+ """The seconds of a sound's late start that an audio-only stream copy of start..end leaves out
453
+ (#515): the copy begins at the first packet, so a sound that starts after `start` on the file's
454
+ clock (stream_starts) comes out that much early. None when it is less than one frame of the
455
+ source's picture (1 ms without one), which no picture could show, or when the start is unknown."""
456
+ audio = meta.get("audio") or {}
457
+ if not isinstance(audio.get("start_time"), (int, float)):
458
+ return None
459
+ lead = min(stream_starts(meta)[1], end) - start
460
+ fps = (meta.get("video") or {}).get("fps")
461
+ return round(lead, 6) if lead >= (1.0 / float(fps) if fps else 0.001) else None
462
+
463
+
464
+ def av_skew(out_meta: dict, edit_list_remedy: bool = False, expected: float = 0.0):
465
+ """(seconds audio starts after video, warning note or None); None when either is missing.
466
+ A lossless cut can start its streams apart -- Core Media HEVC once gave 3.7 s of sound with no
467
+ picture from a run that exited 0 -- so a skew more than max(2 frames, 0.1 s) away from
468
+ `expected` (the source's own skew at the cut's start: a track that starts late there, by
469
+ design, is not a defect of the cut) is named. It is reported, not repaired:
470
+ `edit_list_remedy` (a single MP4/MOV copy whose start snapped, cut without --edit-list)
471
+ names --edit-list as the lossless way to start both streams at --start."""
472
+ v, a = out_meta.get("video") or {}, out_meta.get("audio") or {}
473
+ if v.get("start_time") is None or a.get("start_time") is None:
474
+ return None, None
475
+ skew = round(a["start_time"] - v["start_time"], 6)
476
+ fps = v.get("fps") or 0
477
+ limit = max(2.0 / fps if fps else 0.0, 0.1)
478
+ if abs(skew - expected) <= limit:
479
+ return skew, None
480
+ first = "audio" if skew > 0 else "video"
481
+ return skew, (f"the {'video' if first == 'audio' else 'audio'} starts {abs(skew):.3f}s before the {first}"
482
+ + (f" ({abs(expected):.3f}s in the source there)" if abs(expected) > 1e-3 else "")
483
+ + ": a stream copy began on packets the two streams do not share; re-run with --accurate "
484
+ "for a cut whose picture and sound start together"
485
+ + (", or with --edit-list to keep the lossless copy and hide the keyframe's pre-roll"
486
+ if edit_list_remedy else ""))
487
+
488
+
489
+ _PACKETS: dict = {}
490
+
491
+
492
+ def _packet_time(value):
493
+ try:
494
+ return float(value)
495
+ except (TypeError, ValueError):
496
+ return None
497
+
498
+
499
+ class _Packets(list):
500
+ """video_packets' result: (pts, dts, keyframe) in decode order, plus `breaks`, the indices of
501
+ packets after which a read window ended before the end of the file (what follows is a later
502
+ window, not the next packet), and `spans`, each window's (lo, hi) with the range of packets
503
+ read in it."""
504
+ breaks: frozenset = frozenset()
505
+ spans: tuple = ()
506
+
507
+
508
+ # video_packets reads [start - M, end + M] around each segment, M = max(PACKET_MARGIN, 2 x
509
+ # --tolerance), and widens M x4 up to PACKET_WIDENINGS times before reading the whole file
510
+ PACKET_MARGIN = 10.0
511
+ PACKET_WIDENINGS = 3
512
+
513
+
514
+ def packet_windows(segments, margin: float, total=None) -> tuple:
515
+ """The merged read windows around `segments`, as (lo, hi) on the cut's clock: lo None from the
516
+ file's start (never a seek: a seek to it skips an edit-listed MP4's negative-pts keyframe, as
517
+ measure_frame_timing found), hi None to its end (`total`, the media duration)."""
518
+ spans = sorted((s - margin, e + margin) for s, e in segments)
519
+ merged = []
520
+ for lo, hi in spans:
521
+ if merged and lo <= merged[-1][1]:
522
+ merged[-1][1] = max(merged[-1][1], hi)
523
+ else:
524
+ merged.append([lo, hi])
525
+ return tuple((None if lo <= 0 else round(lo, 6), None if total and hi >= total else round(hi, 6))
526
+ for lo, hi in merged)
527
+
528
+
529
+ def _read_packets(src: str, windows: tuple):
530
+ """The video packets of `src` in `windows` (packet_windows; ((None, None),) is the whole file),
531
+ one ffprobe per window, or None when ffprobe fails. A window's seek lands on the keyframe
532
+ before its start, so packets a previous window already read (dts not after its last) are
533
+ dropped. Cached on (src, windows)."""
534
+ key = (src, windows)
535
+ if key in _PACKETS:
536
+ return _PACKETS[key]
537
+ origin = file_origin(src)
538
+ packets, breaks, spans, last_dts = _Packets(), set(), [], None
539
+ for lo, hi in windows:
540
+ first, before = len(packets), last_dts
541
+ cmd = [require_tool("ffprobe"), "-v", "error", "-select_streams", "v:0", "-show_entries",
542
+ "packet=pts_time,dts_time,flags", "-of", "csv=p=0"]
543
+ if lo is not None or hi is not None:
544
+ cmd += ["-read_intervals", ("" if lo is None else f"{origin + lo:.6f}") + "%"
545
+ + ("" if hi is None else f"{origin + hi:.6f}")]
546
+ proc = run(cmd + [src], quiet=True, check=False)
547
+ if proc.returncode != 0:
548
+ _PACKETS[key] = None
549
+ return None
550
+ for line in (proc.stdout or "").split():
551
+ fields = line.split(",")
552
+ if len(fields) < 3:
553
+ continue
554
+ pts, dts = _packet_time(fields[0]), _packet_time(fields[1])
555
+ pts, dts = (None if pts is None else pts - origin), (None if dts is None else dts - origin)
556
+ if before is not None and dts is not None and dts <= before + 1e-9:
557
+ continue
558
+ packets.append((pts, dts, "K" in fields[2]))
559
+ if dts is not None:
560
+ last_dts = dts
561
+ if hi is not None and len(packets) > first:
562
+ breaks.add(len(packets) - 1)
563
+ spans.append((lo, hi, first, len(packets)))
564
+ packets.breaks, packets.spans = frozenset(breaks), tuple(spans)
565
+ _PACKETS[key] = packets or None
566
+ return _PACKETS[key]
567
+
568
+
569
+ def _windows_cover(packets, segments) -> bool:
570
+ """True when the packets read around each segment hold what the plan needs from them: the
571
+ keyframe the copy lands on (the largest dts at or before the start; none at all only counts
572
+ from the file's start), a whole GOP after it, and the first keyframe at or after the end
573
+ with a whole GOP after that too (gop_is_open judges both) -- or the end of the file."""
574
+ runs = [(lo, hi, packets[i0:i1]) for lo, hi, i0, i1 in packets.spans]
575
+ for s, e in segments:
576
+ run_ = next(((lo, hi, p) for lo, hi, p in runs if (lo is None or lo <= s) and (hi is None or hi >= e)), None)
577
+ if run_ is None:
578
+ return False
579
+ lo, hi, part = run_
580
+ keys = [(p[0], p[1]) for p in part if p[2] and p[0] is not None and p[1] is not None]
581
+ landed = [k for k in keys if k[1] <= s + 1e-6]
582
+ if not landed:
583
+ if lo is None:
584
+ continue
585
+ return False
586
+ k_dts = max(k[1] for k in landed)
587
+ later = [k for k in keys if k[1] > k_dts + 1e-9]
588
+ if not later:
589
+ if hi is None:
590
+ continue
591
+ return False
592
+ after = [k for k in later if k[0] >= e - 1e-6]
593
+ if hi is None:
594
+ continue
595
+ if not after or not [k for k in after if k[1] > min(after)[1] + 1e-9]:
596
+ return False
597
+ return True
598
+
599
+
600
+ def video_packets(src: str, segments=None, tolerance: float = 0.5, total=None):
601
+ """The video packets of `src` a --segments copy join is planned and checked against, in decode
602
+ order, as (pts, dts, keyframe) on the cut's clock (a missing timestamp is None), or None
603
+ when ffprobe cannot read them. Only windows around the segments are read (packet_windows),
604
+ widened x4 up to PACKET_WIDENINGS times while one lacks what the plan needs (_windows_cover),
605
+ and the whole file after that, so the cost follows the segments asked for, not the source's
606
+ length; with no `segments`, the whole file."""
607
+ if segments:
608
+ margin = max(PACKET_MARGIN, 2 * tolerance)
609
+ for _ in range(PACKET_WIDENINGS + 1):
610
+ windows = packet_windows(segments, margin, total)
611
+ if windows == ((None, None),):
612
+ break
613
+ packets = _read_packets(src, windows)
614
+ if packets is None:
615
+ return None
616
+ if _windows_cover(packets, segments):
617
+ return packets
618
+ margin *= 4
619
+ return _read_packets(src, ((None, None),))
620
+
621
+
622
+ def gop_is_open(packets, i: int) -> bool:
623
+ """True when keyframe packets[i] starts an open GOP: a packet decoded after it, before the next
624
+ keyframe, is presented before it (a leading picture, which needs the GOP before to decode). A
625
+ missing timestamp there counts as open, and so does a GOP whose read window ended before its
626
+ next keyframe (video_packets widens its windows so that the GOPs a plan judges are whole). A
627
+ GOP the file ends in has been read to its last packet and is judged on those."""
628
+ key = packets[i][0]
629
+ breaks = getattr(packets, "breaks", ())
630
+ if key is None or i in breaks:
631
+ return True
632
+ for j in range(i + 1, len(packets)):
633
+ pts, dts, is_key = packets[j]
634
+ if is_key:
635
+ return False
636
+ if pts is None or dts is None or pts < key - 1e-6 or j in breaks:
637
+ return True
638
+ return False
639
+
640
+
641
+ # a copied part stops before its end keyframe's packet by this much: -t compares decode
642
+ # timestamps, and ffprobe prints them rounded to the microsecond
643
+ _DTS_MARGIN = 1e-4
644
+
645
+
646
+ def reorders(packets) -> bool:
647
+ """True when the source's frames reorder: some packet is presented before one decoded ahead of
648
+ it (B-frames). A source that never reorders cuts exactly in decode order, so its --segments
649
+ parts are cut as in every 2.x release (main()). Judged within each window video_packets read:
650
+ the gap between two windows is not a reorder."""
651
+ breaks = getattr(packets, "breaks", ())
652
+ top = None
653
+ for i, (pts, _dts, _key) in enumerate(packets):
654
+ if pts is not None:
655
+ if top is not None and pts < top - 1e-6:
656
+ return True
657
+ top = pts if top is None else max(top, pts)
658
+ if i in breaks:
659
+ top = None
660
+ return False
661
+
662
+
663
+ def plan_part(packets, start: float, end: float, tolerance: float, vend, fps, snap_end: bool = True,
664
+ landing=None) -> dict:
665
+ """How the --segments part start-end is stream-copied for a concat-demuxer join.
666
+
667
+ The copy begins at the keyframe `-ss start` lands on: `landing`, seek_keyframe()'s measurement,
668
+ when it is one of `packets`' keyframes, otherwise the one with the largest dts at or before
669
+ `start` (which the MP4 demuxer's seek over raw decode times does not always take: the join
670
+ check is the backstop). The join presents from that keyframe: the concat demuxer does not apply the part's edit
671
+ list start. The part ends at its end keyframe's DTS: an input -t stops in decode order, so
672
+ ending at the keyframe's pts would carry that keyframe and the P-frame after it into the part.
673
+ The end keyframe is the first one presented at or after `end` among those decoded after the
674
+ landing (an earlier one would drop requested frames, and any decoded before the landing would
675
+ give -t <= 0); one past `tolerance` re-encodes, reason "tolerance". With no keyframe after
676
+ `end` (the end is in the video's last GOP) the end stays where asked and check_join judges
677
+ the copy. A part that reaches the end of the video keeps -t end-start: nothing follows it to
678
+ leak in. Without `snap_end` (a source whose frames do not reorder, or Matroska/MPEG-TS
679
+ parts) the end is left where asked, as in every 2.x release; only the start is judged."""
680
+ frame = 1.0 / fps if fps else 0.001
681
+ keys = [(i, p[0], p[1]) for i, p in enumerate(packets) if p[2] and p[0] is not None and p[1] is not None]
682
+ measured = ([k for k in keys if abs(k[1] - landing[0]) < 1e-5] if landing else [])
683
+ landed = measured[:1] or [k for k in keys if k[2] <= start + 1e-6]
684
+ if not landed and keys and (not getattr(packets, "spans", None) or packets.spans[0][0] is None):
685
+ # a video stream that starts after `start` (its sound leads it): the seek lands on its
686
+ # first keyframe, which the tolerance judges like any other
687
+ landed = keys[:1]
688
+ plan = {"reason": None, "start": start, "t": end - start, "start_index": None, "start_pts": None,
689
+ "end_index": None, "end_pts": None, "end_bound": end}
690
+ if not landed:
691
+ plan["reason"] = "tolerance"
692
+ return plan
693
+ si, s_pts, s_dts = max(landed, key=lambda k: k[2])
694
+ plan.update(start_index=si, start_pts=s_pts)
695
+ within = (lambda off: True) if tolerance < 0 else (lambda off: off < tolerance)
696
+ if not within(abs(s_pts - start)):
697
+ plan["reason"] = "tolerance"
698
+ return plan
699
+ if vend is not None and end >= vend - frame / 2:
700
+ plan["end_bound"] = None
701
+ return plan
702
+ if not snap_end:
703
+ return plan
704
+ after = [k for k in keys if k[2] > s_dts + 1e-9 and k[1] >= end - 1e-6]
705
+ if not after:
706
+ # the end is in the video's last GOP: no keyframe to snap it to, so the end stays where
707
+ # asked and check_join judges the copy (a B-frame part cut mid-GOP in decode order usually
708
+ # fails it, and the join is re-cut) -- not a tolerance miss, even under --tolerance -1
709
+ return plan
710
+ ei, e_pts, e_dts = min(after, key=lambda k: k[1])
711
+ if not within(e_pts - end):
712
+ plan["reason"] = "tolerance"
713
+ return plan
714
+ t = e_dts - start - _DTS_MARGIN
715
+ if t < 0.001:
716
+ # the start sits within a millisecond of the end keyframe's dts: no packet to copy
717
+ plan["reason"] = "tolerance"
718
+ return plan
719
+ plan.update(t=t, end_index=ei, end_pts=e_pts, end_bound=e_pts)
720
+ return plan
721
+
722
+
723
+ def hidden_preroll_start(packets, plans, edit_listed: bool):
724
+ """The 1-based number of the first part after the first whose start is not on a keyframe
725
+ presented at or before it, for edit-listed (.mp4/.mov) parts of a source whose frames reorder;
726
+ None otherwise. Such a part stores the frames from its keyframe to its start as hidden
727
+ pre-roll, which the concat demuxer crushes into sub-millisecond steps at the join (measured on
728
+ every source shape tried), so the join is re-cut without trying the copy."""
729
+ if not edit_listed:
730
+ return None
731
+ for i, plan in enumerate(plans):
732
+ if i and not plan["reason"] and plan["start_pts"] is not None and plan["start_pts"] < plan["start"] - _DTS_MARGIN:
733
+ return i + 1
734
+ return None
735
+
736
+
737
+ def open_join_key(packets, plans):
738
+ """The pts of the first keyframe a stream-copy join of the planned parts cannot cross, or None.
739
+ An open END keyframe: its leading pictures belong to the part but decode after the keyframe,
740
+ so a part cut in decode order loses them. An open START keyframe after the first part: the
741
+ decoder drops leading pictures only at the start of a stream, so after a join they would decode
742
+ against the previous part's frames. Parts that re-encode anyway are skipped."""
743
+ for i, plan in enumerate(plans):
744
+ if plan["reason"]:
745
+ continue
746
+ if i and gop_is_open(packets, plan["start_index"]):
747
+ return plan["start_pts"]
748
+ if plan["end_index"] is not None and gop_is_open(packets, plan["end_index"]):
749
+ return plan["end_pts"]
750
+ return None
751
+
752
+
753
+ def stream_packet_times(path: str, stream: str, entry: str, limit: int = None) -> list:
754
+ """One timestamp field (pts_time, duration_time) of every packet of the first `stream` ("v" or
755
+ "a") in `path`, or of its first `limit` packets; a missing value is None. [] when there is no
756
+ such stream or ffprobe fails."""
757
+ cmd = [require_tool("ffprobe"), "-v", "error", "-select_streams", f"{stream}:0", "-show_entries", f"packet={entry}",
758
+ "-of", "csv=p=0"] + (["-read_intervals", f"%+#{limit}"] if limit else []) + [path]
759
+ proc = run(cmd, quiet=True, check=False)
760
+ if proc.returncode != 0:
761
+ return []
762
+ return [_packet_time(line.split(",")[0]) for line in (proc.stdout or "").split()]
763
+
764
+
765
+ def expected_packets(packets, ranges) -> int:
766
+ """How many source video packets the join's parts present: those with lo <= pts < hi in each
767
+ (lo, hi) range, hi None for a part that runs to the end of the video."""
768
+ return sum(1 for lo, hi in ranges for pts, _, _ in packets
769
+ if pts is not None and pts >= lo - 1e-6 and (hi is None or pts < hi - 1e-6))
770
+
771
+
772
+ def check_join(out_pts, counts, fps, cfr: bool, predicted=None) -> dict:
773
+ """The joined file measured, not predicted: its video packet count against the source's
774
+ (`counts`, one per part, from expected_packets), and with constant frame timing every
775
+ presentation step. A step inside a part is a frame (more than half, less than one and a half).
776
+ The step at a join is the one `predicted` from the parts (predicted_join_steps), within a
777
+ millisecond: the frame before a join is shown for its frame plus the time the concat
778
+ demuxer leaves between the parts' pictures, which is not a fixed bound -- 56.7 ms at 30 fps
779
+ for an exact no-B-frame join, one audio frame or more past a frame for PCM -- and a bound
780
+ loose enough for every source let a hole of one audio packet through. Without a prediction
781
+ a join step is held to the interior bound."""
782
+ expected = sum(counts)
783
+ pts = sorted(p for p in out_pts if p is not None)
784
+ ok = len(out_pts) == expected and len(pts) == len(out_pts)
785
+ max_step = None
786
+ if cfr and fps:
787
+ frame = 1.0 / fps
788
+ gaps = [b - a for a, b in zip(pts, pts[1:])]
789
+ if gaps:
790
+ max_step = round(max(gaps), 6)
791
+ joins = {}
792
+ if ok and predicted:
793
+ at = 0
794
+ for j, n in enumerate(counts[:-1]):
795
+ at += n
796
+ if 0 < at < len(pts) and j < len(predicted) and predicted[j] is not None:
797
+ joins[at - 1] = predicted[j]
798
+ ok = ok and all(abs(g - joins[i]) <= JOIN_STEP_SLACK and g > frame / 2 if i in joins
799
+ else frame / 2 < g < 1.5 * frame for i, g in enumerate(gaps))
800
+ return {"packets": len(out_pts), "expected_packets": expected, "max_step_seconds": max_step, "ok": ok}
801
+
802
+
803
+ def _adts_payload(data: str) -> bytes:
804
+ """A packet's bytes from ffprobe's -show_data hex dump, without the ADTS header an MPEG-TS AAC
805
+ packet carries (7 bytes, 9 with a CRC): what aac_adtstoasc leaves when the packet is copied
806
+ into MP4, MOV or Matroska."""
807
+ raw = bytearray()
808
+ for line in str(data or "").strip().splitlines():
809
+ _, _, rest = line.partition(":")
810
+ raw += bytes.fromhex(rest.strip().split(" ")[0].replace(" ", ""))
811
+ if len(raw) >= 7 and raw[0] == 0xFF and (raw[1] & 0xF6) == 0xF0:
812
+ return bytes(raw[7 if raw[1] & 1 else 9:])
813
+ return bytes(raw)
814
+
815
+
816
+ def audio_packet_hashes(path: str, lo=None, hi=None, stream: str = "a:0", strip_adts: bool = False) -> list:
817
+ """(pts, CRC32) of the `stream` audio packets of `path`, on its own raw clock, from `lo` to `hi`
818
+ (absolute seconds; None = the file's start or end: a read from the start never seeks). With
819
+ `strip_adts` each packet is hashed without its ADTS header (_adts_payload; zlib's CRC32 is
820
+ ffprobe's), so an MPEG-TS source's AAC matches the same packets copied out of it. [] when
821
+ there is no such stream or ffprobe fails."""
822
+ cmd = [require_tool("ffprobe"), "-v", "error", "-select_streams", stream]
823
+ if strip_adts:
824
+ cmd += ["-show_entries", "packet=pts_time,data", "-show_data", "-of", "json"]
825
+ else:
826
+ cmd += ["-show_entries", "packet=pts_time,data_hash", "-show_data_hash", "CRC32", "-of", "csv=p=0"]
827
+ if lo is not None or hi is not None:
828
+ cmd += ["-read_intervals", ("" if lo is None else f"{lo:.6f}") + "%" + ("" if hi is None else f"{hi:.6f}")]
829
+ proc = run(cmd + [path], quiet=True, check=False)
830
+ out = []
831
+ if proc.returncode != 0:
832
+ return out
833
+ if strip_adts:
834
+ try:
835
+ packets = json.loads(proc.stdout or "").get("packets") or []
836
+ except (ValueError, AttributeError):
837
+ return out
838
+ for p in packets:
839
+ pts = _packet_time(p.get("pts_time")) if isinstance(p, dict) else None
840
+ if pts is not None and p.get("data"):
841
+ out.append((pts, "CRC32:%08x" % zlib.crc32(_adts_payload(p["data"]))))
842
+ return out
843
+ for line in (proc.stdout or "").split():
844
+ fields = line.split(",")
845
+ pts = _packet_time(fields[0])
846
+ crc = next((f for f in fields[1:] if f.startswith("CRC32:")), None)
847
+ if pts is not None and crc:
848
+ out.append((pts, crc))
849
+ return out
850
+
851
+
852
+ def copied_audio_streams(meta: dict, joined: str) -> List[str]:
853
+ """The source audio streams (`a:N`) a join's sound may have been copied from: those with the
854
+ codec, channel count and sample rate of the joined file's audio. FFmpeg's default selection
855
+ copies the stream with the most channels, which need not be a:0 (a stereo AAC a:0 beside a
856
+ 6-channel PCM a:1 copied a:1), so the check must hash the stream that was copied."""
857
+ proc = run([require_tool("ffprobe"), "-v", "error", "-select_streams", "a:0", "-show_entries",
858
+ "stream=codec_name,channels,sample_rate", "-of", "json", joined], quiet=True, check=False)
859
+ try:
860
+ st = (json.loads(proc.stdout or "").get("streams") or [{}])[0] if proc.returncode == 0 else {}
861
+ shape = (st.get("codec_name"), int(st.get("channels") or 0), int(st.get("sample_rate") or 0))
862
+ except (ValueError, TypeError, AttributeError, IndexError):
863
+ return ["a:0"]
864
+ found = [f"a:{a['index']}" for a in meta.get("audio_streams") or []
865
+ if (a.get("codec"), a.get("channels") or 0, a.get("sample_rate") or 0) == shape]
866
+ return found or ["a:0"]
867
+
868
+
869
+ # check_join_audio: a run of AUDIO_RUN packets, from AUDIO_SKIP seconds into a part and starting
870
+ # within AUDIO_REACH of it, is looked for within AUDIO_SEARCH of where it belongs in the source; a
871
+ # part whose sound is more than AUDIO_SYNC_LIMIT off its picture fails the join
872
+ AUDIO_RUN, AUDIO_SKIP, AUDIO_REACH, AUDIO_SEARCH, AUDIO_SYNC_LIMIT = 8, 0.25, 2.0, 0.5, 0.005
873
+
874
+
875
+ def check_join_audio(src: str, joined: str, starts, counts, out_pts=None, streams=("a:0",),
876
+ strip_adts: bool = False) -> dict:
877
+ """Each copied part's sound against its picture in the joined file, by matching audio packets
878
+ with the source's (CRC32). A part's video moved by (its first frame in the join - its start
879
+ keyframe in the source), and its sound by (an audio packet's time in the join - the same
880
+ packet's time in the source); the two must agree within AUDIO_SYNC_LIMIT. The packet is the
881
+ first of AUDIO_RUN consecutive ones, from AUDIO_SKIP into the part, whose run appears exactly
882
+ once within AUDIO_SEARCH of where the video's move puts it. A part with no such run (digital
883
+ silence, a periodic tone, a part too short) is unmeasured, not failed. `starts` are the
884
+ parts' start keyframes (pts on the cut's clock), `counts` their video packets in the join,
885
+ `out_pts` the join's video packet times when the caller has read them. `streams` are the
886
+ source streams the sound may have come from (copied_audio_streams), tried in turn until one
887
+ measures a part; `strip_adts` hashes the source's packets without their ADTS headers.
888
+ Returns {audio_offset_ms: per part, sound minus picture (+ = sound late, null = unmeasured),
889
+ audio_parts_checked, audio_ok}. A B-frame H.264 + PCM .mov join measured 0 / +16.0 / +53.3 ms
890
+ and passed the video check; clean joins measure under 1 ms."""
891
+ out_a = audio_packet_hashes(joined)
892
+ if out_pts is None:
893
+ out_pts = stream_packet_times(joined, "v", "pts_time")
894
+ vpts = sorted(p for p in out_pts if p is not None)
895
+ if not out_a or len(vpts) != sum(counts):
896
+ return {"audio_offset_ms": None, "audio_parts_checked": 0, "audio_ok": True}
897
+ origin = file_origin(src)
898
+ offsets: list = []
899
+ for stream in streams:
900
+ offsets, first = [], 0
901
+ for k, n in zip(starts, counts):
902
+ v_out = vpts[first]
903
+ nxt = vpts[first + n] if first + n < len(vpts) else float("inf")
904
+ first += n
905
+ vshift = v_out - (k + origin)
906
+ lo = k + origin - 1.0
907
+ src_a = audio_packet_hashes(src, None if lo <= origin else lo, k + origin + AUDIO_REACH + 2 * AUDIO_SEARCH,
908
+ stream=stream, strip_adts=strip_adts)
909
+ by_hash: dict = {}
910
+ for j, (_, crc) in enumerate(src_a):
911
+ by_hash.setdefault(crc, []).append(j)
912
+ found = None
913
+ for m, (p, crc) in enumerate(out_a):
914
+ if p < v_out + AUDIO_SKIP:
915
+ continue
916
+ if p > v_out + AUDIO_REACH or m + AUDIO_RUN > len(out_a) or out_a[m + AUDIO_RUN - 1][0] >= nxt:
917
+ break
918
+ run_ = [h for _, h in out_a[m:m + AUDIO_RUN]]
919
+ hits = [j for j in by_hash.get(crc, ()) if abs(src_a[j][0] - (p - vshift)) <= AUDIO_SEARCH
920
+ and [h for _, h in src_a[j:j + AUDIO_RUN]] == run_]
921
+ if len(hits) == 1:
922
+ found = (p - src_a[hits[0]][0]) - vshift
923
+ break
924
+ offsets.append(None if found is None else round(found * 1000, 2) + 0.0)
925
+ if any(o is not None for o in offsets):
926
+ break
927
+ measured = [o for o in offsets if o is not None]
928
+ return {"audio_offset_ms": offsets, "audio_parts_checked": len(measured),
929
+ "audio_ok": all(abs(o) <= AUDIO_SYNC_LIMIT * 1000 for o in measured)}
930
+
931
+
932
+ def cut_one(src: str, start: float, end: float, dst: str, reencode: bool, crf: int, preset: str, tolerance: float = 0.5, meta: dict = None,
933
+ _reasons: List[str] = None, edit_list_ok: bool = False, copy_t: float = None) -> dict:
934
+ """Cut one segment. Returns its outcome: {reencoded, reasons, precision, start_snapped, ...}, where
935
+ `reasons` lists why THIS segment re-encoded on its own (pcm_container / copy_failed / tolerance);
936
+ the caller adds the reasons that forced every segment (requested, codec, vfr).
937
+
938
+ `edit_list_ok` (--edit-list) keeps the edit list a single MP4/MOV copy writes instead of
939
+ -avoid_negative_ts make_zero; off, the copy is cut and judged as in every 2.x release.
940
+
941
+ `copy_t` is a --segments part planned by plan_part: copied for -t copy_t (to its end
942
+ keyframe's dts), keeping the edit list an MP4/MOV copy writes, and not judged by its length
943
+ here, since plan_part judged each of its ends."""
944
+ reasons = list(_reasons or [])
945
+ dur = end - start
946
+ meta = meta or probe(src)
947
+ audio_only = is_audio_output(dst) or not meta.get("video")
948
+ if not reencode and audio_only and audio_codec_for(dst)[1].startswith("pcm") and not str((meta.get("audio") or {}).get("codec", "")).startswith("pcm"):
949
+ info(f"{(meta.get('audio') or {}).get('codec')} packets cannot be copied into a PCM container; decoding to PCM")
950
+ reencode = True
951
+ reasons.append("pcm_container")
952
+ edit_list = False
953
+ notes: List[str] = []
954
+ if reencode and os.path.splitext(dst)[1].lower() in UNWRITTEN_AUDIO_EXT:
955
+ # a .wma is written only as a stream copy of WMA sound: a copy this run judged and is about
956
+ # to re-encode (its length, a lost stream, a failed copy) is refused, not encoded into ASF,
957
+ # and the copy it wrote is removed, so a failed run leaves no file under the name (#517).
958
+ # A copy that failed wrote nothing there (run() replaces an existing path only on success),
959
+ # so the file is the caller's earlier one under --overwrite and is left
960
+ if _reasons and _reasons[-1] in ("stream_lost", "tolerance") and not STATE.dry_run and os.path.isfile(dst):
961
+ os.remove(dst) # the copy this run just wrote and judged (the recursion's last reason)
962
+ if "tolerance" in reasons:
963
+ info(f"the stream copy into {dst} is re-encoded for its length, and a .wma cannot be encoded; "
964
+ "--tolerance -1 keeps the copy as it lands")
965
+ refuse_unwritten_output(dst)
966
+ if reencode:
967
+ if is_audio_output(dst) or not meta.get("video"):
968
+ # -ss before -i seeks, then decoding discards samples up to the exact start
969
+ # (accurate_seek); atrim bounds the decoded stream to the requested length at sample
970
+ # resolution. The input seek counts from the file's start, so a sound that starts after
971
+ # it (late against its picture) arrives at its offset from `start`; it is padded with
972
+ # silence from 0, as the --segments re-cut pads it (av_trim), not rebased to its own
973
+ # first sample, which moved it earlier and made the cut shorter than asked (#462 A46)
974
+ cmd = ffmpeg_base() + ["-ss", f"{start:.6f}", "-i", src, "-t", f"{dur:.6f}"] + stream_maps(meta, dst, copy=False)
975
+ pad = PAD_SOUND_FROM_ZERO if audio_codec_for(dst)[1] == "flac" else "aresample=async=1:first_pts=0"
976
+ cmd += ["-af", f"atrim=end={dur:.6f},{pad}"]
977
+ else:
978
+ # Seek SEEK_MARGIN early, then drop the margin on the output side, which decodes and
979
+ # discards it from both streams alike. An input seek straight to `start` can land (the
980
+ # MP4 demuxer seeks over its raw decode times) on a keyframe whose picture comes after
981
+ # `start` and lose the frames before it (-ss 9.9 on a B-frame HEVC file began at 10.0).
982
+ m = min(SEEK_MARGIN, start)
983
+ cmd = ffmpeg_base() + ["-ss", f"{start - m:.6f}", "-i", src, "-ss", f"{m:.6f}", "-t", f"{dur:.6f}"]
984
+ cmd += stream_maps(meta, dst, copy=False)
985
+ # a VFR source is conformed by the fps filter at the rate cfr_args() delivers: the
986
+ # encoder line's -fps_mode cfr alone let a frame run up to two frames late (#512). Its
987
+ # grid is laid from the output-side seek, so the cut lands on a slot (#538)
988
+ cmd += ["-vf", cfr_filter(meta, seek=m)] if cfr_filter(meta) else []
989
+ # ffmpeg's default stream selection also picks one subtitle stream; a re-encode cannot
990
+ # trim it (the cues kept their timestamps and the container grew to 2 s for a 1 s cut,
991
+ # sweep F2), so the re-encode carries video/audio only and the result says so
992
+ cmd += ["-sn", "-dn"]
993
+ if meta.get("subtitle_streams") or meta.get("data_streams"):
994
+ DROPPED_STREAMS.append(dst)
995
+ cmd += encode_args(meta, dst, crf, preset)
996
+ if audio_only:
997
+ # asetpts already starts the samples at 0. make_zero is what folds the encoder's
998
+ # priming into the container length, which is the delay precision codec_frame reports.
999
+ # A video re-encode must not take it (#336): the earliest timestamp is that priming,
1000
+ # or a negative B-frame decode time, so make_zero starts the picture after 0 and
1001
+ # leaves the sound at 0. fit --fps then drops or repeats a frame. Without the shift
1002
+ # a start on a frame has that frame at 0. A start between frames begins on the next
1003
+ # frame and may keep up to one frame of timestamp; moving the picture alone would
1004
+ # leave the sound that far ahead. An MP4/MOV edit list hides the priming, and a
1005
+ # source whose audio starts late keeps that offset.
1006
+ cmd += ["-avoid_negative_ts", "make_zero"]
1007
+ cmd += [dst]
1008
+ elif audio_only:
1009
+ # output-side seek: an input seek on a video file lands on the previous video keyframe and on
1010
+ # FLAC/MP3 on a coarse index; reading from the start and dropping packets is exact to the packet
1011
+ cmd = (ffmpeg_base() + ["-i", src, "-ss", f"{start:.6f}", "-t", f"{dur:.6f}"] + stream_maps(meta, dst, copy=True)
1012
+ + copy_args(meta, dst) + ["-avoid_negative_ts", "make_zero", dst])
1013
+ else:
1014
+ # With --edit-list a single MP4/MOV output keeps the edit list the plain copy writes: the
1015
+ # keyframe's pre-roll is stored but hidden, so the picture and the sound start at `start`.
1016
+ # make_zero (the default, as in every 2.x release) shifts the timestamps instead and shows
1017
+ # the pre-roll -- on Core Media HEVC, 3.7 s of sound with no picture from a run that exited
1018
+ # 0, which av_start_skew_seconds and a note report. A planned concat part keeps it: the concat
1019
+ # demuxer ignores where the edit list starts (it shows the pre-roll) but places the next
1020
+ # part by its length, which make_zero parts got wrong by the B-frame reorder delay.
1021
+ # Other concat parts (Matroska, MPEG-TS) keep make_zero.
1022
+ edit_list = (edit_list_ok or copy_t is not None) and os.path.splitext(dst)[1].lower() in EDIT_LIST_EXTS
1023
+ cmd = (ffmpeg_base() + ["-ss", f"{start:.6f}", "-i", src, "-t", f"{dur if copy_t is None else copy_t:.6f}"]
1024
+ + stream_maps(meta, dst, copy=True) + copy_args(meta, dst)
1025
+ + ([] if edit_list else ["-avoid_negative_ts", "make_zero"]) + [dst])
1026
+ if not audio_only and (meta.get("timecode") or {}).get("value"):
1027
+ cmd[-1:-1] = output_timecode_args(meta, first_frame_from(src, meta, start, reencode, edit_list and copy_t is None),
1028
+ delivered_rate(meta) if reencode else None)
1029
+ proc = run(cmd, check=False)
1030
+ if proc.returncode != 0:
1031
+ if not reencode:
1032
+ fail_if_classified(proc) # a full disk fails the re-encode too: its error, not a retry (#415)
1033
+ info("stream copy failed, falling back to re-encode")
1034
+ return cut_one(src, start, end, dst, True, crf, preset, tolerance, meta, reasons + ["copy_failed"], edit_list_ok)
1035
+ die(f"ffmpeg failed:\n{proc.stderr.strip()}", kind="ffmpeg", **ffmpeg_failure_extra(proc.stderr))
1036
+ out_meta = probe(dst) if not reencode and not STATE.dry_run and copy_t is None else None
1037
+ if out_meta is not None:
1038
+ # #367: a copy from MPEG-TS whose window holds no video keyframe writes no video at all
1039
+ # (the TS demuxer does not seek back to one, as the MP4 demuxer does), and ffmpeg exits 0
1040
+ lost = [k for k in ("video", "audio") if meta.get(k) and not out_meta.get(k) and not (k == "video" and audio_only)]
1041
+ if lost:
1042
+ info(f"the stream copy wrote no {' or '.join(lost)} stream (no keyframe to start it from); "
1043
+ "re-encoding this segment")
1044
+ return _with_notes(cut_one(src, start, end, dst, True, crf, preset, tolerance, meta, reasons + ["stream_lost"],
1045
+ edit_list_ok), notes)
1046
+ if out_meta is not None and tolerance >= 0:
1047
+ got = out_meta.get("duration") or 0.0
1048
+ vdur, fps = (out_meta.get("video") or {}).get("duration"), (meta.get("video") or {}).get("fps")
1049
+ if edit_list and not audio_only and vdur and fps and abs(got - vdur) > 1.0 / fps:
1050
+ # the container's length counts the longer track; the tolerance is about the picture.
1051
+ # Only under --edit-list: the default judges the container, as every 2.x release did
1052
+ msg = f"the container is {got:.3f}s but its video {vdur:.3f}s; the cut was judged by the video"
1053
+ info(msg)
1054
+ notes.append(msg)
1055
+ got = vdur
1056
+ if abs(got - dur) >= tolerance and edit_list and (copy_presentation(start, seek_keyframe(src, start), True, fps)["stored_preroll_seconds"] is not None):
1057
+ # the edit list started the picture at `start`: only the END is off (it lands on a
1058
+ # packet boundary), and no other --start would change that
1059
+ info(f"the stream copy starts where asked but its end landed {got - dur:+.2f}s from the requested "
1060
+ f"length (> {tolerance:.2f}s tolerance); re-encoding this segment for accuracy")
1061
+ return _with_notes(cut_one(src, start, end, dst, True, crf, preset, tolerance, meta, reasons + ["tolerance"], edit_list_ok), notes)
1062
+ if abs(got - dur) >= tolerance: # a snap of exactly the tolerance is not "within" it (sweep F20)
1063
+ near = keyframes_near(src, start)
1064
+ alt = ""
1065
+ if near:
1066
+ closest = min(near, key=lambda k: abs(k - start))
1067
+ alt = (f"; for a lossless cut move --start to a keyframe (nearest: {closest:.3f}s"
1068
+ + (f", others within 5 s: {', '.join(f'{k:.3f}' for k in near if k != closest)}" if len(near) > 1 else "") + ")")
1069
+ NEAREST_KEYFRAMES.extend(k for k in near if k not in NEAREST_KEYFRAMES)
1070
+ info(f"stream copy landed on a keyframe {abs(got - dur):.2f}s away from the requested cut "
1071
+ f"(> {tolerance:.2f}s tolerance); re-encoding this segment for accuracy{alt}")
1072
+ return _with_notes(cut_one(src, start, end, dst, True, crf, preset, tolerance, meta, reasons + ["tolerance"], edit_list_ok), notes)
1073
+ if audio_only and not reencode:
1074
+ # an audio-only copy is judged by its written length too (above): a dry run that wrote
1075
+ # nothing says a real run may still re-encode it (#510 review)
1076
+ pending = {"length_unjudged": True} if (STATE.dry_run and copy_t is None and tolerance >= 0) else {}
1077
+ if pending and os.path.splitext(dst)[1].lower() in UNWRITTEN_AUDIO_EXT:
1078
+ notes.append(f"a run judges the copy by its written length: one that comes out --tolerance or more off "
1079
+ f"is refused (output_extension_unsupported), since a .wma cannot be encoded; --tolerance -1 "
1080
+ "keeps the copy as it lands")
1081
+ lead = copied_lead(meta, start, end)
1082
+ if lead:
1083
+ # a copy cannot add silence: the sound starts at its first packet, `lead` earlier than it
1084
+ # sat after `start` (#515). Kept within --tolerance, as a start that snapped is, and said.
1085
+ # A dry run says it for a lead of --tolerance or more too: the run judges the written
1086
+ # length, which is short by up to a packet less than the lead (0.351 s for a lead of
1087
+ # 0.355), so it may keep that copy; it re-encodes and pads it otherwise (#542 review)
1088
+ unsure = STATE.dry_run and 0 <= tolerance <= lead
1089
+ notes.append(f"the sound starts {lead:.3f}s after {start:.3f}s in the source; a stream copy cannot "
1090
+ f"add silence, so the extraction starts with the sound, {lead:.3f}s early against the "
1091
+ "picture (--accurate pads it from the start"
1092
+ + ("; a run re-encodes and pads it instead when the copy comes out --tolerance or more short)" if unsure else ")"))
1093
+ return _outcome(meta, dst, False, reasons, notes=notes, audio_lead_dropped_seconds=lead or None, **pending)
1094
+ if reencode:
1095
+ return _outcome(meta, dst, reencode, reasons)
1096
+ if STATE.dry_run:
1097
+ # the planned copy: whether it keeps an edit list is known; where it lands is not, so a
1098
+ # real run that judges the written copy by its length may still re-encode it (#510)
1099
+ return _outcome(meta, dst, False, reasons, edit_list=edit_list and edit_list_ok, start_snapped=None,
1100
+ length_unjudged=copy_t is None and tolerance >= 0)
1101
+ fps = (meta.get("video") or {}).get("fps")
1102
+ # a concat part's edit list does not hide its pre-roll in the join, so it presents from the keyframe
1103
+ shown = edit_list and edit_list_ok
1104
+ key = seek_keyframe(src, start)
1105
+ return _outcome(meta, dst, False, reasons, edit_list=shown, notes=notes, landed_pts=key[0] if key else None,
1106
+ **copy_presentation(start, key, shown, fps))
1107
+
1108
+
1109
+ # The most segments one fallback ffmpeg call opens: every segment is its own input (a file handle,
1110
+ # a demuxer and a decoder each), and macOS shells default to 256 open files.
1111
+ JOIN_CHUNK = 32
1112
+ # Seconds of fade on each side of every --segments join the re-encode makes (--declick-ms / --no-declick).
1113
+ # Butting two cuts together leaves a step in the waveform wherever they were not both at zero, which
1114
+ # plays as a click: measured on a 440 Hz tone, the step at the join was 14x the tone's own largest
1115
+ # sample-to-sample change. A 20 ms fade is too short to hear as a dip and long enough to remove it.
1116
+ DECLICK_S = 0.02
1117
+ # codecs whose configuration travels in the packets, so a part with no extradata is not missing any
1118
+ _PARTS: dict = {}
1119
+
1120
+
1121
+ def _part_probe(path: str):
1122
+ """ffprobe's streams and format of a cut part, with extradata hashes; None when it cannot be
1123
+ read. One probe per part serves join_signature and predicted_join_steps."""
1124
+ if path not in _PARTS:
1125
+ proc = run([require_tool("ffprobe"), "-v", "error", "-show_data_hash", "sha256", "-show_streams", "-show_format",
1126
+ "-of", "json", path], quiet=True, check=False)
1127
+ try:
1128
+ doc = json.loads(proc.stdout or "") if proc.returncode == 0 else None
1129
+ except ValueError:
1130
+ doc = None
1131
+ _PARTS[path] = doc if isinstance(doc, dict) and isinstance(doc.get("streams"), list) else None
1132
+ return _PARTS[path]
1133
+
1134
+
1135
+ def join_signature(path: str):
1136
+ """What a stream-copy join needs to be identical across parts (_common.probe.stream_signature).
1137
+ None when ffprobe cannot read the part."""
1138
+ doc = _part_probe(path)
1139
+ return None if doc is None else stream_signature(doc)
1140
+
1141
+
1142
+ # how far a measured join step may be from the predicted one: ffprobe prints the parts' times
1143
+ # to the microsecond, and a time base coarser than that (Matroska's 1 ms) rounds each of them
1144
+ JOIN_STEP_SLACK = 0.001
1145
+
1146
+
1147
+ def predicted_join_steps(parts) -> list:
1148
+ """For each join of `parts`, the presentation step from the last frame of one part to the
1149
+ first of the next, as the concat demuxer places them: the next part starts where this one's
1150
+ container ends, so the step is (this part's container end - its last frame's pts) + (the next
1151
+ part's first frame's pts - its container start), read from the parts' own packets (Matroska
1152
+ stores no stream durations). None for a join whose parts' times are unknown. On an exact
1153
+ no-B-frame join (0-1.8,4-6 at 30 fps) that is 33.3 + 13.3 + 10.0 = 56.7 ms, what the joined
1154
+ file showed."""
1155
+ def times(path):
1156
+ doc = _part_probe(path)
1157
+ pts = [p for p in stream_packet_times(path, "v", "pts_time") if p is not None]
1158
+ try:
1159
+ fmt = (doc or {}).get("format") or {}
1160
+ c_start, c_dur = float(fmt["start_time"]), float(fmt["duration"])
1161
+ except (KeyError, TypeError, ValueError):
1162
+ return None
1163
+ return (c_start, c_start + c_dur, min(pts), max(pts)) if pts else None
1164
+ spans = [times(p) for p in parts]
1165
+ return [None if a is None or b is None else (a[1] - a[3]) + (b[2] - b[0]) for a, b in zip(spans, spans[1:])]
1166
+
1167
+
1168
+ def _fraction_rate(text: str) -> float:
1169
+ """"30000/1001" or "30" as a number."""
1170
+ num, _, den = str(text).partition("/")
1171
+ return float(num) / float(den or 1)
1172
+
1173
+
1174
+ # the first frame at or after t on the source's grid; shared with the tools that cut both streams
1175
+ # on one set of bounds (#409)
1176
+
1177
+
1178
+ def _join_chunk(src: str, segments: List[Tuple[float, float]], dst: str, meta: dict, crf: int, preset: str,
1179
+ has_v: bool, intermediate: bool = False, vend=None, hold=frozenset(), first: int = 0,
1180
+ total=None) -> List[str]:
1181
+ """Re-cut `segments` from the source into one file through the concat filter, returning the codec
1182
+ arguments it encoded with. Each segment is
1183
+ its own seeked input, so both of its streams start at the segment's origin (0); neither is
1184
+ rebased on its own, which would drop a real A/V offset -- the audio is padded to the origin
1185
+ instead. Both streams are cut to the same length so the next segment starts where this ends.
1186
+
1187
+ An `intermediate` chunk keeps its audio as PCM, so the chunks join with no encoder priming
1188
+ between them and the audio is encoded once, for the final file."""
1189
+ has_a = bool(meta.get("audio"))
1190
+ cmd = ffmpeg_base()
1191
+ graph, pads = [], ""
1192
+ video = meta.get("video") or {}
1193
+ rate_arg = video.get("r_frame_rate") if has_v else None
1194
+ try:
1195
+ rate = _fraction_rate(rate_arg) if rate_arg else (video.get("fps") or 0.0)
1196
+ except (ValueError, ZeroDivisionError):
1197
+ rate = video.get("fps") or 0.0
1198
+ v0 = (video.get("start_time") or 0.0) - file_origin(src) if has_v and rate else 0.0
1199
+ for i, (s, e) in enumerate(segments):
1200
+ d = e - s
1201
+ # Seek SEEK_MARGIN early and trim to the exact start. The MP4 demuxer seeks over its raw
1202
+ # decode times, so a start just before a keyframe (within the B-frame reorder delay) can
1203
+ # land on that keyframe and lose its leading frames -- measured: -ss 9.9 on a keyint-60
1204
+ # HEVC file began at 10.0 (seek_keyframe measures where a copy lands). Likewise an input -t stops reading at s+d in decode order and would drop
1205
+ # B-frames that display inside the segment, so it reads a second past the end.
1206
+ # -reinit_filter 0: every input is the same file, so the graph keeps the format it was
1207
+ # configured with. A later input that decodes across a mid-stream colour-tag change (an
1208
+ # in-band SPS going from untagged to bt470bg, say) made FFmpeg 8.1 rebuild the graph at
1209
+ # that input's buffer source and deadlock at 0% CPU (#316); the output's colour tags are
1210
+ # written explicitly (video_args), so the retag is a label here, not a conversion.
1211
+ m = min(SEEK_MARGIN, s)
1212
+ cmd += ["-ss", f"{s - m:.6f}", "-t", f"{m + d + 1.0:.6f}", "-reinit_filter", "0", "-i", src]
1213
+ a, b, half = m, m + d, 0.0
1214
+ if has_v and rate:
1215
+ # Both streams are cut on the source's frame grid: from the first frame at or after the
1216
+ # start to the first at or after the end, which are the frames the segment holds. A
1217
+ # segment starting between frames otherwise placed its pictures half a frame off the
1218
+ # output's grid, and the constant-rate output duplicated one (65 frames for 64 on
1219
+ # FFmpeg 6.1). The video trim sits half a frame before each grid point, so no FFmpeg
1220
+ # version rounds a frame on the boundary in or out.
1221
+ a = m + (grid_at_or_after(s, v0, rate) - s)
1222
+ b = m + (grid_at_or_after(e, v0, rate) - s)
1223
+ half = 0.5 / rate
1224
+ # both streams shift by the same constant, so an offset between them (audio that starts
1225
+ # late) survives; the audio is then padded to the segment's origin
1226
+ if has_v:
1227
+ # a segment that runs past the video's end holds its last frame for the sound (main()
1228
+ # has already ended one that ran less than a frame past it at the video's end): the
1229
+ # concat filter starts the next segment after the longer stream, so a short picture
1230
+ # would leave a hole in the video there
1231
+ pad = f"tpad=stop_mode=clone:stop_duration={e - vend + 1.0:.6f}," if first + i in hold else ""
1232
+ graph.append(f"[{i}:{PROBED_VIDEO}]{pad}trim=start={a - half:.6f}:end={b - half:.6f},setpts=PTS-{a:.6f}/TB[v{i}]")
1233
+ pads += f"[v{i}]"
1234
+ if has_a:
1235
+ # fade only the sides that meet another segment: the file's own start and end stay as cut
1236
+ n = first + i
1237
+ fade = min(DECLICK_S, (b - a) / 2)
1238
+ fades = ""
1239
+ if fade > 0 and n > 0:
1240
+ fades += f",afade=t=in:st=0:d={fade:.6f}"
1241
+ if fade > 0 and n < (len(segments) if total is None else total) - 1:
1242
+ fades += f",afade=t=out:st={b - a - fade:.6f}:d={fade:.6f}"
1243
+ graph.append(f"[{i}:{PROBED_AUDIO}]atrim=start={a:.6f}:end={b:.6f},asetpts=PTS-{a:.6f}/TB,"
1244
+ f"aresample=async=1:first_pts=0{fades}[a{i}]")
1245
+ pads += f"[a{i}]"
1246
+ outs = ("[v]" if has_v else "") + ("[a]" if has_a else "")
1247
+ graph.append(f"{pads}concat=n={len(segments)}:v={int(has_v)}:a={int(has_a)}{outs}")
1248
+ # a VFR source is conformed by the fps filter after the concat, at the rate cfr_args() delivers
1249
+ # (#512); a constant-rate source's graph is unchanged
1250
+ fc, vpad = graph_with_cfr(";".join(graph), "[v]", meta) if has_v else (";".join(graph), None)
1251
+ cmd += ["-filter_complex", fc]
1252
+ for pad in (vpad, "[a]" if has_a else None):
1253
+ if pad:
1254
+ cmd += ["-map", pad]
1255
+ if intermediate:
1256
+ codec = (video_encode_args(meta, crf, preset) if has_v else ["-vn"]) + ["-c:a", "pcm_s24le"]
1257
+ else:
1258
+ codec = encode_args(meta, dst, crf, preset)
1259
+ # the source's rate, stated: FFmpeg 7.0 encoded the trimmed, concatenated pictures at 25 fps
1260
+ # and dropped frames to fit (98 frames for 117 at 30 fps)
1261
+ rate_out = ["-r", rate_arg] if has_v and rate_arg and rate and "-r" not in codec else []
1262
+ # a join's frames after the first range are not the source's next frames: no start timecode
1263
+ # labels them, so the output carries none (a single range's cut moves it to its first frame)
1264
+ if not intermediate:
1265
+ # the chapters land where their ranges do (#696): FFmpeg kept the source's times
1266
+ cmd = with_mapped_chapters(cmd, meta, segments_map(segments), None)
1267
+ cmd += ["-sn", "-dn"] + codec + rate_out + ([] if intermediate or not has_v else output_timecode_args(meta, None)) + [dst]
1268
+ run(cmd)
1269
+ return codec
1270
+
1271
+
1272
+ def join_from_source(src: str, segments: List[Tuple[float, float]], dst: str, meta: dict, crf: int, preset: str, tmp: str) -> None:
1273
+ """The join fallback: every segment re-cut from the source and encoded once. The parts are not
1274
+ reused -- a copied part carries keyframe pre-roll and an audio tail the concat filter would
1275
+ turn into a gap, and a re-encode keeps nothing lossless anyway."""
1276
+ if meta.get("subtitle_streams") or meta.get("data_streams"):
1277
+ DROPPED_STREAMS.append(dst)
1278
+ has_v = bool(meta.get("video")) and not is_audio_output(dst)
1279
+ vend = video_end(src, meta) if has_v else None
1280
+ # the segments whose picture ends before their sound; the last one is left as the source had it,
1281
+ # since no join follows it
1282
+ # (by position: a repeat of a held segment in last place is still the last one)
1283
+ hold = frozenset(k for k, (_, e) in enumerate(segments[:-1]) if vend is not None and e > vend + 1e-6)
1284
+ if len(segments) <= JOIN_CHUNK:
1285
+ _join_chunk(src, segments, dst, meta, crf, preset, has_v, vend=vend, hold=hold)
1286
+ return
1287
+ ext = os.path.splitext(dst)[1].lower() or ".mp4" # IMG_0001.MOV is a .mov
1288
+ # Matroska chunks with PCM audio: no edit lists and no AAC priming to carry into the join (MP4
1289
+ # chunks measured the video 23 ms late against the audio after a copy concat)
1290
+ # the chunks' codec tag (hvc1), which a stream copy out of Matroska does not carry into an MP4
1291
+ # (it writes hev1, which Apple players refuse)
1292
+ tag: List[str] = []
1293
+
1294
+ def encode_chunks() -> List[str]:
1295
+ out = []
1296
+ for k in range(0, len(segments), JOIN_CHUNK):
1297
+ chunk = os.path.join(tmp, f"chunk{k // JOIN_CHUNK:03d}.mkv")
1298
+ args = _join_chunk(src, segments[k:k + JOIN_CHUNK], chunk, meta, crf, preset, has_v, intermediate=True,
1299
+ vend=vend, hold=hold, first=k, total=len(segments)) or []
1300
+ if "-tag:v" in args:
1301
+ tag[:] = args[args.index("-tag:v"):args.index("-tag:v") + 2]
1302
+ out.append(chunk)
1303
+ return out
1304
+
1305
+ chunks = encode_chunks()
1306
+ if not STATE.dry_run and STATE.hw and not signatures_match([join_signature(c) for c in chunks], ".mkv"):
1307
+ # VideoToolbox refused some chunk and run() re-encoded that one on the CPU, so the chunks
1308
+ # no longer match: encode them all on the CPU rather than refuse a join that can be made
1309
+ info("the GPU refused part of this join and the chunks came out mixed; re-encoding every chunk on the CPU")
1310
+ STATE.hw_notes.append("the --segments join fell back to the CPU for every chunk after VideoToolbox refused one")
1311
+ # off for these encodes only: the result still reports that the GPU was asked for
1312
+ STATE.hw = False
1313
+ try:
1314
+ chunks = encode_chunks()
1315
+ finally:
1316
+ STATE.hw = True
1317
+ if not STATE.dry_run and not signatures_match([join_signature(c) for c in chunks], ".mkv"):
1318
+ die("the re-encoded chunks of this join came out with different stream parameters, so they "
1319
+ f"cannot be joined safely; cut at most {JOIN_CHUNK} segments per run and join the results "
1320
+ "with join.py", kind="ffmpeg")
1321
+ listfile = os.path.join(tmp, "chunks.txt")
1322
+ with open(listfile, "w", encoding="utf-8") as fh:
1323
+ for c in chunks:
1324
+ fh.write(concat_list_line(c) + "\n")
1325
+ audio = [] if not meta.get("audio") else (aac_args() if has_v else audio_codec_for(dst))
1326
+ run(with_mapped_chapters(ffmpeg_base() + ["-f", "concat", "-safe", "0", "-i", listfile], meta, segments_map(segments), None)
1327
+ + (["-c:v", "copy"] + (tag if ext in (".mp4", ".mov", ".m4v") else []) if has_v else ["-vn"]) + audio
1328
+ + (["-movflags", "+faststart"] if ext in (".mp4", ".mov", ".m4v") and has_v else [])
1329
+ + (output_timecode_args(meta, None) if has_v else []) + [dst])
1330
+
1331
+
1332
+ BEAT_RATE = 22050 # the decode rate the onset pass uses, matching scenes.py --beats
1333
+
1334
+
1335
+ def _grid_from_source(path: str, min_confidence: float, named: bool = False) -> "dict":
1336
+ """The beat grid of `path`: a scenes.py --json document if that is what it is, otherwise a
1337
+ media file to measure. Reading a document is how a caller avoids a second decode."""
1338
+ try:
1339
+ doc = read_json(path) # a media file is not UTF-8 or not JSON: a ValueError, then measured
1340
+ except JsonTooDeep as exc:
1341
+ die(f"--snap-source {path}: {exc}", kind="input")
1342
+ except (OSError, ValueError):
1343
+ doc = None
1344
+ if isinstance(doc, dict) and doc.get("beat_grid"):
1345
+ if not isinstance(doc["beat_grid"], dict) or not isinstance(doc.get("beats") or [], list):
1346
+ die(f"--snap-source {path}: beat_grid must be an object and beats a list "
1347
+ "(regenerate it with `scenes.py MUSIC --beats --json`)", kind="input")
1348
+ grid = dict(doc["beat_grid"])
1349
+ grid["beats"] = doc.get("beats") or []
1350
+ # A scenes.py document carries the supported subset since 1.17; one written by an older
1351
+ # build does not, and a grid whose supported points are unknown is not one this tool may
1352
+ # move a cut onto -- an unknown subset is not an empty one, but it is not a measurement
1353
+ # either, so it is refused rather than silently treated as "all of them".
1354
+ grid["supported_beats"] = doc.get("beat_grid", {}).get("supported_beats")
1355
+ if grid["supported_beats"] is None:
1356
+ grid["supported_beats"] = doc.get("supported_beats")
1357
+ try:
1358
+ tempo = grid.get("tempo_bpm")
1359
+ grid["tempo_bpm"] = float(tempo) if tempo is not None else None
1360
+ grid["confidence"] = float(grid.get("confidence") or 0.0)
1361
+ except (TypeError, ValueError):
1362
+ die(f"--snap-source {path}: beat_grid.tempo_bpm and .confidence must be numbers "
1363
+ "(regenerate it with `scenes.py MUSIC --beats --json`)", kind="input")
1364
+ if grid["beats"] and grid["tempo_bpm"] is None:
1365
+ die(f"--snap-source {path}: this document lists beats but no tempo_bpm, so no grid "
1366
+ "was actually measured in it. Regenerate it with "
1367
+ "`scenes.py MUSIC --beats --json`.", kind="input")
1368
+ grid["usable"] = grid["confidence"] >= min_confidence
1369
+ return grid
1370
+ if isinstance(doc, dict):
1371
+ die(f"--snap-source {path}: this JSON has no beat_grid -- produce one with "
1372
+ "`scenes.py MUSIC --beats --json`", kind="input")
1373
+ if doc is not None:
1374
+ die(f"--snap-source {path}: this JSON is not a scenes.py document (it is a {type(doc).__name__}, "
1375
+ "not an object with beat_grid) -- produce one with `scenes.py MUSIC --beats --json`", kind="input")
1376
+ samples = decode_pcm_mono(path, BEAT_RATE, check=False)
1377
+ if not samples and named:
1378
+ # not "no reliable beat grid in this audio": nothing was decoded, so nothing was measured (#404)
1379
+ die(f"--snap-source {path}: no audio could be decoded from it, and it is not a scenes.py --beats --json "
1380
+ "document, so no beat grid was measured", kind="input",
1381
+ hint="pass the music bed (a media file with sound) or the JSON `scenes.py MUSIC --beats --json` prints")
1382
+ block = max(1, int(round(BEAT_RATE * 0.01)))
1383
+ env = rms_envelope(samples, block)
1384
+ # the envelope's real step is block / rate (220 / 22050 = 9.977 ms), not the 10 ms asked for:
1385
+ # timing the onsets at 10 ms stretched the grid 0.23 % (68 ms over 30 s) -- see scenes.py
1386
+ return beat_grid(env, block / BEAT_RATE, min_confidence=min_confidence)
1387
+
1388
+
1389
+ def snap_segments(args, segments, meta, total):
1390
+ """Move every in/out point to the nearest measured beat. Returns (result dict, segments).
1391
+
1392
+ A cut point may move to a measured, onset-supported grid point and may not appear from one:
1393
+ the number of segments is unchanged, and nothing is ever proposed. The keyframe/tolerance
1394
+ decision downstream then runs on the snapped values, which is the right order -- whether a cut
1395
+ can be lossless depends on where it actually lands.
1396
+ """
1397
+ source = args.snap_source or args.input
1398
+ if not args.snap_source and not meta.get("audio"):
1399
+ die("--snap beats needs audio to measure a beat in; this file has none. Cut without it "
1400
+ "(--snap none), or pass --snap-source with the music bed.", kind="input")
1401
+ # Compare the PARSED segments against the whole file, not the raw --start string: "0:00",
1402
+ # "0.0" and "00:00:00" are all a zero start that a string comparison lets through, and the
1403
+ # run would then snap the implicit end point and silently shorten a whole-file copy.
1404
+ whole_file = (len(segments) == 1 and abs(segments[0][0]) < 1e-6
1405
+ and (not total or abs(segments[0][1] - total) < 1e-6))
1406
+ if whole_file:
1407
+ die("--snap beats has no in or out point to move: this run copies the whole file. Give "
1408
+ "--start/--end (or --segments), or drop --snap.", kind="input")
1409
+ # A floor of zero would make the confidence check vacuous -- a grid measured from noise scores
1410
+ # above 0.0 and would pass -- and the whole point of the flag is that a cut only moves onto a
1411
+ # pulse somebody can hear. The number is a floor on belief, so it must be a positive one.
1412
+ if args.min_confidence <= 0:
1413
+ die("--min-confidence must be greater than 0: at 0 every grid is 'reliable', including "
1414
+ "one measured from noise, which is exactly what --snap beats must not cut to. Use "
1415
+ "--snap none if you do not want the points moved at all.", kind="input")
1416
+ grid = _grid_from_source(source, args.min_confidence, named=bool(args.snap_source))
1417
+ confidence = float(grid.get("confidence") or 0.0)
1418
+ tempo = grid.get("tempo_bpm")
1419
+ if confidence < args.min_confidence or not grid.get("beats"):
1420
+ die(f"no reliable beat grid in this audio (confidence {confidence:.2f}, needs "
1421
+ f"{args.min_confidence:.2f}): cutting to invented beats would move your in/out points "
1422
+ "to times nothing in the audio supports. Re-run with --snap none, or pass "
1423
+ "--snap-source from a music bed.", kind="input")
1424
+ # THE grid a cut may move onto is the onset-supported subset, never the full regular grid.
1425
+ # beat_grid() reports a regular grid over the whole duration by design -- a grid has to be
1426
+ # regular -- so it runs on through a passage with no music in it. Snapping to one of those
1427
+ # points moves a cut to a time nothing in the audio marks, which is the fabrication this
1428
+ # release forbids and which this tool's own refusal text promises it does not do.
1429
+ supported = grid.get("supported_beats")
1430
+ if supported is None:
1431
+ die(f"--snap-source {source}: this document does not say which grid points a measured "
1432
+ "onset supports, so there is no way to tell a beat from a gap in it. Regenerate it "
1433
+ "with `scenes.py MUSIC --beats --json`.", kind="input")
1434
+ if not supported:
1435
+ die(f"no measured onset supports any point of this beat grid (confidence "
1436
+ f"{confidence:.2f}): the grid is regular but nothing in the audio marks it, so every "
1437
+ "move would be to an invented time. Re-run with --snap none, or pass --snap-source "
1438
+ "from a music bed.", kind="input")
1439
+ points = [t for seg in segments for t in seg]
1440
+ moved = snap_points(points, supported, args.snap_tolerance)
1441
+ out_segments = []
1442
+ for i in range(0, len(moved), 2):
1443
+ s, e = moved[i]["to"], moved[i + 1]["to"]
1444
+ if e <= s: # a snap that would collapse the segment is not applied to it
1445
+ s, e = moved[i]["from"], moved[i + 1]["from"]
1446
+ moved[i].update({"to": s, "delta": 0.0, "snapped": False, "beat_index": None})
1447
+ moved[i + 1].update({"to": e, "delta": 0.0, "snapped": False, "beat_index": None})
1448
+ out_segments.append((s, e))
1449
+ snapped = sum(1 for m in moved if m["snapped"])
1450
+ for m in moved:
1451
+ if m["snapped"]:
1452
+ info(f"--snap beats: {m['from']:.3f}s -> {m['to']:.3f}s ({m['delta'] * 1000:+.0f} ms)")
1453
+ info(f"--snap beats: {tempo:.1f} BPM, confidence {confidence:.2f}; {snapped} of {len(moved)} "
1454
+ f"point(s) moved, within {args.snap_tolerance:.3f}s, onto {len(supported)} of "
1455
+ f"{len(grid['beats'])} grid point(s) a measured onset supports")
1456
+ return ({"mode": "beats", "tolerance": args.snap_tolerance, "confidence": confidence,
1457
+ "tempo_bpm": tempo, "grid": "supported", "grid_points": len(supported),
1458
+ "moved": [dict(m) for m in moved], "snapped": snapped,
1459
+ "unchanged": len(moved) - snapped,
1460
+ "source": "measured" if not args.snap_source else args.snap_source},
1461
+ out_segments)
1462
+
1463
+
1464
+ @contextlib.contextmanager
1465
+ def _join_workspace():
1466
+ """A --segments copy join's workspace: a temp directory for its parts, and a list of the files
1467
+ it writes beside the output (the checked join, renamed into place when it passes), removed
1468
+ whatever happens."""
1469
+ temps: List[str] = []
1470
+ try:
1471
+ with tempfile.TemporaryDirectory(prefix="ffskill_cut_") as tmp:
1472
+ yield tmp, temps
1473
+ finally:
1474
+ for path in temps:
1475
+ try:
1476
+ os.remove(path)
1477
+ except OSError:
1478
+ pass
1479
+
1480
+
1481
+ def run_smart(args, segments, output: str, meta: dict, forced: List[str], hold_needed: bool, total: float) -> dict:
1482
+ """--smart: the keyframe-aware cut (_smartcut), written beside the output and moved into place once
1483
+ verified. Returns the `smart` document; {applied: false, reason, reason_code} when it could not be
1484
+ made or did not verify, and the caller re-encodes the whole cut."""
1485
+ import _smartcut
1486
+
1487
+ def fallback(reason: str, code: str) -> dict:
1488
+ return {"applied": False, "reason": reason, "reason_code": code}
1489
+
1490
+ # an existing output is refused before the parts are rendered and checked, not at placement
1491
+ refuse_existing_outputs([output])
1492
+ video = meta.get("video") or {}
1493
+ if not video or is_audio_output(output):
1494
+ return fallback("the cut has no picture to copy (an audio output or an audio-only source)", "no_video")
1495
+ if dry_run_input_pending(args.input):
1496
+ return fallback("the input does not exist yet, so its keyframes cannot be read", "pending_input")
1497
+ for why in forced:
1498
+ if why in ("vfr", "vfr_inconclusive"):
1499
+ return fallback("the source's frame timing is variable or could not be measured; a copy of it cannot be "
1500
+ "placed frame-accurately", "vfr")
1501
+ if why == "codec":
1502
+ return fallback("--codec asks for another codec, so nothing can be copied", "codec")
1503
+ if hold_needed:
1504
+ return fallback("a segment runs past the end of the video, and only a re-encode can hold its last frame",
1505
+ "hold")
1506
+ if meta.get("audio") and len(segments) > JOIN_CHUNK:
1507
+ # the sound of every segment is one input of the join command; past this many the command
1508
+ # line can outgrow Windows' limit, and the full re-encode joins in chunks of this size
1509
+ return fallback(f"{len(segments)} segments with sound: the smart join takes at most {JOIN_CHUNK}, the "
1510
+ "full re-encode joins them in chunks", "segments")
1511
+ ext = os.path.splitext(output)[1].lower() or ".mp4"
1512
+ params = _smartcut.stream_params(args.input)
1513
+ bad = _smartcut.ineligible(params, meta, ext)
1514
+ if bad:
1515
+ return fallback(*bad)
1516
+ packets = video_packets(args.input, segments, 0.5, total)
1517
+ if not packets:
1518
+ return fallback("the source's video packets could not be read", "packets")
1519
+ with _join_workspace() as (tmp, temps):
1520
+ dst = output if STATE.dry_run else sibling_temp(output, "smart")
1521
+ if not STATE.dry_run:
1522
+ temps.append(dst)
1523
+ try:
1524
+ doc = _smartcut.execute(args.input, segments, dst, meta, params, packets, args.crf, args.preset, tmp,
1525
+ vend=video_end(args.input, meta), gop_is_open=gop_is_open, landing=seek_keyframe,
1526
+ origin=file_origin, declick=DECLICK_S, seek_margin=SEEK_MARGIN)
1527
+ except _smartcut.SmartFallback as exc:
1528
+ return fallback(exc.reason, exc.code)
1529
+ if not STATE.dry_run:
1530
+ place_output(dst, output, move=True)
1531
+ if meta.get("subtitle_streams") or meta.get("data_streams"):
1532
+ DROPPED_STREAMS.append(output)
1533
+ return doc
1534
+
1535
+
1536
+ def smart_verification(doc: dict) -> List[dict]:
1537
+ """The --smart checks as verification steps (all passed: a failed one fell back before this)."""
1538
+ c = doc["checks"]
1539
+ return [{"step": "smart_frames", "ok": True, "frames": c["frames"], "grid_worst_seconds": c["grid_worst_seconds"]},
1540
+ {"step": "smart_packets", "ok": True, "copied_packets_equal": c["copied_packets_equal"]},
1541
+ {"step": "smart_decode", "ok": True, "frames_decoded_equal": c["frames_decoded_equal"]},
1542
+ {"step": "smart_params", "ok": True, "time_base": c["time_base"]}]
1543
+
1544
+
1545
+ def main() -> int:
1546
+ global DECLICK_S
1547
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
1548
+ ap.add_argument("input")
1549
+ ap.add_argument("-o", "--output", help="output file (default: <name>_cut.<ext>)")
1550
+ g = ap.add_argument_group("range (single segment)")
1551
+ g.add_argument("--start", help="start time (seconds, mm:ss or hh:mm:ss.ms). default 0")
1552
+ g.add_argument("--end", help="end time")
1553
+ g.add_argument("--duration", help="duration instead of --end")
1554
+ ap.add_argument("--segments", help="comma separated START-END list, e.g. '0:05-0:12,1:00-1:20' (joined in order)")
1555
+ ap.add_argument("--remove", metavar="START-END[,...]",
1556
+ help="the inverse of --segments: drop these ranges and keep the rest, joined in order "
1557
+ "(e.g. '1:20-2:05,10:00-10:30'); overlapping ranges merge")
1558
+ ap.add_argument("--smart", action="store_true",
1559
+ help="keyframe-aware cut of an H.264 source: re-encode only from each cut point to the next keyframe "
1560
+ "(and from the last keyframe to the end point), matched to the source's profile, level, pixel "
1561
+ "format, reorder depth and colour tags, and stream-copy the whole GOPs between; verified (frame "
1562
+ "grid, copied packets, decoded frames) or re-encoded in full with the reason in smart.reason")
1563
+ ap.add_argument("--accurate", action="store_true", help="always re-encode for frame-accurate (video) / sample-accurate (audio) cuts (default: lossless -c copy, re-encoding only when the keyframe snap exceeds --tolerance)")
1564
+ el = ap.add_mutually_exclusive_group()
1565
+ el.add_argument("--edit-list", action="store_true",
1566
+ help="a single-segment .mp4/.mov stream copy keeps the MP4 edit list that hides the keyframe's pre-roll, "
1567
+ "so the picture starts at --start (the default since 3.0.0); a player that ignores edit lists shows the pre-roll")
1568
+ el.add_argument("--no-edit-list", action="store_true",
1569
+ help="shift the copy's timestamps instead (-avoid_negative_ts make_zero, every 2.x release's default): "
1570
+ "the picture starts at the keyframe before --start")
1571
+ kh = ap.add_mutually_exclusive_group()
1572
+ kh.add_argument("--keep-hevc", action="store_true",
1573
+ help="a re-encode of an SDR HEVC source stays HEVC (x265 8-bit BT.709; VideoToolbox under --hw); "
1574
+ "the default since 3.0.0; --codec overrides it")
1575
+ kh.add_argument("--no-keep-hevc", action="store_true",
1576
+ help="re-encode an SDR HEVC source with x264, as every 2.x release did (HDR still gets x265 Main10)")
1577
+ ap.add_argument("--vfr-guard", choices=["average", "sampled", "off"], default="sampled",
1578
+ help="what keeps a variable-frame-rate source from a stream copy (default sampled since 3.0.0: re-encode "
1579
+ "only when sampled packet timestamps are variable or too few to judge; average, every 2.x "
1580
+ "release's default: a nominal rate that differs from the average re-encodes, as --accurate, "
1581
+ "and the sampled timing is reported; off: measure and keep the copy, with a note)")
1582
+ ap.add_argument("--tolerance", type=float, default=0.5, help="max seconds a lossless cut may deviate before re-encoding kicks in (default 0.5, -1 = never for a "
1583
+ "keyframe snap; a --segments join is still re-cut for open GOPs, a later B-frame .mp4/.mov "
1584
+ "segment starting between keyframes, or a failed join check)")
1585
+ dc = ap.add_mutually_exclusive_group()
1586
+ dc.add_argument("--declick-ms", type=float, default=DECLICK_S * 1000,
1587
+ help="--segments: fade the sound this many ms on each side of every join the re-encode makes, so "
1588
+ "butted cuts do not click (default %(default)g; a stream-copy join is not faded)")
1589
+ dc.add_argument("--no-declick", action="store_true", help="--segments: butt the joins with no fade")
1590
+ snap = ap.add_argument_group("beat snapping")
1591
+ snap.add_argument("--snap", choices=["none", "beats"], default="none",
1592
+ help="move each in/out point to the nearest measured beat (default none)")
1593
+ snap.add_argument("--snap-tolerance", type=float, default=0.12,
1594
+ help="most seconds a point may move with --snap beats (default 0.12, about a "
1595
+ "quarter of a beat at 120 BPM)")
1596
+ snap.add_argument("--snap-source", metavar="FILE",
1597
+ help="take the beat grid from this scenes.py --beats --json document (or from "
1598
+ "this media file) instead of measuring the input again")
1599
+ snap.add_argument("--min-confidence", type=float, default=BEAT_MIN_CONFIDENCE,
1600
+ help=f"refuse to snap below this measured beat confidence (default {BEAT_MIN_CONFIDENCE})")
1601
+ ap.set_defaults(crf=18) # --quality's default (the --crf alias was removed in 2.0)
1602
+ ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset when re-encoding")
1603
+ add_common(ap)
1604
+ args = ap.parse_args()
1605
+ apply_common(args)
1606
+ global KEEP_HEVC
1607
+ # 3.0.0 defaults: keep HEVC and the edit list unless the --no- form is given (--edit-list and
1608
+ # --keep-hevc stay accepted, and now say what happens anyway)
1609
+ KEEP_HEVC = not args.no_keep_hevc
1610
+
1611
+ meta = probe(args.input)
1612
+ # read as a one-frame clip, a still wrote 0.04 s with --start 0 and nothing (kind output) past it (#531)
1613
+ refuse_still(meta, args.input, "cut.py keeps a stretch of a clip's time, and a still has none")
1614
+ total = meta.get("duration") or 0.0
1615
+ # why every segment re-encodes, if one of these forces it; `requested` is read before the
1616
+ # guards below overwrite args.accurate, so a forced re-encode is never reported as asked for
1617
+ if args.smart and args.accurate:
1618
+ die("--smart re-encodes only the partial GOPs at each cut and copies the rest; --accurate re-encodes all of it: "
1619
+ "choose one")
1620
+ forced: List[str] = ["requested"] if args.accurate else []
1621
+ if STATE.codec:
1622
+ # "cut this and make it HEVC": a stream copy keeps the source codec, so the request is a
1623
+ # re-encode -- and a cause of it even when --accurate or the VFR guard already forced one
1624
+ if not args.accurate:
1625
+ info(f"--codec {STATE.codec} asks for a re-encode; the lossless copy path keeps the source codec, switching to --accurate")
1626
+ args.accurate = True
1627
+ forced.append("codec")
1628
+
1629
+ fps = (meta.get("video") or {}).get("fps")
1630
+ remove_notes: List[str] = []
1631
+ if args.remove:
1632
+ if args.segments or args.end or args.duration or args.start is not None:
1633
+ die("--remove names what to drop from the whole file: it does not combine with --segments, --start, --end or --duration")
1634
+ if args.snap == "beats":
1635
+ # a snapped edge of what is kept could move into a range the caller asked to drop
1636
+ die("--remove drops exactly the ranges given: --snap beats would move the kept edges, possibly into them; "
1637
+ "snap the ranges first (scenes.py --beats) or cut with --segments --snap beats")
1638
+ if not total:
1639
+ die(f"--remove needs the input's duration, which {args.input} does not report"
1640
+ + (" yet (it is an earlier step's output)" if dry_run_input_pending(args.input) else ""))
1641
+ picture = None
1642
+ if (meta.get("video") or {}).get("fps") and not is_audio_output(args.output or "") and not dry_run_input_pending(args.input):
1643
+ vend = video_end(args.input, meta)
1644
+ if vend is not None:
1645
+ picture = ((meta["video"].get("start_time") or 0.0) - file_origin(args.input), vend)
1646
+ sound_only: List[Tuple[float, float]] = []
1647
+ args.segments = ",".join(f"{s:.6f}-{e:.6f}" for s, e in keep_ranges_after_removing(
1648
+ parse_segments(args.remove, fps, clamp=True), total, fps, picture, sound_only))
1649
+ for a, b in sound_only:
1650
+ remove_notes.append(f"--remove left {a:.3f}-{b:.3f}s, which holds sound but no frame of the picture "
1651
+ f"(the video runs {picture[0]:.3f}-{picture[1]:.3f}s); it is not kept")
1652
+ info(remove_notes[-1])
1653
+ elif args.segments and (args.end or args.duration or args.start is not None):
1654
+ # A50: the single-range flags were accepted beside --segments and not read, where --remove
1655
+ # refuses the same combination
1656
+ die("--segments names every range to keep: it does not combine with --start, --end or --duration "
1657
+ "(give the one range as --segments A-B, or drop --segments)")
1658
+ if args.segments:
1659
+ segments = parse_segments(args.segments, fps)
1660
+ else:
1661
+ start = _t(args.start or "0", fps, "--start")
1662
+ if start < 0:
1663
+ die(f"--start must not be negative, got {args.start!r}")
1664
+ if args.end and args.duration:
1665
+ die("use --end or --duration, not both")
1666
+ if args.end:
1667
+ end = _t(args.end, fps, "--end")
1668
+ if end < 0:
1669
+ die(f"--end must not be negative, got {args.end!r}")
1670
+ elif args.duration:
1671
+ end = start + _t(args.duration, fps, "--duration")
1672
+ else:
1673
+ end = total
1674
+ if end <= start:
1675
+ die("end must be after start")
1676
+ segments = [(start, end)]
1677
+
1678
+ snap_result = None
1679
+ if args.snap == "beats":
1680
+ snap_result, segments = snap_segments(args, segments, meta, total)
1681
+
1682
+ for s, e in segments:
1683
+ if total and s >= total:
1684
+ die(f"segment start {s:.3f}s is beyond the media duration {total:.3f}s")
1685
+ # what was asked for, clamped to the media duration as in every 2.x release: requested_* and
1686
+ # expected_duration report this, and a segment the join below ends with the video (less than a
1687
+ # frame of sound trimmed) shows that trim in duration_delta_seconds and a note instead
1688
+ requested = [(s, min(e, total) if total else e) for s, e in segments]
1689
+ # a start or end written in milliseconds is cut on the frame it reads back to (#653): the nearest
1690
+ # frame when that is within half a millisecond either way (1.902 and 1.935 for the frames at
1691
+ # 1.9019 and 1.93527), never one before the first; a sound-only output or a VFR picture has no
1692
+ # grid (decision.on_frame; grid_at_or_after itself is unchanged, since a length also goes through it)
1693
+ on_frame = lambda t, rate=0 if is_audio_output(args.output or "") or (meta.get("video") or {}).get("variable_frame_rate_suspected") else frame_rate(meta): decision_on_frame(t, stream_starts(meta)[0], rate)
1694
+ segments = [(on_frame(s), min(on_frame(e), total or math.inf)) for s, e in requested]
1695
+ if len(segments) == 1:
1696
+ declare_time_map("input seek") # one range: FFmpeg moves the chapters with the input -ss
1697
+ video = meta.get("video") or {}
1698
+ if video.get("fps") and not is_audio_output(args.output or ""):
1699
+ # a video segment shorter than one frame has no picture to cut: a copy lands on a whole
1700
+ # GOP and a re-encode on one frame or none, so the result would not be what was asked
1701
+ frame = 1.0 / video["fps"]
1702
+ # where the video ends on the cut's clock (video_end), not the stream's length: video that
1703
+ # starts after the container does (MPEG-TS) ends later than its length says. A pending
1704
+ # --dry-run input has nothing to probe, so it falls back to the media duration.
1705
+ vend = (None if dry_run_input_pending(args.input) else video_end(args.input, meta)) or total
1706
+ for s, e in segments:
1707
+ if (min(e, vend) if vend else e) - s < frame - 1e-6:
1708
+ die(f"segment {s:.3f}-{e:.3f}s is shorter than one frame ({frame:.4f}s at {video['fps']:g} fps)"
1709
+ + (" inside the video stream" if vend and e > vend else "")
1710
+ + "; give every segment at least one frame", kind="input")
1711
+
1712
+ output = args.output or default_output(args.input, "cut")
1713
+ # --snap-source is read for its beat grid and is never an -i of the cut (#522's sweep)
1714
+ refuse_output_is_input(output, args.input, *([args.snap_source] if args.snap_source else []))
1715
+ ext = os.path.splitext(output)[1].lower() or ".mp4" # an upper-case .MP4 is still faststart
1716
+
1717
+ # A segment that runs past the end of the video, with a join after it: whatever joins it (the
1718
+ # concat demuxer or the concat filter) starts the next segment after its LONGER stream, so the
1719
+ # sound with no picture left a hole in the video (0.355 s for 0.3 s of sound, reported as a
1720
+ # clean copy). clip_length's rule, as join.py uses it: less than a frame past -> end the
1721
+ # segment with its picture; more -> hold the last frame for the sound, which only a re-cut
1722
+ # can do. The last segment is left as the source had it: nothing is placed after it.
1723
+ join_notes: List[str] = list(remove_notes)
1724
+ hold_needed = False
1725
+ vend = (video_end(args.input, meta) if len(segments) > 1 and video.get("fps") and not is_audio_output(output)
1726
+ and not dry_run_input_pending(args.input) else None)
1727
+ if vend is not None:
1728
+ frame = 1.0 / video["fps"]
1729
+ for i, (s, e) in enumerate(segments[:-1]):
1730
+ if e <= vend + 1e-6:
1731
+ continue
1732
+ if e - vend <= frame + 1e-6:
1733
+ segments[i] = (s, vend)
1734
+ join_notes.append(f"segment {i + 1} ends with the video at {vend:.3f}s: the {(e - vend) * 1000:.0f} ms of "
1735
+ "sound after its last frame is trimmed")
1736
+ else:
1737
+ hold_needed = True
1738
+ join_notes.append(f"segment {i + 1} runs {e - vend:.3f}s past the end of the video; its last frame is held "
1739
+ "for the sound, which a stream-copy join cannot do, so every segment was re-cut")
1740
+ for n in join_notes:
1741
+ info(n)
1742
+
1743
+ # the VFR guard: a stream copy of variable-frame-rate video cuts unreliably. --vfr-guard average
1744
+ # (the default, as in every 2.x release) trusts probe's nominal-vs-average rate check and
1745
+ # re-encodes on it; the sampled packet timing is then measured only to report whether that
1746
+ # check was right. sampled re-encodes on the sampled timing instead (an iPhone's 30 vs 29.98
1747
+ # fps is not taken for VFR), and off measures and keeps the copy.
1748
+ vfr_check = None
1749
+ vfr_notes: List[str] = []
1750
+ could_copy = (bool(video) and not args.accurate and not hold_needed and not is_audio_output(output)
1751
+ and not dry_run_input_pending(args.input))
1752
+
1753
+ def sample_timing() -> dict:
1754
+ return {"heuristic": True, **measure_frame_timing(args.input, total, video.get("start_time") or 0.0),
1755
+ "method": "sampled", "guard": args.vfr_guard}
1756
+
1757
+ if args.vfr_guard == "average":
1758
+ if video.get("variable_frame_rate_suspected") and not args.accurate:
1759
+ info("source looks variable-frame-rate; lossless cuts on VFR are unreliable, switching to --accurate")
1760
+ if could_copy:
1761
+ vfr_check = sample_timing()
1762
+ if vfr_check["measured"] == "sampled_cfr":
1763
+ vfr_notes.append("the nominal and average frame rates differ, so the source was taken for VFR and "
1764
+ "re-encoded, but its sampled frame timing is constant: --vfr-guard sampled keeps "
1765
+ "the lossless copy")
1766
+ info(vfr_notes[-1])
1767
+ args.accurate = True
1768
+ forced.append("vfr")
1769
+ elif could_copy:
1770
+ vfr_check = sample_timing()
1771
+ measured = vfr_check["measured"]
1772
+ what = ("the sampled frame timing is variable" if measured == "vfr"
1773
+ else "the frame timing could not be measured")
1774
+ if measured != "sampled_cfr" and args.vfr_guard == "off":
1775
+ vfr_notes.append(f"{what}; --vfr-guard off skipped the re-encode that forces, so a stream copy of this "
1776
+ "source may land off its frames")
1777
+ info(vfr_notes[-1])
1778
+ elif measured != "sampled_cfr":
1779
+ info(f"{what}; lossless cuts on VFR are unreliable, switching to --accurate (--vfr-guard off keeps the copy)")
1780
+ args.accurate = True
1781
+ forced.append("vfr" if measured == "vfr" else "vfr_inconclusive")
1782
+
1783
+ if not math.isfinite(args.declick_ms) or args.declick_ms < 0:
1784
+ die(f"--declick-ms must be a finite number of ms, 0 or more, got {args.declick_ms:g}")
1785
+ DECLICK_S = 0.0 if args.no_declick else args.declick_ms / 1000
1786
+ outcomes: List[dict] = []
1787
+ join_reencoded = False
1788
+ join_check = None
1789
+ smart_doc = None
1790
+ if args.smart:
1791
+ smart_doc = run_smart(args, segments, output, meta, forced, hold_needed, total)
1792
+ if not smart_doc["applied"]:
1793
+ # the stated fallback: the full re-encode --accurate makes, with the reason reported
1794
+ record_fallback(f"--smart: {smart_doc['reason']}; re-encoding the whole cut instead", "smart_fallback",
1795
+ reason_code=smart_doc["reason_code"])
1796
+ join_notes.append(f"--smart fell back to a full re-encode: {smart_doc['reason']}")
1797
+ args.accurate = True
1798
+ forced.append("smart_fallback")
1799
+ if smart_doc is not None and smart_doc["applied"]:
1800
+ # every part copied and no sound (a silent source cut on keyframes) re-encodes nothing
1801
+ smart_encoded = bool(smart_doc["reencoded_frames"] or meta.get("audio"))
1802
+ outcomes = [_outcome(meta, output, smart_encoded, ["smart"] if smart_encoded else []) for _ in segments]
1803
+ elif len(segments) == 1:
1804
+ outcomes.append(cut_one(args.input, segments[0][0], segments[0][1], output, args.accurate, args.crf, args.preset, args.tolerance, meta,
1805
+ edit_list_ok=not args.no_edit_list))
1806
+ elif hold_needed or args.accurate:
1807
+ # Straight to one encode through the concat filter. A held frame needs the re-cut (no part
1808
+ # can carry it into a copy join); and when every part re-encodes anyway, encoding each on
1809
+ # its own and copy-joining them left a hole of one AAC frame at every join (each part's
1810
+ # audio runs an encoder frame past its picture, and the concat demuxer places the next
1811
+ # part after it: measured 23 ms per join).
1812
+ with tempfile.TemporaryDirectory(prefix="ffskill_cut_") as tmp:
1813
+ join_from_source(args.input, segments, output, meta, args.crf, args.preset, tmp)
1814
+ join_reencoded = hold_needed # only the hold is a fallback; --accurate asked for this
1815
+ outcomes = [_outcome(meta, output, True, []) for _ in segments]
1816
+ else:
1817
+ with _join_workspace() as (tmp, temps):
1818
+ # A video join is planned from the source's own packets and measured against them once
1819
+ # written (check_join). A source whose frames do not reorder (no B-frames) cuts its
1820
+ # parts as every 2.x release did (make_zero, -t end-start, each part judged against
1821
+ # --tolerance by its length): in decode order that is already exact. One whose frames
1822
+ # reorder keeps .mp4/.mov parts' edit lists and cuts each from its start keyframe to
1823
+ # its end keyframe's dts (plan_part). An audio-only join keeps the plain cut.
1824
+ join_video = bool(video) and not is_audio_output(output) and not dry_run_input_pending(args.input)
1825
+ # where each part's -ss lands, measured (seek_keyframe); the packets read around the
1826
+ # segments reach back to it
1827
+ landings = [seek_keyframe(args.input, s) for s, _ in segments] if join_video else None
1828
+ packets = (video_packets(args.input, [(min(s, k[0]) if k else s, e) for (s, e), k in zip(segments, landings)],
1829
+ args.tolerance, total) if join_video else None)
1830
+ snap_end = bool(packets) and reorders(packets) and ext.lower() in EDIT_LIST_EXTS
1831
+ plans = ([plan_part(packets, s, e, args.tolerance, video_end(args.input, meta), fps, snap_end, k)
1832
+ for (s, e), k in zip(segments, landings)] if packets else None)
1833
+ open_key = open_join_key(packets, plans) if plans else None
1834
+ preroll = hidden_preroll_start(packets, plans, snap_end) if plans else None
1835
+ recut = None # why the parts are not joined by stream copy, when that is known before cutting them
1836
+ if join_video and not packets:
1837
+ recut = ("the source's video packets could not be read, so a stream-copy join could not be checked; "
1838
+ "every segment was re-cut from the source")
1839
+ elif open_key is not None:
1840
+ recut = (f"the source uses open GOPs: frames before the keyframe at {open_key:.3f}s decode after it, so a "
1841
+ "stream-copy join would drop them; every segment was re-cut from the source")
1842
+ elif preroll is not None and not any(p["reason"] for p in plans):
1843
+ recut = (f"segment {preroll} starts between keyframes of a source whose frames reorder: its copy would "
1844
+ "hide the frames before its start, which a stream-copy join cannot do; every segment was re-cut "
1845
+ "from the source")
1846
+ compatible = False
1847
+ if recut:
1848
+ info(recut)
1849
+ join_notes.append(recut)
1850
+ elif plans and any(p["reason"] for p in plans):
1851
+ # a segment with no keyframe near its start or end re-encodes, and only copied parts are
1852
+ # joined by copy (parts encoded one by one leave an AAC frame's hole at every join), so
1853
+ # every segment is re-cut into one encode, without encoding the parts first
1854
+ late = [str(i + 1) for i, p in enumerate(plans) if p["reason"]]
1855
+ # the keyframes near each such segment's start, as a part judged on its own named them
1856
+ # in every 2.x release, so the caller can move the cut instead
1857
+ for (s, _), p in zip(segments, plans):
1858
+ if p["reason"]:
1859
+ NEAREST_KEYFRAMES.extend(k for k in keyframes_near(args.input, s) if k not in NEAREST_KEYFRAMES)
1860
+ info(f"segment{'s' if len(late) > 1 else ''} {', '.join(late)} {'have' if len(late) > 1 else 'has'} no keyframe "
1861
+ f"within {args.tolerance:.2f}s of {'their' if len(late) > 1 else 'its'} start or end to copy from; "
1862
+ "re-cutting every segment from the source into one re-encode")
1863
+ recut = "tolerance"
1864
+ if recut:
1865
+ outcomes = [_outcome(meta, output, True, ["tolerance"] if plans and plans[i]["reason"] else [])
1866
+ for i in range(len(segments))]
1867
+ else:
1868
+ parts = []
1869
+ for i, (s, e) in enumerate(segments):
1870
+ part = os.path.join(tmp, f"part{i:03d}{ext}")
1871
+ plan = plans[i] if plans else None
1872
+ outcomes.append(cut_one(args.input, s, e, part, False, args.crf, args.preset, args.tolerance, meta,
1873
+ edit_list_ok=False, copy_t=plan["t"] if plan and snap_end else None))
1874
+ parts.append(part)
1875
+ # a stream-copy join is only safe between identical copied parts: the concat demuxer
1876
+ # takes the first part's parameters for all of them, and a mismatch (a copied HEVC part
1877
+ # next to a re-encoded one, or H.264 next to HEVC) decodes with errors from a run that
1878
+ # exited 0; video parts that all re-encoded match, but leave an AAC frame's hole at each
1879
+ # join (audio decoded to PCM has no encoder priming, so those parts still join)
1880
+ compatible = (not (join_video and any(o["reencoded"] for o in outcomes))
1881
+ and (STATE.dry_run or signatures_match([join_signature(p) for p in parts], ext)))
1882
+ if compatible:
1883
+ listfile = os.path.join(tmp, "list.txt")
1884
+ with open(listfile, "w", encoding="utf-8") as fh:
1885
+ for p in parts:
1886
+ fh.write(concat_list_line(p) + "\n")
1887
+ # a join that is checked is written to a hidden file beside the output and renamed
1888
+ # into place only once it passes (copying it out of the temp directory cost about 2 s
1889
+ # for 240 MB): a failed check re-cuts, and a re-cut that then failed must not cost
1890
+ # the caller the file --overwrite would have replaced
1891
+ checked = bool(plans) and not STATE.dry_run
1892
+ joined = sibling_temp(output, "join") if checked else output
1893
+ if checked:
1894
+ temps.append(joined)
1895
+ cmd = with_mapped_chapters(ffmpeg_base() + ["-f", "concat", "-safe", "0", "-i", listfile], meta,
1896
+ segments_map(segments), None) + ["-c", "copy"]
1897
+ if ext in (".mp4", ".mov", ".m4v"):
1898
+ cmd += ["-movflags", "+faststart"]
1899
+ if not is_audio_output(output):
1900
+ cmd += output_timecode_args(meta, None) # a join: no start timecode (_join_chunk)
1901
+ cmd += [joined]
1902
+ proc = run(cmd, check=False)
1903
+ fail_if_classified(proc) # #415: a full disk is not a reason to re-cut every segment
1904
+ if proc.returncode != 0:
1905
+ info("concat with stream copy failed; re-cutting every segment from the source into one re-encode")
1906
+ compatible = False
1907
+ elif checked:
1908
+ # measured, not predicted: the joined file against the source packets its parts hold
1909
+ # constant frame timing: measured by the sampled guards, and under the default
1910
+ # average guard a copy is only reached when probe's rate check found it constant
1911
+ cfr = (vfr_check.get("measured") == "sampled_cfr" if vfr_check
1912
+ else args.vfr_guard == "average")
1913
+ counts = [expected_packets(packets, [(p["start_pts"], p["end_bound"])]) for p in plans]
1914
+ out_pts = stream_packet_times(joined, "v", "pts_time")
1915
+ join_check = check_join(out_pts, counts, fps, cfr, predicted_join_steps(parts))
1916
+ # the sound of each part against its picture (only once the pictures are right: the
1917
+ # parts are located in the join by their packet counts)
1918
+ video_ok = join_check["ok"]
1919
+ audio = (check_join_audio(args.input, joined, [p["start_pts"] for p in plans], counts, out_pts,
1920
+ copied_audio_streams(meta, joined),
1921
+ strip_adts=("mpegts" in str(meta.get("format") or "").split(",")
1922
+ and ext.lower() not in TS_EXTS))
1923
+ if video_ok and meta.get("audio") else
1924
+ {"audio_offset_ms": None, "audio_parts_checked": 0, "audio_ok": True})
1925
+ audio_ok = audio.pop("audio_ok")
1926
+ join_check["ok"] = video_ok and audio_ok
1927
+ join_check.update(audio)
1928
+ if not join_check["ok"]:
1929
+ step = join_check["max_step_seconds"]
1930
+ if video_ok:
1931
+ off = max((o for o in join_check["audio_offset_ms"] if o is not None), key=abs)
1932
+ why = (f"segment {join_check['audio_offset_ms'].index(off) + 1}'s sound is {abs(off):.1f} ms "
1933
+ f"{'late' if off > 0 else 'early'} against its picture")
1934
+ else:
1935
+ why = (f"{join_check['packets']} video packets where the segments hold "
1936
+ f"{join_check['expected_packets']} in the source"
1937
+ + (f", largest step {step:.3f}s" if step is not None else ""))
1938
+ msg = f"the stream-copy join was checked and failed: {why}; every segment was re-cut from the source"
1939
+ info(msg)
1940
+ join_notes.append(msg)
1941
+ compatible = False
1942
+ else:
1943
+ place_output(joined, output, move=True)
1944
+ else:
1945
+ info("the cut parts cannot be joined by stream copy (a segment re-encoded, or the parts differ in "
1946
+ "codec parameters); re-cutting every segment from the source into one re-encode")
1947
+ if not compatible:
1948
+ join_from_source(args.input, segments, output, meta, args.crf, args.preset, tmp)
1949
+ join_reencoded = True
1950
+ # every segment was re-cut and re-encoded: none of them keeps its copy precision
1951
+ outcomes = [_outcome(meta, output, True, o["reasons"]) for o in outcomes]
1952
+
1953
+ result = probe(output, role="output")
1954
+ expected = sum(e - s for s, e in requested)
1955
+ # the join counts: a copy join that fell back to a re-encode is not a stream copy (2.x reported
1956
+ # it as mode copy, precision packet)
1957
+ reencoded = join_reencoded or any(o["reencoded"] for o in outcomes)
1958
+ report = report_precision(meta, output, reencoded, outcomes)
1959
+ precision = report["precision"]
1960
+ reencode_reason: List[str] = []
1961
+ if reencoded:
1962
+ for r in forced + [r for o in outcomes for r in o["reasons"]] + (["concat_fallback"] if join_reencoded else []):
1963
+ if r not in reencode_reason:
1964
+ reencode_reason.append(r)
1965
+ got = result.get("duration")
1966
+ error_ms = round((got - expected) * 1000, 3) if got is not None and not STATE.dry_run else None
1967
+ # mode: "copy" (nothing re-encoded at any stage, the join included), "accurate" (--accurate was
1968
+ # asked for or forced), "hybrid" (asked for lossless but a segment or the join re-encoded anyway;
1969
+ # reencode_reason says why)
1970
+ mode = ("smart" if smart_doc is not None and smart_doc["applied"] else
1971
+ "copy" if not reencoded else ("accurate" if args.accurate else "hybrid"))
1972
+ notes: List[str] = vfr_notes + join_notes + [n for o in outcomes for n in o.get("notes") or []]
1973
+ verification = smart_verification(smart_doc) if smart_doc is not None and smart_doc.get("checks") else []
1974
+ if not STATE.dry_run and mode == "copy" and len(requested) > 1:
1975
+ # Per-segment keyframe snaps can all be within tolerance and still accumulate
1976
+ # into a materially longer or shorter output. Check the written timeline once.
1977
+ tolerance = min(expected, args.tolerance) if args.tolerance >= 0 else expected
1978
+ if fps and result.get("video"):
1979
+ tolerance = max(tolerance, 1 / fps)
1980
+ delta = got - expected if got is not None else None
1981
+ ok = delta is not None and abs(delta) <= tolerance + 1e-6
1982
+ verification.append({"step": "cut_total_duration", "property": "output_duration",
1983
+ "expected": round(expected, 6), "measured": round(got, 6) if got is not None else None,
1984
+ "delta": round(delta, 6) if delta is not None else None,
1985
+ "tolerance": round(tolerance, 6), "provenance": "user_specified", "ok": ok})
1986
+ if not ok:
1987
+ message = (f"stream-copy total duration: wrote {fmt_secs(got)}, requested {expected:.3f}s "
1988
+ f"(tolerance {tolerance:.3f}s); use --accurate to re-encode the cut")
1989
+ notes.append(message)
1990
+ info(message)
1991
+ possible = possible_reencode_reason(mode, outcomes, len(segments))
1992
+ if possible:
1993
+ notes.append(possible_reencode_note(mode, possible, args.tolerance))
1994
+ single = outcomes[0] if len(outcomes) == 1 else {}
1995
+ stored = single.get("stored_preroll_seconds")
1996
+ if single.get("edit_list") and stored:
1997
+ notes.append(f"{stored:.3f}s of pre-roll is stored, hidden by the MP4 edit list; a player or "
1998
+ "tool that ignores edit lists will show it")
1999
+ # where each copied part's end moved to its keyframe; only for a join that is those parts
2000
+ end_snaps = None
2001
+ if join_check and join_check["ok"] and not join_reencoded:
2002
+ end_snaps = [None if o["reencoded"] or p["end_pts"] is None else round(p["end_pts"] - e, 3) + 0.0
2003
+ for o, p, (_, e) in zip(outcomes, plans, segments)]
2004
+ # a single MP4/MOV copy without --edit-list shows the pre-roll the edit list would hide
2005
+ remedy = (len(outcomes) == 1 and not reencoded and not single.get("edit_list") and single.get("start_snapped")
2006
+ and ext.lower() in EDIT_LIST_EXTS and not is_audio_output(output))
2007
+ # the source's own skew where the output's picture starts: at the keyframe the first copy
2008
+ # landed on, or at the start when an edit list hides the pre-roll (or a re-encode starts there)
2009
+ first = outcomes[0] if outcomes else {}
2010
+ at = (first["landed_pts"] if not reencoded and not first.get("edit_list") and first.get("landed_pts") is not None
2011
+ else segments[0][0])
2012
+ skew, skew_note = ((None, None) if STATE.dry_run
2013
+ else av_skew(result, bool(remedy), source_skew(args.input, meta, at)))
2014
+ if reencoded:
2015
+ # a re-encode starts both streams where the source had them at the start (the re-cut pads the
2016
+ # audio to each segment's origin): the skew is reported, but no copy began on unshared packets
2017
+ skew_note = None
2018
+ if skew_note:
2019
+ info(skew_note)
2020
+ notes.append(skew_note)
2021
+ info(f"wrote {output} ({fmt_secs(got)}, expected ~{expected:.3f}s, "
2022
+ + ("re-encoded" if reencoded else "lossless stream copy") + f", {precision} precision)")
2023
+ # the streams the source had and this cut was not told to drop (an audio extension drops the
2024
+ # picture): #367, a TS cut that lost its video must not say verified. ffmpeg's default stream
2025
+ # selection writes one of each, so that is the count; the source's own picture/sound gap is
2026
+ # the reference for the lengths check
2027
+ expect_streams = {"video": int(bool(meta.get("video")) and not is_audio_output(output)), "audio": int(bool(meta.get("audio")))}
2028
+ # cut writes one audio track (ffmpeg's default selection, on a stream copy as on a re-encode):
2029
+ # a source with more must say which ones did not come along (#397), as export.py's non_av_streams does
2030
+ src_audio = meta.get("audio_streams") or []
2031
+ out_audio = (result.get("audio_streams") or []) if not STATE.dry_run else src_audio[:1]
2032
+ dropped_audio = len(src_audio) - len(out_audio) if src_audio else 0
2033
+ if dropped_audio > 0:
2034
+ kept = len(out_audio)
2035
+ msg = (f"the source has {len(src_audio)} audio tracks; this cut kept {kept} and left {dropped_audio} out "
2036
+ f"(cut writes one audio track, on a stream copy as on a re-encode)")
2037
+ warn(msg, "audio_tracks_dropped", source=len(src_audio), kept=kept, dropped=dropped_audio)
2038
+ notes.append(msg)
2039
+ # a copied audio extraction that starts with the sound, not where it sat after --start (#515); an
2040
+ # outcome a re-cut replaced carries none, so this is what the written file holds
2041
+ leads = [(i + 1, o["audio_lead_dropped_seconds"]) for i, o in enumerate(outcomes) if o.get("audio_lead_dropped_seconds")]
2042
+ if leads:
2043
+ where = (f" (segment{'s' if len(leads) > 1 else ''} {', '.join(str(i) for i, _ in leads)})"
2044
+ if len(outcomes) > 1 else "")
2045
+ warn(f"the stream copy left out {sum(s for _, s in leads):.3f}s of silence before the sound{where}, so the "
2046
+ "sound is early against the source's picture; --accurate keeps it", "audio_lead_dropped",
2047
+ seconds=round(sum(s for _, s in leads), 6), segments=[{"index": i, "seconds": s} for i, s in leads])
2048
+ emit(output, expected_duration=round(expected, 6), duration_error_ms=error_ms, precision=precision, reencoded=reencoded,
2049
+ expect_streams=expect_streams, stream_reference=[meta], stream_windows=[(s, e) for s, e in requested],
2050
+ dropped_non_av_streams=bool(DROPPED_STREAMS), dropped_audio_streams=max(dropped_audio, 0),
2051
+ requested_start=round(requested[0][0], 6) if len(requested) == 1 else None,
2052
+ requested_end=round(requested[0][1], 6) if len(requested) == 1 else None,
2053
+ requested_segments=[[round(s, 6), round(e, 6)] for s, e in requested] if len(requested) > 1 else None,
2054
+ requested_duration=round(expected, 6), output_duration=round(got, 6) if got is not None and not STATE.dry_run else None,
2055
+ duration_delta_seconds=round(error_ms / 1000, 6) if error_ms is not None else None,
2056
+ mode=mode, possible_reencode_reason=possible, keyframe_snapped=report["keyframe_snapped"], start_snapped=report["start_snapped"],
2057
+ reencode_reason=reencode_reason, least_exact_precision=report["least_exact_precision"],
2058
+ segment_precision=report["segment_precision"],
2059
+ edit_list=bool(single.get("edit_list")), stored_preroll_seconds=stored, av_start_skew_seconds=skew,
2060
+ join_check=join_check, segment_end_snap_seconds=end_snaps,
2061
+ # the joins were faded only where the concat filter re-encoded them
2062
+ declick_ms=(DECLICK_S * 1000 if len(segments) > 1 and meta.get("audio")
2063
+ and (join_reencoded or args.accurate or mode == "smart") else None),
2064
+ notes=notes, **({"vfr_check": vfr_check} if vfr_check else {}),
2065
+ nearest_keyframes=sorted(NEAREST_KEYFRAMES) if NEAREST_KEYFRAMES else None,
2066
+ # the trade the caller can offer instead of a re-encode (eval e02: "without losing quality")
2067
+ lossless_alternative=(f"--start {min(NEAREST_KEYFRAMES, key=lambda k: abs(k - segments[0][0])):.3f} lands on a keyframe: "
2068
+ f"stream copy with no re-encode, {abs(min(NEAREST_KEYFRAMES, key=lambda k: abs(k - segments[0][0])) - segments[0][0]):.2f}s off the requested start")
2069
+ if mode == "hybrid" and NEAREST_KEYFRAMES and len(segments) == 1 else None,
2070
+ snap=snap_result, **({"smart": smart_doc} if smart_doc is not None else {}),
2071
+ verification=verification)
2072
+ return 0
2073
+
2074
+
2075
+ if __name__ == "__main__":
2076
+ sys.exit(main())