@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,450 @@
1
+ """cut.py --smart: a keyframe-aware cut that re-encodes only the partial GOPs at each cut point.
2
+
3
+ A segment [s, e) on a CFR, progressive H.264 source is split at its keyframes:
4
+
5
+ head [first frame at/after s, K1) re-encoded (K1 = first keyframe at or after s)
6
+ copy [K1, K2) stream-copied, whole closed GOPs
7
+ tail [K2, first frame at/after e) re-encoded (K2 = last keyframe at or before e)
8
+
9
+ A part that is empty (s on a keyframe, e on a keyframe or the end of the video) is left out; a
10
+ segment with no keyframe inside it is one re-encoded part. The re-encoded parts are encoded with
11
+ libx264 matched to the source stream (profile, level, pixel format, reorder depth, frame size,
12
+ SAR, colour tags) and every part is written as MPEG-TS, where each keyframe carries its own
13
+ parameter sets in-band, so the decoder switches between the encoder's SPS/PPS and the source's at
14
+ every join. The parts are joined with the concat demuxer (each part's exact length stated), and
15
+ the sound is cut from the source on the same frame grid and encoded once, in the same command.
16
+
17
+ The result is verified before it is moved into place, and any failure falls back to the full
18
+ re-encode with the reason stated:
19
+
20
+ frames the output's frame count and presentation times: one frame per frame duration from
21
+ 0, none missing, none repeated
22
+ packets every copied part's packets against the source's (MD5 of each packet with the
23
+ parameter-set and delimiter NAL units removed, which the in-band switch adds)
24
+ decode framemd5 of each re-encoded part as written against the same frames decoded from
25
+ the output, and of the first DECODE_CHECK_MAX_FRAMES frames of each copied
26
+ part against the source's
27
+ params the re-encoded parts' stream parameters against the source's, and the output's
28
+ time base against the source's
29
+
30
+ Nothing here decides where to cut; it only executes the cut it is given.
31
+ """
32
+ import os
33
+ from fractions import Fraction
34
+ from typing import Any, Dict, List, Optional, Tuple
35
+
36
+ from _common import STATE, aac_args, concat_list_line, ffmpeg_base, require_tool, run
37
+ from _common.color import carried_tag_args
38
+ from _common.runner import fail_if_classified
39
+
40
+ # the stream parameters a re-encoded part must share with the source (ffprobe -show_streams)
41
+ MATCH_FIELDS = ("codec_name", "profile", "level", "pix_fmt", "width", "height", "sample_aspect_ratio",
42
+ "has_b_frames", "color_space", "color_range", "color_transfer", "color_primaries")
43
+ # what libx264 here can encode to match: 8-bit 4:2:0 (full range as yuvj420p)
44
+ SMART_PIX_FMTS = ("yuv420p", "yuvj420p")
45
+ SMART_PROFILES = {"Constrained Baseline": "baseline", "Baseline": "baseline", "Main": "main", "High": "high"}
46
+ SMART_EXTS = (".mp4", ".mov", ".m4v", ".mkv")
47
+ # the first frames of a copied part are decoded and compared against the source's; capped so a long part
48
+ # does not make the check cost a long decode
49
+ DECODE_CHECK_MAX_FRAMES = 300
50
+ # an input -ss lands this far after the keyframe it is asked for (ffprobe prints microseconds)
51
+ _SEEK_PAST = 1e-4
52
+ _DTS_MARGIN = 1e-4
53
+
54
+
55
+ class SmartFallback(Exception):
56
+ """The smart cut cannot be made or did not verify: `reason` is the stated cause."""
57
+
58
+ def __init__(self, reason: str, code: str):
59
+ super().__init__(reason)
60
+ self.reason, self.code = reason, code
61
+
62
+
63
+ def stream_params(path: str) -> Optional[Dict[str, Any]]:
64
+ """The first video stream's parameters (MATCH_FIELDS plus field_order, time_base, r_frame_rate)."""
65
+ import json
66
+ fields = ",".join(MATCH_FIELDS + ("field_order", "time_base", "r_frame_rate"))
67
+ proc = run([require_tool("ffprobe"), "-v", "error", "-select_streams", "v:0", "-show_entries",
68
+ f"stream={fields}", "-of", "json", path], quiet=True, check=False)
69
+ try:
70
+ streams = json.loads(proc.stdout or "{}").get("streams") or []
71
+ except ValueError:
72
+ return None
73
+ return streams[0] if proc.returncode == 0 and streams else None
74
+
75
+
76
+ def _norm(field: str, value: Any) -> Any:
77
+ if field == "profile":
78
+ return SMART_PROFILES.get(str(value), value)
79
+ if field == "sample_aspect_ratio" and value in (None, "0:1", "N/A"):
80
+ return "1:1"
81
+ return value
82
+
83
+
84
+ def mismatches(want: Dict[str, Any], got: Dict[str, Any]) -> List[str]:
85
+ """`field source/part` for every MATCH_FIELDS value the part does not share."""
86
+ return [f"{f} {want.get(f)}/{got.get(f)}" for f in MATCH_FIELDS if _norm(f, want.get(f)) != _norm(f, got.get(f))]
87
+
88
+
89
+ def ineligible(params: Optional[Dict[str, Any]], meta: Dict[str, Any], ext: str) -> Optional[Tuple[str, str]]:
90
+ """(reason, code) when the source or the output cannot take a smart cut, else None."""
91
+ if params is None:
92
+ return "the source's video stream parameters could not be read", "params_unreadable"
93
+ if ext.lower() not in SMART_EXTS:
94
+ return f"--smart writes {', '.join(SMART_EXTS)}; {ext} is not one", "container"
95
+ if params.get("codec_name") != "h264":
96
+ return (f"--smart matches the source with libx264, so it takes H.264; this source is "
97
+ f"{params.get('codec_name')}", "codec")
98
+ if params.get("pix_fmt") not in SMART_PIX_FMTS:
99
+ return f"--smart encodes 8-bit 4:2:0; this source is {params.get('pix_fmt')}", "pix_fmt"
100
+ if str(params.get("profile")) not in SMART_PROFILES:
101
+ return f"H.264 profile {params.get('profile')} cannot be matched by libx264 here", "profile"
102
+ if params.get("field_order") not in (None, "progressive", "unknown"):
103
+ return f"the source is interlaced ({params.get('field_order')})", "interlaced"
104
+ if int(params.get("has_b_frames") or 0) > 2:
105
+ return f"a reorder depth of {params.get('has_b_frames')} frames cannot be matched", "reorder_depth"
106
+ if not _rate(params):
107
+ return "the source states no frame rate", "frame_rate"
108
+ if (meta.get("video") or {}).get("bt2020_or_hdr"):
109
+ return "an HDR or BT.2020 source is encoded on the 10-bit HEVC line, not matched", "hdr"
110
+ return None
111
+
112
+
113
+ # Matroska stores every timestamp in milliseconds (its default TimestampScale), whatever the source's
114
+ # time base: an .mkv output's stream reads 1/1000 however it is written
115
+ MATROSKA_TIME_BASE = "1/1000"
116
+
117
+
118
+ def expected_time_base(params: Dict[str, Any], ext: str) -> Optional[str]:
119
+ """The time base the joined output's video should read: the source's for MP4/MOV, whose time
120
+ scale execute() sets from it (-video_track_timescale), and Matroska's own for .mkv. Comparing a
121
+ .mkv against an MP4 source's 1/15360 failed every such cut, and only after the whole smart cut had
122
+ been built and checked (#462 A45)."""
123
+ if ext.lower() == ".mkv":
124
+ return MATROSKA_TIME_BASE
125
+ return params.get("time_base")
126
+
127
+
128
+ def _rate(params: Dict[str, Any]) -> Optional[Fraction]:
129
+ try:
130
+ q = Fraction(str(params.get("r_frame_rate") or ""))
131
+ except (ValueError, ZeroDivisionError):
132
+ return None
133
+ return q if q > 0 else None
134
+
135
+
136
+ def x264_line(params: Dict[str, Any], crf: int, preset: str) -> List[str]:
137
+ """libx264 arguments that reproduce the source stream's parameters (MATCH_FIELDS)."""
138
+ level = int(params.get("level") or 0)
139
+ depth = int(params.get("has_b_frames") or 0)
140
+ # the reorder depth decides how far each part's decode times run ahead of its presentation
141
+ # times; parts of different depth would collide in decode order at the join
142
+ b = "bframes=0" if depth == 0 else ("bframes=3:b-pyramid=none" if depth == 1 else "bframes=3:b-pyramid=normal")
143
+ args = ["-c:v", "libx264", "-preset", preset, "-crf", str(crf),
144
+ "-profile:v", SMART_PROFILES[str(params["profile"])], "-pix_fmt", params["pix_fmt"],
145
+ "-x264-params", f"{b}:open-gop=0"]
146
+ if level:
147
+ args += ["-level:v", f"{level // 10}.{level % 10}"]
148
+ # spelled the way the output options take them (#454: ffprobe's bt470m/bt470bg transfer and
149
+ # gbr space are not their names)
150
+ args += carried_tag_args([("-colorspace", params.get("color_space")), ("-color_primaries", params.get("color_primaries")),
151
+ ("-color_trc", params.get("color_transfer"))])
152
+ if params.get("color_range") and params.get("color_range") != "unknown":
153
+ args += ["-color_range", str(params["color_range"])]
154
+ return args
155
+
156
+
157
+ def frames_between(frames: List[float], lo: float, hi: Optional[float]) -> List[float]:
158
+ return [p for p in frames if p >= lo - 1e-6 and (hi is None or p < hi - 1e-6)]
159
+
160
+
161
+ def plan_segment(packets: List[Tuple[Any, Any, bool]], s: float, e: float, vend: Optional[float],
162
+ gop_is_open) -> List[Dict[str, Any]]:
163
+ """The parts of one segment, in order: {kind: reencode|copy, start, end (None: to the end of
164
+ the video), frames}. Raises SmartFallback when a keyframe the copy would start or stop at
165
+ opens its GOP or the packets around a cut were not read."""
166
+ frames = sorted(p[0] for p in packets if p[0] is not None)
167
+ keyidx = [i for i, p in enumerate(packets) if p[2] and p[0] is not None and p[1] is not None]
168
+ seg = frames_between(frames, s, e)
169
+ if not seg:
170
+ raise SmartFallback(f"no frame of the source lies in {s:.3f}-{e:.3f}s", "no_frames")
171
+ first, last = seg[0], seg[-1]
172
+ to_end = vend is not None and e >= vend - 1e-6
173
+ end_bound = None if to_end else next((p for p in frames if p >= e - 1e-6), None)
174
+ if end_bound is None and not to_end:
175
+ raise SmartFallback(f"the frames after {e:.3f}s were not read", "packets")
176
+ k1 = next((i for i in keyidx if packets[i][0] >= first - 1e-6), None)
177
+ if k1 is None or packets[k1][0] > last + 1e-6:
178
+ return [{"kind": "reencode", "start": first, "end": end_bound, "frames": len(seg)}]
179
+ if gop_is_open(packets, k1):
180
+ raise SmartFallback(f"the keyframe at {packets[k1][0]:.3f}s opens its GOP (frames decoded after it are shown "
181
+ "before it), so a copy cannot start there", "open_gop")
182
+ k1_pts = packets[k1][0]
183
+ # where the copy stops: the last keyframe presented at or before the end bound, decoded after K1.
184
+ # A segment that runs to the end of the video has no end bound to stop before: its copy runs
185
+ # to the end, and the last GOP is whole, so it is copied, not re-encoded as a tail (#462 A44)
186
+ stops = [i for i in keyidx if not to_end and packets[i][1] > packets[k1][1] + 1e-9
187
+ and (end_bound is None or packets[i][0] <= end_bound + 1e-6)]
188
+ k2 = stops[-1] if stops else None
189
+ if k2 is not None and gop_is_open(packets, k2):
190
+ raise SmartFallback(f"the keyframe at {packets[k2][0]:.3f}s opens its GOP, so the copy cannot stop there",
191
+ "open_gop")
192
+ copy_end = packets[k2][0] if k2 is not None else None
193
+ if copy_end is None and not to_end:
194
+ # no keyframe after K1 inside the segment: the copy would run past the end in its last GOP
195
+ return [{"kind": "reencode", "start": first, "end": end_bound, "frames": len(seg)}]
196
+ parts: List[Dict[str, Any]] = []
197
+ if first < k1_pts - 1e-6:
198
+ parts.append({"kind": "reencode", "start": first, "end": k1_pts,
199
+ "frames": len(frames_between(frames, first, k1_pts))})
200
+ parts.append({"kind": "copy", "start": k1_pts, "end": copy_end, "key_dts": packets[k1][1],
201
+ "end_dts": packets[k2][1] if k2 is not None else None})
202
+ if copy_end is not None and (end_bound is None or copy_end < end_bound - 1e-6):
203
+ tail = frames_between(frames, copy_end, end_bound)
204
+ if tail:
205
+ parts.append({"kind": "reencode", "start": copy_end, "end": end_bound, "frames": len(tail)})
206
+ return parts
207
+
208
+
209
+ def _framehashes(cmd: List[str], code: str) -> List[Tuple[int, str]]:
210
+ """(size, md5) per line of an ffmpeg -f framemd5 run (packets with -c copy, frames otherwise).
211
+ A run that failed is no evidence, even when the hashes it printed match: a classified failure
212
+ (a full disk) fails the run, any other is a fallback with `code`."""
213
+ proc = run(cmd, quiet=True, check=False)
214
+ fail_if_classified(proc)
215
+ if proc.returncode != 0:
216
+ lines = [ln.strip() for ln in (proc.stderr or "").splitlines() if ln.strip()]
217
+ raise SmartFallback(f"the check could not hash {cmd[cmd.index('-i') + 1]}: "
218
+ f"{lines[-1] if lines else f'exit code {proc.returncode}'}", code)
219
+ out = []
220
+ for line in (proc.stdout or "").splitlines():
221
+ if not line or line.startswith("#"):
222
+ continue
223
+ cols = [c.strip() for c in line.split(",")]
224
+ if len(cols) >= 6:
225
+ try:
226
+ out.append((int(cols[4]), cols[5]))
227
+ except ValueError:
228
+ continue
229
+ return out
230
+
231
+
232
+ _NORMALIZE = "h264_mp4toannexb,filter_units=remove_types=7|8|9"
233
+
234
+
235
+ def packet_hashes(path: str, seek: Optional[float] = None, t: Optional[float] = None) -> List[Tuple[int, str]]:
236
+ """The first video stream's packets as (size, md5) with SPS, PPS and delimiters removed."""
237
+ ff = require_tool("ffmpeg")
238
+ cmd = [ff, "-hide_banner", "-loglevel", "error", "-nostdin"]
239
+ if seek is not None:
240
+ cmd += ["-ss", f"{seek:.6f}"]
241
+ cmd += ["-i", path]
242
+ if t is not None:
243
+ cmd += ["-t", f"{t:.6f}"]
244
+ return _framehashes(cmd + ["-map", "0:v:0", "-c", "copy", "-bsf:v", _NORMALIZE, "-f", "framemd5", "-"], "packets")
245
+
246
+
247
+ def frame_hashes(path: str, at: Optional[float], count: int) -> List[Tuple[int, str]]:
248
+ """framemd5 of `count` decoded frames from `at` (seconds, an accurate seek; None from the start)."""
249
+ ff = require_tool("ffmpeg")
250
+ cmd = [ff, "-hide_banner", "-loglevel", "error", "-nostdin"]
251
+ if at is not None and at > 0:
252
+ cmd += ["-ss", f"{at:.6f}"]
253
+ return _framehashes(cmd + ["-i", path, "-map", "0:v:0", "-frames:v", str(count), "-flags:v", "+bitexact",
254
+ "-fflags", "+bitexact", "-f", "framemd5", "-"], "decode")
255
+
256
+
257
+ def output_pts(path: str) -> List[float]:
258
+ proc = run([require_tool("ffprobe"), "-v", "error", "-select_streams", "v:0", "-show_entries", "packet=pts_time",
259
+ "-of", "csv=p=0", path], quiet=True, check=False)
260
+ out = []
261
+ for line in (proc.stdout or "").split():
262
+ try:
263
+ out.append(float(line.strip(",")))
264
+ except ValueError:
265
+ continue
266
+ return sorted(out)
267
+
268
+
269
+ def _write(cmd: List[str], what: str) -> None:
270
+ """Run one of the smart cut's ffmpeg writes. A failure the runner classifies (a full disk, a
271
+ missing input) fails the run as it would anywhere; any other is a fallback with ffmpeg's reason
272
+ (x264 refusing the matched profile at --quality 0, a copy the muxer rejects)."""
273
+ proc = run(cmd, check=False)
274
+ fail_if_classified(proc)
275
+ if proc.returncode != 0:
276
+ lines = [ln.strip() for ln in (proc.stderr or "").splitlines() if ln.strip()]
277
+ why = next((ln for ln in lines if "rror" in ln), lines[-1] if lines else f"exit code {proc.returncode}")
278
+ raise SmartFallback(f"ffmpeg could not write {what}: {why}", "encode")
279
+
280
+
281
+ def _count(n_frames: int, rate: Fraction) -> str:
282
+ """A part's exact length for the concat list's `duration`, in seconds."""
283
+ return f"{float(Fraction(n_frames) / rate):.9f}"
284
+
285
+
286
+ def execute(src: str, segments: List[Tuple[float, float]], dst: str, meta: Dict[str, Any], params: Dict[str, Any],
287
+ packets, crf: int, preset: str, tmp: str, *, vend: Optional[float], gop_is_open, landing,
288
+ origin, declick: float, seek_margin: float) -> Dict[str, Any]:
289
+ """Write the smart cut of `segments` to `dst` and verify it (module docstring). Returns the
290
+ `smart` document; raises SmartFallback with the reason when it cannot be made or does not verify.
291
+ `landing(src, t)` is cut.seek_keyframe, `origin(path)` cut.file_origin."""
292
+ rate = _rate(params)
293
+ frame = float(1 / rate)
294
+ half = frame / 2
295
+ x264 = x264_line(params, crf, preset)
296
+ plans = [plan_segment(packets, s, e, vend, gop_is_open) for s, e in segments]
297
+ has_a = bool(meta.get("audio"))
298
+ for si, ((s, _), segment_parts) in enumerate(zip(segments, plans)):
299
+ # the sound is trimmed on the picture's grid from the segment's first frame; a picture that
300
+ # starts later than a frame after the segment (video that starts after its audio) would
301
+ # lose the sound before it, which the full re-encode keeps
302
+ late = segment_parts[0]["start"] - s
303
+ if has_a and late > frame + 1e-6:
304
+ raise SmartFallback(f"the picture of segment {si + 1} starts {late:.3f}s after it does, and the sound "
305
+ "before it is kept only by a full re-encode", "av_offset")
306
+ parts: List[Dict[str, Any]] = []
307
+ for si, segment_parts in enumerate(plans):
308
+ for part in segment_parts:
309
+ part = dict(part, segment=si, path=os.path.join(tmp, f"part{len(parts):03d}.ts"))
310
+ if part["kind"] == "reencode":
311
+ m = min(seek_margin, part["start"])
312
+ trim = f"trim=start={m - half:.6f}" + (f":end={m + part['frames'] * frame - half:.6f}")
313
+ _write(ffmpeg_base() + ["-ss", f"{part['start'] - m:.6f}", "-i", src, "-map", "0:v:0", "-an", "-sn", "-dn",
314
+ "-vf", f"{trim},setpts=PTS-STARTPTS", "-frames:v", str(part["frames"]),
315
+ "-fps_mode", "passthrough"] + x264 + ["-f", "mpegts", part["path"]],
316
+ f"the re-encoded part from {part['start']:.3f}s")
317
+ else:
318
+ target = part["start"] + _SEEK_PAST
319
+ landed = None if STATE.dry_run else landing(src, target)
320
+ if not STATE.dry_run and (landed is None or abs(landed[0] - part["start"]) > 1e-4):
321
+ raise SmartFallback(f"a stream copy from the keyframe at {part['start']:.3f}s lands at "
322
+ f"{'an unreadable place' if landed is None else f'{landed[0]:.3f}s'}", "seek")
323
+ part["seek"] = target
324
+ part["t"] = None if part["end_dts"] is None else part["end_dts"] - target - _DTS_MARGIN
325
+ _write(ffmpeg_base() + ["-ss", f"{target:.6f}", "-i", src] + ([] if part["t"] is None else ["-t", f"{part['t']:.6f}"])
326
+ + ["-map", "0:v:0", "-an", "-sn", "-dn", "-c", "copy", "-f", "mpegts", part["path"]],
327
+ f"the copied part from {part['start']:.3f}s")
328
+ if not STATE.dry_run:
329
+ written = output_pts(part["path"])
330
+ if part["kind"] == "copy":
331
+ expected = None if part["end"] is None else round((part["end"] - part["start"]) * rate)
332
+ if expected is not None and len(written) != expected:
333
+ raise SmartFallback(f"the copy from {part['start']:.3f}s holds {len(written)} frames where the "
334
+ f"source has {expected}", "copy_count")
335
+ part["frames"] = len(written)
336
+ elif len(written) != part["frames"]:
337
+ raise SmartFallback(f"the re-encode from {part['start']:.3f}s holds {len(written)} frames, not "
338
+ f"{part['frames']}", "encode_count")
339
+ if part["kind"] == "reencode":
340
+ got = stream_params(part["path"]) or {}
341
+ diff = mismatches(params, got)
342
+ if diff:
343
+ raise SmartFallback("the re-encoded part does not match the source: " + ", ".join(diff), "params_mismatch")
344
+ parts.append(part)
345
+ listfile = os.path.join(tmp, "smart.txt")
346
+ with open(listfile, "w", encoding="utf-8") as fh:
347
+ for part in parts:
348
+ fh.write(concat_list_line(part["path"]) + "\n")
349
+ if part.get("frames"):
350
+ fh.write(f"duration {_count(part['frames'], rate)}\n")
351
+ ext = os.path.splitext(dst)[1].lower()
352
+ cmd = ffmpeg_base() + ["-f", "concat", "-safe", "0", "-i", listfile]
353
+ graph: List[str] = []
354
+ if has_a:
355
+ # the sound of each segment from the source, on the picture's frame grid, encoded once
356
+ pads = ""
357
+ for i, (s, e) in enumerate(segments):
358
+ first = plans[i][0]["start"]
359
+ last = plans[i][-1]
360
+ end = last["end"] if last["end"] is not None else e
361
+ m = min(seek_margin, s)
362
+ cmd += ["-ss", f"{s - m:.6f}", "-t", f"{m + (end - s) + 1.0:.6f}", "-i", src]
363
+ a, b = m + (first - s), m + (end - s)
364
+ fade = min(declick, (b - a) / 2)
365
+ fades = (f",afade=t=in:st=0:d={fade:.6f}" if fade > 0 and i > 0 else "")
366
+ fades += (f",afade=t=out:st={b - a - fade:.6f}:d={fade:.6f}" if fade > 0 and i < len(segments) - 1 else "")
367
+ # padded to its picture's length: sound that ends early (a track shorter than the
368
+ # picture) must not pull the next segment's sound forward
369
+ graph.append(f"[{i + 1}:a:0]atrim=start={a:.6f}:end={b:.6f},asetpts=PTS-{a:.6f}/TB,"
370
+ f"aresample=async=1:first_pts=0,apad=whole_dur={b - a:.6f}{fades}[a{i}]")
371
+ pads += f"[a{i}]"
372
+ graph.append(f"{pads}concat=n={len(segments)}:v=0:a=1[a]")
373
+ cmd += ["-filter_complex", ";".join(graph), "-map", "0:v:0", "-map", "[a]"] + aac_args()
374
+ else:
375
+ cmd += ["-map", "0:v:0"]
376
+ cmd += ["-c:v", "copy", "-bsf:v", "filter_units=remove_types=9", "-sn", "-dn"]
377
+ tb = str(params.get("time_base") or "")
378
+ if ext in (".mp4", ".mov", ".m4v"):
379
+ if tb.startswith("1/"):
380
+ cmd += ["-video_track_timescale", tb[2:]]
381
+ cmd += ["-tag:v", "avc1", "-movflags", "+faststart"]
382
+ _write(cmd + [dst], "the joined parts")
383
+ doc: Dict[str, Any] = {
384
+ "applied": True,
385
+ "parts": [{"segment": p["segment"] + 1, "kind": p["kind"], "start": round(p["start"], 6),
386
+ "end": None if p["end"] is None else round(p["end"], 6), "frames": p.get("frames")} for p in parts],
387
+ "reencoded_frames": sum(p.get("frames") or 0 for p in parts if p["kind"] == "reencode"),
388
+ "copied_frames": sum(p.get("frames") or 0 for p in parts if p["kind"] == "copy"),
389
+ "matched": {f: params.get(f) for f in MATCH_FIELDS},
390
+ "encoder": x264,
391
+ }
392
+ if STATE.dry_run:
393
+ doc["checks"] = None
394
+ return doc
395
+ doc["checks"] = verify(src, dst, parts, params, rate, origin)
396
+ doc["time_base"] = doc["checks"]["time_base"]
397
+ return doc
398
+
399
+
400
+ def verify(src: str, dst: str, parts: List[Dict[str, Any]], params: Dict[str, Any], rate: Fraction, origin) -> Dict[str, Any]:
401
+ """The checks in the module docstring; raises SmartFallback on the first that fails."""
402
+ frame = float(1 / rate)
403
+ half = frame / 2
404
+ pts = output_pts(dst)
405
+ expected = sum(p["frames"] for p in parts)
406
+ if len(pts) != expected:
407
+ raise SmartFallback(f"the output holds {len(pts)} frames where the parts hold {expected}", "frames")
408
+ worst = max((abs(t - pts[0] - i * frame) for i, t in enumerate(pts)), default=0.0)
409
+ if worst >= half:
410
+ at = next(i for i, t in enumerate(pts) if abs(t - pts[0] - i * frame) >= half)
411
+ raise SmartFallback(f"frame {at} of the output is presented at {pts[at] - pts[0]:.6f}s, off the "
412
+ f"{frame:.6f}s grid (a gap or a repeated frame at a join)", "frames")
413
+ out_packets = packet_hashes(dst)
414
+ if len(out_packets) != expected:
415
+ raise SmartFallback(f"the output holds {len(out_packets)} video packets where the parts hold {expected}", "packets")
416
+ dst_origin = origin(dst)
417
+ offset, copied, decoded = 0, 0, 0
418
+ for p in parts:
419
+ n = p["frames"]
420
+ at_out = pts[offset] - dst_origin - half
421
+ if p["kind"] == "copy":
422
+ source = packet_hashes(src, p["seek"], p["t"])
423
+ if source != out_packets[offset:offset + n]:
424
+ bad = next((i for i, (x, y) in enumerate(zip(source, out_packets[offset:offset + n])) if x != y),
425
+ min(len(source), n))
426
+ raise SmartFallback(f"copied packet {bad} of the part from {p['start']:.3f}s differs from the source's",
427
+ "packets")
428
+ copied += n
429
+ g = min(n, DECODE_CHECK_MAX_FRAMES)
430
+ want = frame_hashes(src, p["start"] - half, g)
431
+ else:
432
+ g = n
433
+ want = frame_hashes(p["path"], None, g)
434
+ got = frame_hashes(dst, at_out, g)
435
+ # a short list on both sides (a frame that did not decode) is not a match of g frames
436
+ if len(want) != g or want != got:
437
+ raise SmartFallback(f"the frames decoded from the output's {p['kind']} part at {pts[offset] - pts[0]:.3f}s "
438
+ f"differ from the {'source' if p['kind'] == 'copy' else 'encoded part'}", "decode")
439
+ decoded += g
440
+ offset += n
441
+ out_params = stream_params(dst) or {}
442
+ want_tb = expected_time_base(params, os.path.splitext(dst)[1])
443
+ if out_params.get("time_base") != want_tb:
444
+ raise SmartFallback(f"the output's time base is {out_params.get('time_base')}, where "
445
+ f"{want_tb} was expected (the source's is {params.get('time_base')})", "time_base")
446
+ diff = mismatches(params, out_params)
447
+ if diff:
448
+ raise SmartFallback("the output's stream does not match the source: " + ", ".join(diff), "params_mismatch")
449
+ return {"frames": expected, "grid_worst_seconds": round(worst, 6), "copied_packets_equal": copied,
450
+ "frames_decoded_equal": decoded, "time_base": out_params.get("time_base")}