@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,1613 @@
1
+ """ffprobe and the measured facts read back off a file: the probe document every script starts
2
+ from, the verification every script ends with, and the level/waveform measurements.
3
+
4
+ Reading only -- the choices made from these facts live in decision.py.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import math
10
+ import os
11
+ import re
12
+ import stat
13
+ import statistics
14
+ import sys
15
+ from array import array
16
+ from fractions import Fraction
17
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
18
+ from _common.emit import die, note, refuse, warn
19
+ from _common.runner import ffmpeg_failure_extra, refuse_denied_input, STATE, dry_run_input_pending, register_plan_input, require_tool, run, run_analysis, still_input_args
20
+
21
+ # The streams probe() describes, as stream specifiers: its `video` is the first picture that is not
22
+ # a cover (`V`), its `audio` the first sound stream. Without a -map, FFmpeg picks the largest
23
+ # picture and the sound with the default disposition or the most channels, so on a file with two
24
+ # of either a tool measured one stream and wrote another: loudness measured track 1 and applied the
25
+ # gain to track 0, cut and crop wrote the larger picture they never probed (A110, A118, A128, A258).
26
+ PROBED_VIDEO = "V:0"
27
+ PROBED_AUDIO = "a:0"
28
+
29
+
30
+ def fingerprint(path: str, *, complete: bool = False) -> Dict[str, Any]:
31
+ """Size plus a sha256 over the first and last 8 MiB: enough to notice a re-export, a re-trim
32
+ or a swapped file, cheap enough for a multi-GB source (hashing a whole master would make
33
+ planning slower than the edit). Sequence plans also request a full-file hash."""
34
+ import hashlib
35
+ h = hashlib.sha256()
36
+ chunk = 8 * 1024 * 1024
37
+ # A file could have been replaced by a FIFO since the caller checked its type.
38
+ def open_without_waiting(name, flags):
39
+ return os.open(name, flags | getattr(os, "O_NONBLOCK", 0))
40
+
41
+ with open(path, "rb", opener=open_without_waiting) as f:
42
+ st = os.fstat(f.fileno())
43
+ if not stat.S_ISREG(st.st_mode):
44
+ raise OSError(f"{path!r} is not a regular file")
45
+ h.update(f.read(chunk))
46
+ if st.st_size > 2 * chunk:
47
+ f.seek(-chunk, os.SEEK_END)
48
+ h.update(f.read(chunk))
49
+ elif st.st_size > chunk:
50
+ h.update(f.read())
51
+ result = {"path": os.path.abspath(path), "size": st.st_size, "sha256_head_tail": h.hexdigest()}
52
+ if complete:
53
+ if st.st_size > 2 * chunk:
54
+ whole = hashlib.sha256()
55
+ f.seek(0)
56
+ for data in iter(lambda: f.read(chunk), b""):
57
+ whole.update(data)
58
+ result["sha256_full"] = whole.hexdigest()
59
+ else:
60
+ result["sha256_full"] = result["sha256_head_tail"]
61
+ return result
62
+
63
+
64
+ def decode_pcm_mono(path: str, sample_rate: int, seconds: Optional[float] = None, start: float = 0.0,
65
+ *, check: bool = True) -> "Sequence[float]":
66
+ """Decode (part of) a file's audio to mono float samples in [-1, 1) at `sample_rate` via a
67
+ single ffmpeg pass under --timeout. Shared by scenes.py (audio envelope for cut scoring) and
68
+ sync.py (cross-correlation); an undecodable input is kind ffmpeg when check=True, else [].
69
+ The samples are on the file's clock: a sound that starts late is padded at its head.
70
+
71
+ The samples are an array('f'), 4 bytes each: a list of Python floats took about 32 (24 for the
72
+ float, 8 for the slot), so scenes.py held ~2.3 GB per hour of audio at 8 kHz + 22.05 kHz and
73
+ multicam --switch energy one such list per camera (A140). An s16 sample divided by 32768 is
74
+ exact in a float32, so every value read back is the double the list held."""
75
+ register_plan_input(path)
76
+ ffmpeg = require_tool("ffmpeg")
77
+ cmd = [ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin"]
78
+ if start:
79
+ cmd += ["-ss", f"{start:.3f}"]
80
+ cmd += ["-i", path]
81
+ if seconds is not None:
82
+ cmd += ["-t", f"{seconds:.3f}"]
83
+ # first_pts=0 pads a sound that starts after the file's start (or after `start`) with silence,
84
+ # so sample i is at start + i / sample_rate on the file's clock: sync.py measured a track that
85
+ # starts 0.3 s late 0.279 s off, and --replace-audio placed it that far late (#409)
86
+ # the first audio track, the one probe() describes (default selection takes the most channels)
87
+ cmd += ["-map", f"0:{PROBED_AUDIO}", "-vn", "-af", "aresample=async=1:first_pts=0", "-ac", "1", "-ar", str(sample_rate), "-f", "s16le", "-"]
88
+ proc = run_analysis(cmd, check=False, text=False)
89
+ if proc.returncode != 0 or not proc.stdout:
90
+ if check:
91
+ die(f"could not decode audio from {path}:\n{proc.stderr.decode(errors='replace').strip()}", kind="ffmpeg", **ffmpeg_failure_extra(proc.stderr.decode(errors="replace")))
92
+ return []
93
+ data, proc = proc.stdout, None
94
+ pcm = array("h")
95
+ pcm.frombytes(memoryview(data)[: len(data) // 2 * 2])
96
+ del data
97
+ if sys.byteorder == "big":
98
+ pcm.byteswap() # s16le on the pipe
99
+ return array("f", (v / 32768.0 for v in pcm))
100
+
101
+
102
+ def rms_envelope(samples: Sequence[float], step: int, *, full_blocks_only: bool = False, remove_mean: bool = False) -> List[float]:
103
+ """RMS per block of `step` samples. full_blocks_only drops a short tail block (sync.py: every
104
+ block must be the same length for the correlation); remove_mean subtracts the envelope's mean
105
+ (sync.py: so silence does not correlate). scenes.py keeps the tail and the absolute level."""
106
+ step = max(1, int(step))
107
+ n = len(samples)
108
+ stop = n - step + 1 if full_blocks_only else n
109
+ env: List[float] = []
110
+ for i in range(0, max(0, stop), step):
111
+ block = samples[i:i + step]
112
+ env.append(math.sqrt(sum(x * x for x in block) / len(block)))
113
+ if remove_mean and env:
114
+ mean = sum(env) / len(env)
115
+ env = [e - mean for e in env]
116
+ return env
117
+
118
+
119
+ # the audio members of MEDIA_EXT: every audio file this skill reads, a wider set than the audio
120
+ # outputs it writes (AUDIO_CODECS / is_audio_output() -- no .wma there: an output named so is
121
+ # refused, decision.UNWRITTEN_AUDIO_EXT)
122
+ AUDIO_MEDIA_EXT = {".wav", ".flac", ".mp3", ".m4a", ".aac", ".ogg", ".opus", ".aif", ".aiff", ".caf", ".mka", ".wma"}
123
+ MEDIA_EXT = {".mp4", ".mov", ".mkv", ".webm", ".m4v", ".avi", ".ts", ".mts", ".m2ts", ".mxf", ".3gp", ".wmv", ".gif",
124
+ ".png", ".jpg", ".jpeg", ".webp"} | AUDIO_MEDIA_EXT
125
+
126
+
127
+ def decode_gray_frames(path: str, fps: float, width: int, height: int, *, start: float = 0.0,
128
+ seconds: "Optional[float]" = None, check: bool = True) -> "List[bytes]":
129
+ """Decode `path` to raw 8-bit grayscale frames at a low `fps`/`width`x`height`, one ffmpeg
130
+ pass to stdout. Used by scenes.py --shots (per-shot flow label) and cropdetect.py
131
+ --motion-centre (motion centroid): both need pixel data, not a filter's own summary number,
132
+ but at 1.18.0's resolutions (tens of pixels a side, a few fps) a whole shot is a few KB, so
133
+ piping raw frames through Python stays cheap and needs no extra dependency."""
134
+ ffmpeg = require_tool("ffmpeg")
135
+ cmd = [ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin"]
136
+ if start:
137
+ cmd += ["-ss", f"{start:.3f}"]
138
+ cmd += ["-i", path]
139
+ if seconds is not None:
140
+ cmd += ["-t", f"{max(0.0, seconds):.3f}"]
141
+ cmd += ["-map", f"0:{PROBED_VIDEO}", "-vf", f"fps={fps:g},scale={width}:{height}:flags=area,format=gray",
142
+ "-f", "rawvideo", "-"]
143
+ proc = run_analysis(cmd, check=False, text=False)
144
+ if proc.returncode != 0 or not proc.stdout:
145
+ if check:
146
+ die(f"could not decode frames from {path}:\n{proc.stderr.decode(errors='replace').strip()}", kind="ffmpeg", **ffmpeg_failure_extra(proc.stderr.decode(errors="replace")))
147
+ return []
148
+ frame_size = width * height
149
+ data = proc.stdout
150
+ return [data[i:i + frame_size] for i in range(0, len(data) - frame_size + 1, frame_size)]
151
+
152
+
153
+ def _output_failed(path: str, why: str) -> "None":
154
+ """An ffmpeg run reported success but the artifact is not usable: say so, and do not leave a
155
+ 0-byte file behind that a later step could mistake for a result."""
156
+ try:
157
+ if os.path.exists(path) and os.path.getsize(path) == 0:
158
+ os.remove(path)
159
+ why += " (empty file removed)"
160
+ except OSError:
161
+ pass
162
+ die(f"output verification failed: {path}: {why}", kind="output")
163
+
164
+
165
+ def verify_output(path: str) -> Dict[str, Any]:
166
+ """The success criterion for every writing tool: the file exists, is not empty and ffprobe
167
+ can read at least one stream from it. Non-media artifacts (srt, edl, html, md) only need to
168
+ exist and be non-empty. Returns the probe (empty dict for non-media)."""
169
+ if not os.path.isfile(path):
170
+ _output_failed(path, "not written")
171
+ if os.path.getsize(path) == 0:
172
+ _output_failed(path, "0 bytes")
173
+ if os.path.splitext(path)[1].lower() not in MEDIA_EXT:
174
+ return {}
175
+ meta = probe(path, role="output")
176
+ if not meta.get("video") and not meta.get("audio"):
177
+ _output_failed(path, "no video or audio stream")
178
+ return meta
179
+
180
+
181
+ _TIMECODE = re.compile(r"^(\d{2}):([0-5]\d):([0-5]\d)([:;.])(\d{2,3})$")
182
+
183
+
184
+ def _tag(entry: Dict[str, Any], key: str) -> Optional[str]:
185
+ return next((v for k, v in (entry.get("tags") or {}).items() if k.lower() == key), None)
186
+
187
+
188
+ def _nominal_fps(video: Optional[Dict[str, Any]]) -> Optional[int]:
189
+ """The integer timecode rate of the picture (30 for 29.97), from avg_frame_rate, else
190
+ r_frame_rate: the order probe()'s `fps` uses, which the timeline export validates against."""
191
+ for key in ("avg_frame_rate", "r_frame_rate"):
192
+ try:
193
+ num, _, den = str((video or {}).get(key) or "").partition("/")
194
+ rate = float(num) / float(den or 1)
195
+ except (ValueError, ZeroDivisionError):
196
+ continue
197
+ if 0 < rate <= 240:
198
+ return int(round(rate))
199
+ return None
200
+
201
+
202
+ def start_timecode(streams: List[Dict[str, Any]], fmt: Dict[str, Any],
203
+ video: Optional[Dict[str, Any]]) -> Dict[str, Any]:
204
+ """The first well-formed `timecode` tag, from the video stream, then a `tmcd` data stream,
205
+ then the container: {value, drop_frame, source}. `drop_frame` is the `;` (or `.`) separator
206
+ before the frames field; `source` is `stream:<ffprobe index>` or `format`. None when no
207
+ source carries one (all three null). A tag that is not HH:MM:SS[:;.]FF, or whose frames field
208
+ the picture's rate cannot reach, is skipped, not repaired."""
209
+ candidates = []
210
+ if video is not None:
211
+ candidates.append((video, f"stream:{video.get('index')}"))
212
+ candidates += [(s, f"stream:{s.get('index')}") for s in streams
213
+ if s.get("codec_type") == "data" and str(s.get("codec_tag_string", "")).lower() == "tmcd"]
214
+ candidates.append((fmt, "format"))
215
+ nominal = _nominal_fps(video)
216
+ for entry, source in candidates:
217
+ value = _tag(entry, "timecode")
218
+ m = _TIMECODE.match(value.strip()) if isinstance(value, str) else None
219
+ # a frames field the picture's rate cannot reach (frame 29 at 25 fps) is no timecode
220
+ # either: the next candidate (a tmcd track's own tag) may still hold a real one (#427)
221
+ if m and not (nominal and int(m.group(5)) >= nominal):
222
+ return {"value": value.strip(), "drop_frame": m.group(4) in ";.", "source": source}
223
+ return {"value": None, "drop_frame": None, "source": None}
224
+
225
+
226
+ # EBU R128 integrated loudness is gated over 400 ms blocks: sound shorter than one has a true peak
227
+ # and no integrated loudness. A longer track can read -inf too (every block under the absolute
228
+ # gate), so "too short" is decided on the sound's length, never on a finite peak alone.
229
+ LOUDNESS_BLOCK_SECONDS = 0.4
230
+
231
+
232
+ def shorter_than_a_loudness_block(length: "Optional[float]") -> bool:
233
+ return length is not None and 0 < length < LOUDNESS_BLOCK_SECONDS
234
+
235
+
236
+ # ffmpeg's log prefix for a component, with the address of its context: `[mov,mp4,m4a @ 0x55d1]`
237
+ # (no `0x` on Windows). It differs on every run and tells a caller nothing.
238
+ _LOG_CONTEXT_RE = re.compile(r"\[[^\]\n]*@ (?:0x)?[0-9A-Fa-f]+\]\s*")
239
+
240
+
241
+ def _refuse_unusable_input(path: str) -> None:
242
+ """Say what an input that cannot be media is, before ffprobe is asked (#558): a directory, an
243
+ empty file (the usual trace of a recording, download or TTS step that failed after creating
244
+ its file) or a file the user may not read. Each reached ffprobe and came back as its raw
245
+ text ("moov atom not found", "Is a directory") with no reason and no hint; join.py's
246
+ preflight has worded the first two itself since 2.2."""
247
+ if os.path.isdir(path):
248
+ refuse("input", "input_is_directory", f"input is a directory, not a file: {path}",
249
+ hint="pass one media file; verify.py and batch.py take a folder", path=path)
250
+ if not os.path.isfile(path):
251
+ return # a pipe or a device: run() refuses it (media_path_not_a_file)
252
+ refuse_denied_input(path)
253
+ try:
254
+ empty = os.path.getsize(path) == 0
255
+ except OSError:
256
+ return
257
+ if empty:
258
+ refuse("input", "input_empty", f"input is empty (0 bytes): {path}",
259
+ hint="the step that should have written it wrote nothing: record, download or render it again", path=path)
260
+
261
+
262
+ def _refuse_not_media(path: str, stderr: str) -> "None":
263
+ """ffprobe could not read an input: `input_not_media`, with ffprobe's own lines as the detail
264
+ (their `[demuxer @ 0x...]` prefixes removed, #558) and a hint. The message still opens with
265
+ "ffprobe failed on PATH", which verify.py's report rows and callers have matched since 1.x."""
266
+ lines = [_LOG_CONTEXT_RE.sub("", ln).strip() for ln in (stderr or "").strip().splitlines()]
267
+ detail = "; ".join(dict.fromkeys(ln for ln in lines if ln)) or "ffprobe gave no reason"
268
+ hint = ("pass a video, audio or picture file; a recording or a copy that was cut short reads this way too "
269
+ "(\"moov atom not found\") and has to be copied again from its source")
270
+ refuse("input", "input_not_media", f"ffprobe failed on {path}: not a media file ffprobe can read ({detail})",
271
+ hint=hint, path=path)
272
+
273
+
274
+ def probe(path: str, role: str = "input", *, required: bool = True, advise_deinterlace: bool = False) -> Dict[str, Any]:
275
+ """Return a compact, script-friendly description of a media file.
276
+
277
+ role="output" marks a file this tool just wrote: a read failure is then reported as an
278
+ output-verification failure (kind "output") instead of an input problem.
279
+ For an aggregate's evidence check, required=False returns {} on an unreadable file."""
280
+ if not os.path.exists(path) or (role == "output" and STATE.dry_run):
281
+ if not required:
282
+ return {}
283
+ if role == "output" and not STATE.dry_run:
284
+ _output_failed(path, "not written")
285
+ if role == "input":
286
+ # a file behind a directory the user may not search is not "not found", and not an
287
+ # earlier dry-run stage's output either (#558)
288
+ refuse_denied_input(path)
289
+ if STATE.dry_run:
290
+ # also for an output path that holds a file: a dry run did not write it, and reading it
291
+ # reported an earlier run's file as this plan's result (#403: cut.py's output_duration)
292
+ # width/height/fps are honestly 0/0/0.0 -- "not measured", matching duration/size_bytes
293
+ # below -- because this is a dry run: the file doesn't exist yet, so there is nothing to
294
+ # probe. Earlier this stub used plausible-looking placeholders (1920x1080x30.0) instead,
295
+ # which some tools' dry-run summary line echoed verbatim as if it were a real computed
296
+ # preview (#77). That was reverted once, because a couple of call sites divided by these
297
+ # values for aspect-ratio math and crashed on a real 0 (join.py, fit.py); those call
298
+ # sites are now guarded to treat 0 as "unknown" and fall back sanely instead of dividing
299
+ # by it, so the stub can finally report the honest, unknown value.
300
+ return {"file": path, "dry_run": True, "format": None, "duration": 0.0, "size_bytes": 0, "bitrate": None,
301
+ "video": {"codec": None, "width": 0, "height": 0, "fps": 0.0, "pix_fmt": None, "hdr": False, "bt2020_or_hdr": False,
302
+ "color_transfer": None, "color_primaries": None, "rotation": 0, "variable_frame_rate_suspected": False},
303
+ "audio": {"codec": None, "channels": 0, "sample_rate": 0}, "subtitle_streams": 0, "data_streams": 0}
304
+ die(f"input not found: {path}")
305
+ if role == "input":
306
+ if not required and (os.path.isdir(path) or (os.path.isfile(path) and os.path.getsize(path) == 0)):
307
+ return {} # an optional probe reports "not usable" as {} (as a failed ffprobe did), never exits
308
+ _refuse_unusable_input(path)
309
+ ffprobe = require_tool("ffprobe")
310
+ proc = run(
311
+ [ffprobe, "-v", "error",
312
+ "-print_format", "json", "-show_format", "-show_streams", "-show_chapters", path],
313
+ quiet=True,
314
+ check=False,
315
+ )
316
+ if proc.returncode != 0:
317
+ if not required:
318
+ return {}
319
+ if role == "output":
320
+ _output_failed(path, f"ffprobe cannot read it:\n{proc.stderr.strip()}")
321
+ _refuse_not_media(path, proc.stderr)
322
+ if role == "input":
323
+ register_plan_input(path)
324
+ if not (proc.stdout or "").strip():
325
+ if not required:
326
+ return {}
327
+ # ffprobe exited 0 and printed nothing we could read. Before 1.17.1 that produced a
328
+ # SUCCESS document of nulls -- "?s | no video | no audio", exit 0 -- which is how #234
329
+ # showed up on a Windows cp932 machine: the capture decoded ffprobe's UTF-8 JSON with the
330
+ # locale code page, the reader thread raised UnicodeDecodeError and stdout came back
331
+ # empty. Every child capture is decoded as UTF-8 with errors="replace" now; if a document
332
+ # still does not arrive, refuse rather than report an unmeasured file as measured.
333
+ msg = (f"ffprobe printed no output for {path}: its JSON could not be read (a decoding or "
334
+ "pipe failure, not a measurement)")
335
+ if proc.stderr.strip():
336
+ msg += f"\n{proc.stderr.strip()}"
337
+ if role == "output":
338
+ _output_failed(path, msg)
339
+ die(msg, kind="input")
340
+ try:
341
+ raw = json.loads(proc.stdout or "{}")
342
+ except ValueError as e:
343
+ if not required:
344
+ return {}
345
+ if role == "output":
346
+ _output_failed(path, f"ffprobe printed unreadable JSON: {e}")
347
+ die(f"ffprobe printed unreadable JSON for {path}: {e}", kind="ffmpeg")
348
+ fmt = raw.get("format", {})
349
+ streams = raw.get("streams", [])
350
+ video = next((s for s in streams if s.get("codec_type") == "video" and s.get("disposition", {}).get("attached_pic", 0) == 0), None)
351
+ audio = next((s for s in streams if s.get("codec_type") == "audio"), None)
352
+ subs = [s for s in streams if s.get("codec_type") == "subtitle"]
353
+ data_stream_count = sum(1 for s in streams if s.get("codec_type") in ("data", "attachment"))
354
+
355
+ duration = _to_float(fmt.get("duration"))
356
+ if duration is None and video:
357
+ duration = _to_float(video.get("duration"))
358
+ if duration is None and audio:
359
+ duration = _to_float(audio.get("duration"))
360
+ if duration and STATE.duration_hint is None:
361
+ STATE.duration_hint = duration
362
+
363
+ out: Dict[str, Any] = {
364
+ "file": path,
365
+ "format": fmt.get("format_name"),
366
+ "duration": duration,
367
+ # where the file's timeline starts (MPEG-TS starts at 1.4 s, not 0): a -ss and a cut's
368
+ # --start count from here
369
+ "start_time": _to_float(fmt.get("start_time")),
370
+ "size_bytes": _to_int(fmt.get("size")),
371
+ "bitrate": _to_int(fmt.get("bit_rate")),
372
+ "video": None,
373
+ "audio": None,
374
+ "subtitle_streams": len(subs),
375
+ "data_streams": data_stream_count,
376
+ # how many picture and sound streams the file carries (a cover picture is not a video
377
+ # stream); the streams check compares them with what the operation should have written
378
+ "stream_counts": {
379
+ "video": sum(1 for s in streams if s.get("codec_type") == "video" and s.get("disposition", {}).get("attached_pic", 0) == 0),
380
+ "audio": sum(1 for s in streams if s.get("codec_type") == "audio"),
381
+ },
382
+ # container-level chapter markers and the common tags, so metadata.py's result is
383
+ # verifiable the same way every other tool's is (additive keys, 1.x-safe)
384
+ "chapters": [{
385
+ "index": n,
386
+ "start": _to_float(ch.get("start_time")),
387
+ "end": _to_float(ch.get("end_time")),
388
+ "title": (ch.get("tags") or {}).get("title"),
389
+ } for n, ch in enumerate(raw.get("chapters") or [])],
390
+ "tags": {k.lower(): v for k, v in (fmt.get("tags") or {}).items() if k.lower() in ("title", "artist", "album", "comment", "date", "genre")},
391
+ # the source's start timecode (a camera's 10:00:00:00), for an edit list or an NLE relink
392
+ "timecode": start_timecode(streams, fmt, video),
393
+ # every subtitle stream in file order: index n here is `-map 0:s:n`
394
+ "subtitle_stream_details": [{
395
+ "index": n,
396
+ "codec": s.get("codec_name"),
397
+ "language": (s.get("tags") or {}).get("language"),
398
+ "title": (s.get("tags") or {}).get("title"),
399
+ # the stream's default disposition as the file states it (caption.py --mode mux
400
+ # reports a kept track's from here, A60)
401
+ "default": bool((s.get("disposition") or {}).get("default")),
402
+ } for n, s in enumerate(subs)],
403
+ }
404
+ if video:
405
+ if advise_deinterlace and video.get("field_order") in ("tt", "bb", "tb", "bt"):
406
+ note("Input video is marked interlaced. For progressive editing, run deinterlace.py first.")
407
+ r_rate = _fraction(video.get("r_frame_rate"))
408
+ avg_rate = _fraction(video.get("avg_frame_rate"))
409
+ fps = float(avg_rate) if avg_rate else (float(r_rate) if r_rate else None)
410
+ vfr = bool(r_rate and avg_rate and abs(float(r_rate) - float(avg_rate)) > 0.01)
411
+ w, h = _to_int(video.get("width")), _to_int(video.get("height"))
412
+ if not (w and h) and _is_still(fmt, video):
413
+ if not required:
414
+ return {}
415
+ # audit A184 (#465): a text file named .png reaches the image demuxer, which lists a
416
+ # png stream it could not decode as 0x0. That was reported as a measured picture
417
+ # (probe.py exit 0) and divided by in insert.py and check.py (tracebacks, no JSON).
418
+ # A video container's stream with no size is left to the tool that reads it.
419
+ msg = (f"{path} is not a picture ffmpeg can decode: its image demuxer ({fmt.get('format_name')}) found a "
420
+ f"{video.get('codec_name') or 'picture'} stream with no frame size"
421
+ + (f"\n{proc.stderr.strip()}" if proc.stderr.strip() else ""))
422
+ if role == "output":
423
+ _output_failed(path, msg)
424
+ refuse("input", "still_unreadable", msg, path=path, format=fmt.get("format_name"),
425
+ codec=video.get("codec_name"))
426
+ rotation = 0
427
+ for sd in video.get("side_data_list", []) or []:
428
+ if "rotation" in sd:
429
+ rotation = int(round(float(sd["rotation"])))
430
+ if "rotate" in (video.get("tags") or {}):
431
+ try:
432
+ rotation = int(video["tags"]["rotate"])
433
+ except ValueError:
434
+ pass
435
+ if not rotation and _is_still(fmt, video):
436
+ # an EXIF Orientation reaches ffmpeg as the decoded frame's display matrix, not as
437
+ # stream side data, so -show_streams has no rotation for a phone's portrait JPEG;
438
+ # ffmpeg still turns the picture upright on decode, and every tool that sizes the
439
+ # frame has to know it did (#411)
440
+ rotation = _still_rotation(path)
441
+ pix = video.get("pix_fmt") or ""
442
+ trc = video.get("color_transfer") or ""
443
+ prim = video.get("color_primaries") or ""
444
+ hdr = trc in ("smpte2084", "arib-std-b67") or prim == "bt2020"
445
+ dovi = None
446
+ for sd in video.get("side_data_list", []) or []:
447
+ if "dv_profile" in sd or "DOVI" in str(sd.get("side_data_type", "")):
448
+ dovi = {"profile": sd.get("dv_profile"), "level": sd.get("dv_level"), "bl_compatibility_id": sd.get("dv_bl_signal_compatibility_id")}
449
+ if dovi: # a Dolby Vision stream is HDR even when its base layer tags are missing
450
+ hdr = True
451
+ hdr_signal = trc in ("smpte2084", "arib-std-b67") or bool(dovi)
452
+ out["video"] = {
453
+ "codec": video.get("codec_name"),
454
+ "profile": video.get("profile"),
455
+ "width": w,
456
+ "height": h,
457
+ "display_aspect": video.get("display_aspect_ratio") or _aspect_string(w, h),
458
+ # the stored pixel's shape (DV, HDV 1440x1080, DVD and XDCAM store non-square pixels);
459
+ # every tool that sizes or draws on the picture works on square pixels at the display
460
+ # aspect (square_pixels() / display_size() below)
461
+ "sample_aspect_ratio": _sar_string(video.get("sample_aspect_ratio")),
462
+ "fps": round(fps, 3) if fps else None,
463
+ "r_frame_rate": video.get("r_frame_rate"),
464
+ "avg_frame_rate": video.get("avg_frame_rate"),
465
+ "variable_frame_rate_suspected": vfr,
466
+ "pix_fmt": video.get("pix_fmt"),
467
+ "bit_depth": _bit_depth(pix),
468
+ # 2.0: `hdr` is true only for a PQ / HLG transfer or Dolby Vision, i.e. a genuinely HDR
469
+ # signal (1.x also counted BT.2020 primaries on an SDR transfer). `hdr_signal` (1.9) is
470
+ # kept, equal to it, for callers that moved to it. `bt2020_or_hdr` is the 1.x meaning,
471
+ # which every editing tool still routes on: a BT.2020 SDR source goes through the
472
+ # 10-bit path with its own tags, since x264 with BT.709 tags would shift its colours.
473
+ "hdr": hdr_signal,
474
+ "hdr_signal": hdr_signal,
475
+ "bt2020_or_hdr": hdr,
476
+ "hdr_format": (("Dolby Vision %s" % (("profile %s" % dovi["profile"]) if dovi and dovi.get("profile") is not None else "")).strip() if dovi else
477
+ "HDR10/PQ" if trc == "smpte2084" else "HLG" if trc == "arib-std-b67" else "BT.2020 SDR" if hdr else None),
478
+ "dolby_vision": dovi,
479
+ # HDR10 static metadata (mastering display, content light level) as the encoders take it:
480
+ # FFmpeg before 7 does not hand it from the decoded frames to libx265 / libsvtav1, so the
481
+ # tools pass it explicitly (decision.hdr10_x265_params). None when the source has none.
482
+ "hdr10_static": _hdr10_static(ffprobe, path, video) if trc == "smpte2084" else None,
483
+ "color_space": video.get("color_space"),
484
+ "color_primaries": video.get("color_primaries"),
485
+ "color_transfer": video.get("color_transfer"),
486
+ "color_range": video.get("color_range"),
487
+ "rotation": rotation,
488
+ "nb_frames": _to_int(video.get("nb_frames")),
489
+ # the stream's own length (a container's also counts audio priming and a longer track)
490
+ "duration": _to_float(video.get("duration")),
491
+ # Matroska/WebM keep the stream's length in a DURATION tag only, as for audio below
492
+ "tagged_duration": _tag_seconds((video.get("tags") or {}).get("DURATION")),
493
+ # where the stream starts; a video stream that starts after its audio (or the reverse)
494
+ # is how a lossless cut's A/V skew shows up
495
+ "start_time": _to_float(video.get("start_time")),
496
+ "bitrate": _to_int(video.get("bit_rate")),
497
+ }
498
+ if audio:
499
+ out["audio"] = {
500
+ "codec": audio.get("codec_name"),
501
+ "channels": _to_int(audio.get("channels")),
502
+ "channel_layout": audio.get("channel_layout"),
503
+ "sample_rate": _to_int(audio.get("sample_rate")),
504
+ "bitrate": _to_int(audio.get("bit_rate")),
505
+ "duration": _to_float(audio.get("duration")),
506
+ "start_time": _to_float(audio.get("start_time")),
507
+ # Matroska/WebM give no stream duration, only a DURATION tag; the container's own length
508
+ # is the longest stream's, which is not the sound's when the picture runs longer (2.20)
509
+ "tagged_duration": _tag_seconds((audio.get("tags") or {}).get("DURATION")),
510
+ }
511
+ # every audio stream in file order: index n here is `-map 0:a:n` (audio.py --audio-stream n)
512
+ out["audio_streams"] = [{
513
+ "index": n,
514
+ "codec": a.get("codec_name"),
515
+ "channels": _to_int(a.get("channels")),
516
+ "channel_layout": a.get("channel_layout"),
517
+ "sample_rate": _to_int(a.get("sample_rate")),
518
+ "language": (a.get("tags") or {}).get("language"),
519
+ "title": (a.get("tags") or {}).get("title"),
520
+ } for n, a in enumerate(s for s in streams if s.get("codec_type") == "audio")]
521
+ if role == "input" and out.get("video") and out["video"].get("codec") \
522
+ and os.path.splitext(path)[1].lower() not in _STILL_EXT:
523
+ # a still (an overlay's logo, an insert card) is not a second picture source (#412 review)
524
+ STATE.video_inputs.add(os.path.realpath(path))
525
+ if role == "input" and out.get("audio_streams"):
526
+ STATE.audio_inputs.add(os.path.realpath(path))
527
+ if role == "input" and getattr(STATE, "first_input", None) is None:
528
+ STATE.first_input = (path, len(out.get("audio_streams") or []),
529
+ (out.get("video") or {}).get("hdr10_static"), (out.get("video") or {}).get("bit_depth"))
530
+ if role == "input" and out["timecode"].get("value") and getattr(STATE, "source_timecode", None) is None:
531
+ STATE.source_timecode = (out["timecode"]["value"], duration)
532
+ # what a source carries besides its picture and sound, for emit()'s source_carry comparison:
533
+ # kept beside the probe, not in it, so no probe document changes
534
+ lang = (audio.get("tags") or {}).get("language") if audio else None
535
+ _CARRY[os.path.realpath(path)] = {
536
+ "subtitles": len(subs),
537
+ "chapters": len(raw.get("chapters") or []),
538
+ "cover_art": sum(1 for s in streams if s.get("codec_type") == "video" and s.get("disposition", {}).get("attached_pic", 0)),
539
+ # Matroska attachments (a subtitle track's fonts, A256) and the playable pictures beside
540
+ # the one probe() describes, which a tool that writes one picture leaves out (A258)
541
+ "attachments": sum(1 for s in streams if s.get("codec_type") == "attachment"),
542
+ "video_streams": sum(1 for s in streams if s.get("codec_type") == "video"
543
+ and not s.get("disposition", {}).get("attached_pic", 0)),
544
+ "creation_time": 1 if any(k.lower() == "creation_time" for k in (fmt.get("tags") or {})) else 0,
545
+ "audio_language": 1 if lang and lang.lower() != "und" else 0,
546
+ "timecode": 1 if out["timecode"].get("value") else 0,
547
+ "timecode_value": out["timecode"].get("value"),
548
+ "audio_channels": (_to_int(audio.get("channels")) or 0) if audio else 0,
549
+ "has_video": bool(video), "has_audio": bool(audio),
550
+ # the guard on time-bearing items (emit.source_carry): the length, and where the chapters are
551
+ "duration": out.get("duration"),
552
+ "chapter_times": [(round(_to_float(c.get("start_time")) or 0.0, 2), round(_to_float(c.get("end_time")) or 0.0, 2))
553
+ for c in (raw.get("chapters") or [])],
554
+ }
555
+ return out
556
+
557
+
558
+ _CARRY: Dict[str, Dict[str, Any]] = {}
559
+
560
+
561
+ def probed_maps(meta: Optional[Dict[str, Any]], *, video: bool = True, audio: bool = True,
562
+ audio_stream: int = 0, input_index: int = 0) -> List[str]:
563
+ """`-map` arguments for the picture and sound probe() describes in `meta` (audio track
564
+ `audio_stream` where a tool takes --audio-stream). A kind the file does not have is left out,
565
+ so the same call serves a silent clip and an audio-only file."""
566
+ out: List[str] = []
567
+ if video and (meta or {}).get("video"):
568
+ out += ["-map", f"{input_index}:{PROBED_VIDEO}"]
569
+ if audio and (meta or {}).get("audio"):
570
+ out += ["-map", f"{input_index}:a:{audio_stream}"]
571
+ return out
572
+
573
+
574
+ def several_av_streams(meta: Optional[Dict[str, Any]]) -> bool:
575
+ """True when FFmpeg's default stream selection could pick a picture or a sound other than the
576
+ one probe() describes: more than one playable video stream or more than one audio stream."""
577
+ counts = (meta or {}).get("stream_counts") or {}
578
+ return (counts.get("video") or 0) > 1 or (counts.get("audio") or 0) > 1
579
+
580
+
581
+ def carry_inventory(path: str) -> "Optional[Dict[str, Any]]":
582
+ """The carry-over items probe() last read off `path` (see emit()'s source_carry), or None."""
583
+ return _CARRY.get(os.path.realpath(path)) if path else None
584
+
585
+
586
+ def _hdr10_static(ffprobe: str, path: str, stream: Dict[str, Any]) -> "Optional[Dict[str, Any]]":
587
+ """A PQ stream's mastering display and content light level, from the stream (an mdcv/clli box,
588
+ a Matroska colour element) or else its first frame (the HEVC SEI / AV1 metadata OBU): one
589
+ frame is decoded when either part is missing or incomplete in the stream. Each part is taken
590
+ from wherever it is complete first, the stream before the frame. Chromaticities are CIE 1931
591
+ x/y, luminances cd/m2. None when it has neither."""
592
+ out = _hdr10_parts(stream.get("side_data_list") or [])
593
+ if len(out) < 2:
594
+ # V:0, not v:0: an attached cover picture before the motion video has no HDR side data
595
+ proc = run([ffprobe, "-v", "error", "-select_streams", "V:0", "-read_intervals", "%+#1", "-show_frames",
596
+ "-show_entries", "frame=side_data_list", "-of", "json", path], quiet=True, check=False)
597
+ frames: List[Dict[str, Any]] = []
598
+ if proc.returncode == 0:
599
+ try:
600
+ frames = json.loads(proc.stdout or "{}").get("frames") or []
601
+ except ValueError:
602
+ pass
603
+ for k, v in _hdr10_parts((frames[0].get("side_data_list") or []) if frames else []).items():
604
+ out.setdefault(k, v)
605
+ return out or None
606
+
607
+
608
+ def _hdr10_parts(sides: Sequence[Dict[str, Any]]) -> Dict[str, Any]:
609
+ """The complete parts in one side-data list: a mastering display with every field, a content
610
+ light level with both values; an incomplete record counts as absent."""
611
+ out: Dict[str, Any] = {}
612
+ for sd in sides:
613
+ kind = _side_kind(sd)
614
+ if kind == "mastering" and "mastering_display" not in out:
615
+ vals = {k: _ratio(sd.get(k)) for k in ("red_x", "red_y", "green_x", "green_y", "blue_x", "blue_y",
616
+ "white_point_x", "white_point_y", "min_luminance", "max_luminance")}
617
+ if all(v is not None for v in vals.values()):
618
+ out["mastering_display"] = {k: float(v) for k, v in vals.items()}
619
+ elif kind == "light" and "content_light" not in out:
620
+ mc, ma = _to_int(sd.get("max_content")), _to_int(sd.get("max_average"))
621
+ if mc is not None and ma is not None:
622
+ out["content_light"] = {"max_content": mc, "max_average": ma}
623
+ return out
624
+
625
+
626
+ _STILL_EXT = (".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff", ".gif", ".avif", ".heic")
627
+
628
+
629
+ def _ratio(v: Any) -> "Optional[Fraction]":
630
+ """A side-data value such as "34000/50000" or "0/10000". Unlike _fraction() a zero is a value
631
+ (a mastering display's minimum luminance may be 0 cd/m2); only a missing or malformed one is None."""
632
+ try:
633
+ f = Fraction(str(v))
634
+ except (ValueError, ZeroDivisionError, TypeError):
635
+ return None
636
+ return f if f >= 0 else None
637
+
638
+
639
+ def _side_kind(sd: Dict[str, Any]) -> "Optional[str]":
640
+ t = str(sd.get("side_data_type") or "")
641
+ return "mastering" if t == "Mastering display metadata" else "light" if t == "Content light level metadata" else None
642
+
643
+
644
+ def _bit_depth(pix_fmt: Optional[str]) -> int:
645
+ """Bits per component from a pixel format name. `"10" in pix` used to read yuv410p (4:1:0
646
+ chroma) as 10-bit; the depth is the number that ends the name (before an le/be suffix):
647
+ yuv420p10le -> 10, gbrp12be -> 12, gray16le -> 16, yuv410p / yuv420p / rgb24 -> 8."""
648
+ m = re.search(r"(\d{1,2})(?:le|be)?$", pix_fmt or "")
649
+ if not m:
650
+ return 8
651
+ n = int(m.group(1))
652
+ if n in (24, 32): # packed 8-bit rgb24/bgr32/rgb0 etc.
653
+ return 8
654
+ if n in (48, 64): # packed 16-bit rgb48/rgba64
655
+ return 16
656
+ return n if 8 <= n <= 16 else 8
657
+
658
+
659
+ def keyframe_times(path: str, lo: float, hi: float, stream: str = "v:0") -> Optional[List[float]]:
660
+ """Keyframe timestamps of `stream` read from lo to hi seconds (file time), ascending and as
661
+ ffprobe prints them (microseconds). Read with -read_intervals so a long file is not scanned end
662
+ to end; the read starts at the keyframe at or before lo, so the first may lie before it. None
663
+ when ffprobe fails (unmeasured, not "no keyframes")."""
664
+ # an interval's end is exclusive (6.1: a keyframe at exactly hi is not read), so read a
665
+ # little past it and drop what lies beyond hi
666
+ proc = run([require_tool("ffprobe"), "-v", "error", "-select_streams", stream, "-skip_frame", "nokey",
667
+ "-read_intervals", f"{max(0.0, lo):.6f}%{hi + 0.01:.6f}", "-show_entries", "frame=pts_time",
668
+ "-of", "csv=p=0", path], quiet=True, check=False)
669
+ if proc.returncode != 0:
670
+ return None
671
+ out: List[float] = []
672
+ for line in proc.stdout.splitlines():
673
+ try:
674
+ k = float(line.strip().rstrip(","))
675
+ except ValueError:
676
+ continue
677
+ if k <= hi + 1e-6:
678
+ out.append(k)
679
+ return sorted(set(out))
680
+
681
+
682
+ def keyframes_near(path: str, t: float, window: float = 5.0) -> List[float]:
683
+ """Video keyframe timestamps within +-window seconds of t (to the ms), ascending; empty when
684
+ ffprobe cannot say (cut.py's best-effort hints; probe.py --keyframes-near uses keyframe_times)."""
685
+ return sorted(set(round(k, 3) for k in keyframe_times(path, t - window, t + window) or []))
686
+
687
+
688
+ # frame timing: is a stream's frame rate really variable? (cut.py's VFR guard)
689
+ TIMING_WINDOWS = 5 # sampled windows per file, fewer on a short one
690
+ TIMING_WINDOW_SECONDS = 6
691
+ TIMING_MIN_DELTAS = 20 # fewer measured intervals than this is no evidence either way
692
+
693
+
694
+ def complete_pts(packets: Sequence[Dict[str, Any]]) -> List[Any]:
695
+ """The pts of `packets` (as read, in decode order) whose frames are all there: those at or
696
+ before the last dts read. A read that stops just after a frame stored ahead of the B-frames
697
+ shown before it has missed those B-frames, and their gap would read as a dropped frame; every
698
+ frame shown by the last dts was decoded by then, so it was read. (FFmpeg 9.0's interval reads
699
+ measured whole on MP4; this keeps a demuxer that stops elsewhere from faking VFR.)"""
700
+ dts = [p["dts"] for p in packets if isinstance(p.get("dts"), int)]
701
+ pts = [p.get("pts") for p in packets]
702
+ return pts if not dts else [t for t in pts if isinstance(t, int) and t <= max(dts)]
703
+
704
+
705
+ def classify_frame_timing(windows: Sequence[Sequence[Any]], time_base: Any) -> Dict[str, Any]:
706
+ """Whether the frame timing in sampled windows is constant. `windows` are lists of pts in
707
+ `time_base` ticks, the first starting at the file's first packet.
708
+
709
+ Each window's pts are sorted (decode order stores B-frames out of sequence) and differenced,
710
+ with repeats and missing values dropped. The file-start window also drops its first interval:
711
+ an edit list or encoder priming can stretch it without the frame rate being variable.
712
+ `sampled_cfr` needs every interval within one tick (at least 1 ms) of its window's median and
713
+ the window medians to agree, so a single dropped or irregular frame is `vfr`. The tolerance
714
+ never exceeds half a frame: a tick that coarse (AVI's 1/fps) cannot round an interval, and one
715
+ tick of slack there would pass a dropped frame. Fewer than
716
+ TIMING_MIN_DELTAS intervals is `inconclusive`. What happens between the windows is not seen."""
717
+ result: Dict[str, Any] = {"measured": "inconclusive", "windows": len(windows), "deltas": 0}
718
+ tick = _fraction(str(time_base)) if time_base else None
719
+ if not tick or tick <= 0:
720
+ return result
721
+ per_window: List[List[float]] = []
722
+ for i, pts in enumerate(windows):
723
+ vals = sorted(float(p) for p in pts if isinstance(p, (int, float)) and math.isfinite(p))
724
+ deltas = [(b - a) * float(tick) for a, b in zip(vals, vals[1:]) if b != a]
725
+ per_window.append(deltas[1:] if i == 0 else deltas)
726
+ per_window = [d for d in per_window if d]
727
+ result["deltas"] = sum(len(d) for d in per_window)
728
+ if result["deltas"] < TIMING_MIN_DELTAS:
729
+ return result
730
+ medians = [statistics.median(d) for d in per_window]
731
+ tol = min(max(0.001, float(tick) + 1e-6), min(medians) / 2)
732
+ steady = all(abs(x - m) <= tol for d, m in zip(per_window, medians) for x in d)
733
+ result["measured"] = "sampled_cfr" if steady and max(medians) - min(medians) <= tol else "vfr"
734
+ return result
735
+
736
+
737
+ def timing_window_starts(duration: float, start: float = 0.0) -> List[float]:
738
+ """Up to TIMING_WINDOWS non-overlapping window starts spread over the file, the first on its
739
+ first packet. -read_intervals takes timestamps, so a file that starts at 10 s is read from 10."""
740
+ n = max(1, min(TIMING_WINDOWS, int((duration or 0.0) // TIMING_WINDOW_SECONDS)))
741
+ span = (duration or 0.0) - TIMING_WINDOW_SECONDS
742
+ return [round(start + (span * i / (n - 1) if n > 1 else 0.0), 3) for i in range(n)]
743
+
744
+
745
+ def measure_frame_timing(path: str, duration: Optional[float], start: float = 0.0) -> Dict[str, Any]:
746
+ """classify_frame_timing over sampled windows of `path`'s first video stream that is not cover
747
+ art (probe()'s choice): one packet-only ffprobe per window, no decoding. An interval read seeks
748
+ back to the keyframe before its start and, given a relative end, ends that far past the
749
+ keyframe -- on a long GOP every window read the file's first seconds -- so each window names
750
+ its absolute end and keeps only the frames from its start. The first window does not seek at
751
+ all: a seek to the start of an edit-listed MP4 skips its keyframe, stored before the start
752
+ with a negative pts, and loses the frames that depend on it (seeks near the start behave
753
+ erratically, so no margin is safe). The cost: a file whose video begins long after its first
754
+ packet is demuxed, not decoded, up to the video start. An ffprobe failure is `inconclusive`."""
755
+ ffprobe = require_tool("ffprobe")
756
+ windows: List[List[Any]] = []
757
+ time_base = None
758
+ for i, t in enumerate(timing_window_starts(duration or 0.0, start)):
759
+ proc = run([ffprobe, "-v", "error", "-select_streams", "V:0", "-show_packets",
760
+ "-show_entries", "packet=pts,dts,flags:stream=time_base", "-of", "json",
761
+ "-read_intervals", f"{t if i else ''}%{t + TIMING_WINDOW_SECONDS:.3f}", path], quiet=True, check=False)
762
+ try:
763
+ doc = json.loads(proc.stdout) if proc.returncode == 0 else None
764
+ except ValueError:
765
+ doc = None
766
+ if not isinstance(doc, dict):
767
+ return {"measured": "inconclusive", "windows": len(windows), "deltas": 0}
768
+ time_base = time_base or ((doc.get("streams") or [{}])[0] or {}).get("time_base")
769
+ tick = float(_fraction(str(time_base)) or 0) if time_base else 0.0
770
+ packets = doc.get("packets") or []
771
+ floor = t - 1e-6
772
+ if i:
773
+ # a seek into MPEG-TS lands mid-GOP, not on a keyframe: a frame stored before the
774
+ # landing point is missing, which read as a dropped frame (a constant TS measured
775
+ # `vfr`). Judge a seeked window from its first keyframe's presentation on.
776
+ key = next((p.get("pts") for p in packets if "K" in str(p.get("flags", "")) and isinstance(p.get("pts"), int)), None)
777
+ if key is not None:
778
+ floor = max(floor, key * tick - 1e-6)
779
+ windows.append([p for p in complete_pts(packets) if isinstance(p, int) and p * tick >= floor])
780
+ return classify_frame_timing(windows, time_base)
781
+
782
+
783
+ def measured_level_dbfs(path: str, seconds: Optional[float] = 120.0,
784
+ audio_stream: Optional[int] = None) -> Optional[Dict[str, float]]:
785
+ """Mean and peak level of the first `seconds` of audio (volumedetect), in dBFS; None if unmeasurable.
786
+ Cheap enough to run once as a hint when a threshold-based tool found nothing. seconds=None
787
+ measures the whole file; audio_stream picks the Nth audio stream (default: the first, the one
788
+ probe() describes; FFmpeg's own choice was the track with the most channels)."""
789
+ ffmpeg = require_tool("ffmpeg")
790
+ head = ["-t", f"{seconds:.0f}"] if seconds is not None else []
791
+ pick = ["-map", f"0:a:{audio_stream or 0}"]
792
+ proc = run_analysis([ffmpeg, "-hide_banner", "-nostdin", *head, "-i", path, *pick, "-vn",
793
+ "-af", "volumedetect", "-f", "null", "-"], check=False)
794
+ m_mean = re.search(r"mean_volume:\s*(-?[0-9.]+) dB", proc.stderr)
795
+ m_max = re.search(r"max_volume:\s*(-?[0-9.]+) dB", proc.stderr)
796
+ if not (m_mean and m_max):
797
+ return None
798
+ return {"mean_dbfs": float(m_mean.group(1)), "peak_dbfs": float(m_max.group(1))}
799
+
800
+
801
+ # Legal signal range of limited-range Y'CbCr (check.py --levels, color.py --legalize). Each standard
802
+ # is stated in percent of the nominal swing, so the code limits follow from the bit depth: 0 % luma is
803
+ # code 16 << (depth - 8), 100 % is 235 << (depth - 8); chroma's nominal swing is 16..240 (scaled the
804
+ # same way) around the midpoint. A sample is legal when its code lies inside [lo, hi] inclusive.
805
+ # bt709 ITU-R BT.709 nominal range: luma 0..100 %, chroma 16..240 (8-bit) -- no excursion.
806
+ # ebu-r103 EBU R 103 tolerance: luma -1 %..103 %, RGB components -5 %..105 %. Chroma is held to the
807
+ # widest Cb/Cr an RGB triple inside -5 %..105 % can produce (|C| <= 0.55 of the RGB span,
808
+ # i.e. 8-bit 5..251); RGB gamut itself is not measured here (a per-plane Y'CbCr count).
809
+ LEGAL_RANGES: Dict[str, Dict[str, Any]] = {
810
+ "bt709": {"luma_pct": (0.0, 100.0), "chroma_half_swing": 0.5,
811
+ "reference": "ITU-R BT.709 nominal range: luma 16-235, chroma 16-240 (8-bit; 10-bit 64-940 / 64-960)"},
812
+ "ebu-r103": {"luma_pct": (-1.0, 103.0), "chroma_half_swing": 0.55,
813
+ "reference": "EBU R 103 tolerance: luma -1 %..103 % (8-bit 14-241), chroma as far as RGB -5 %..105 % "
814
+ "reaches (8-bit 5-251)"},
815
+ }
816
+ LEGAL_RANGE_CHOICES = sorted(LEGAL_RANGES)
817
+
818
+
819
+ def legal_limits(standard: str, bit_depth: int = 8) -> Dict[str, Tuple[int, int]]:
820
+ """{"y": (lo, hi), "c": (lo, hi)}: the inclusive legal code range of a limited-range sample at
821
+ `bit_depth`. A limit that falls between two codes is rounded inward (the code past it is out)."""
822
+ spec = LEGAL_RANGES[standard]
823
+ scale = 1 << (max(8, int(bit_depth)) - 8)
824
+ black, white = 16 * scale, 235 * scale
825
+ span = white - black
826
+ p_lo, p_hi = spec["luma_pct"]
827
+ y = (math.ceil(black + span * p_lo / 100.0 - 1e-9), math.floor(white + span * (p_hi - 100.0) / 100.0 + 1e-9))
828
+ mid, cspan = 128 * scale, 224 * scale
829
+ half = spec["chroma_half_swing"] * cspan
830
+ c = (max(0, math.ceil(mid - half - 1e-9)), min((256 * scale) - 1, math.floor(mid + half + 1e-9)))
831
+ return {"y": y, "c": c}
832
+
833
+
834
+ _COMPONENT_DEPTHS: Dict[str, int] = {}
835
+
836
+
837
+ def component_depth(pix_fmt: Optional[str]) -> int:
838
+ """Bits per luma sample of `pix_fmt`, from ffmpeg's own pixel-format table (`-pix_fmts`,
839
+ BIT_DEPTHS column): the depth the planes really hold, which the name does not always say --
840
+ nv12 is 8-bit 4:2:0 (the 12 is bits per pixel), p010le is 10-bit. Falls back to _bit_depth()
841
+ when ffmpeg does not list the format."""
842
+ name = str(pix_fmt or "")
843
+ if not _COMPONENT_DEPTHS:
844
+ proc = run_analysis([require_tool("ffmpeg"), "-hide_banner", "-pix_fmts"], check=False)
845
+ for line in (proc.stdout or "").splitlines():
846
+ cols = line.split()
847
+ if len(cols) == 5 and re.fullmatch(r"\d+(?:-\d+)*", cols[4]):
848
+ _COMPONENT_DEPTHS[cols[1]] = int(cols[4].split("-")[0])
849
+ return _COMPONENT_DEPTHS.get(name) or _bit_depth(name)
850
+
851
+
852
+ def _metadata_frames(text: str, keys: Optional[frozenset] = None) -> List[Tuple[float, Dict[str, float]]]:
853
+ """metadata=print's output: one (pts_time, {key: value}) per `frame:` block, signalstats keys only
854
+ (only those in `keys` when given: signalstats prints ~25 per frame and an hour is 100k frames)."""
855
+ frames: List[Tuple[float, Dict[str, float]]] = []
856
+ for line in text.splitlines():
857
+ if line.startswith("frame:"):
858
+ m = re.search(r"pts_time:\s*(-?[0-9.]+|nan)", line)
859
+ t = float(m.group(1)) if m and m.group(1) != "nan" else float("nan")
860
+ frames.append((t, {}))
861
+ elif "lavfi.signalstats." in line and "=" in line and frames:
862
+ key, val = line.split("lavfi.signalstats.", 1)[1].split("=", 1)
863
+ key = key.strip()
864
+ if keys is not None and key not in keys:
865
+ continue
866
+ try:
867
+ frames[-1][1][key] = float(val)
868
+ except ValueError:
869
+ pass
870
+ return frames
871
+
872
+
873
+ # the signalstats keys measure_signal_range reads: the frame's own extremes and BRNG, and the mask's means
874
+ _OWN_KEYS = frozenset({"BRNG", "YMIN", "YMAX", "UMIN", "UMAX", "VMIN", "VMAX"})
875
+ _MASK_KEYS = frozenset({"YAVG", "UAVG", "VAVG"})
876
+
877
+
878
+ def measure_signal_range(path: str, standard: str, window: float = 10.0,
879
+ bit_depth: Optional[int] = None, pix_fmt: Optional[str] = None) -> Optional[Dict[str, Any]]:
880
+ """Share of luma and chroma samples outside `standard`'s legal range, per clip and per `window`
881
+ seconds, plus min/max Y/U/V, from one decode of every frame of the first video stream.
882
+
883
+ The count is exact, not sampled from a histogram: each plane goes through lutyuv, which maps an
884
+ out-of-range code to the depth's top code (255 at 8 bits) and every other code to 0, and
885
+ signalstats' mean of that mask is the top code x the out-of-range share of that plane in that frame. Chroma planes are
886
+ counted at their own (subsampled) resolution, so "chroma" is the share of Cb and Cr samples. A
887
+ second signalstats ahead of the mask reads the frame's own MIN/MAX and BRNG (the share of pixels
888
+ with any component outside the BT.601/709 nominal range, signalstats' fixed limits). Every frame
889
+ holds the same number of samples, so a clip's share is the mean of its frames' shares.
890
+
891
+ The limits and the mask use `bit_depth`, or else the depth of `pix_fmt`'s planes
892
+ (component_depth(): nv12 is 8-bit, not 12). None when the measurement is not whole: nothing
893
+ decoded, ffmpeg failed part-way (a share from the frames read before the failure would grade a
894
+ file nobody measured to the end), or the two passes counted different frames."""
895
+ if standard not in LEGAL_RANGES:
896
+ die(f"unknown legal range {standard!r}; choose from {', '.join(LEGAL_RANGE_CHOICES)}")
897
+ import tempfile
898
+ from _common.decision import escape_filter_path
899
+ ffmpeg = require_tool("ffmpeg")
900
+ depth = int(bit_depth or component_depth(pix_fmt))
901
+ lim = legal_limits(standard, depth)
902
+ (ylo, yhi), (clo, chi) = lim["y"], lim["c"]
903
+ top = (1 << depth) - 1 # a literal: lutyuv's own maxval is 235 for limited-range luma, 240 for chroma
904
+ out = str(top) + "*(lt(val\\,{lo})+gt(val\\,{hi}))"
905
+ mask = (f"lutyuv=y='{out.format(lo=ylo, hi=yhi)}':u='{out.format(lo=clo, hi=chi)}'"
906
+ f":v='{out.format(lo=clo, hi=chi)}'")
907
+ with tempfile.TemporaryDirectory(prefix="ffskill_levels_") as tmp:
908
+ stats_file = os.path.join(tmp, "stats.txt")
909
+ vf = (f"signalstats=stat=brng,metadata=print:file={escape_filter_path(stats_file)},"
910
+ f"{mask},signalstats,metadata=print:file=-")
911
+ cmd = [ffmpeg, "-hide_banner", "-nostdin", "-i", path, "-map", f"0:{PROBED_VIDEO}", "-an", "-sn", "-dn", "-vf", vf, "-f", "null", "-"]
912
+ proc = run_analysis(cmd, check=False, record=True)
913
+ try:
914
+ with open(stats_file, encoding="utf-8", errors="replace") as f:
915
+ own = _metadata_frames(f.read(), _OWN_KEYS)
916
+ except OSError:
917
+ own = []
918
+ masks = _metadata_frames(proc.stdout or "", _MASK_KEYS)
919
+ if proc.returncode != 0 or not own or len(own) != len(masks):
920
+ return None
921
+ t0 = next((t for t, _ in own if t == t), 0.0)
922
+ rows: List[Dict[str, Any]] = []
923
+ for (t, s), (_, m) in zip(own, masks, strict=True):
924
+ y, u, v = (m.get(k, 0.0) / top * 100.0 for k in ("YAVG", "UAVG", "VAVG"))
925
+ rows.append({"t": (t - t0) if t == t else None, "y": y, "u": u, "v": v, "brng": s.get("BRNG", 0.0) * 100.0,
926
+ "min": {k: s.get(k.upper() + "MIN") for k in "yuv"}, "max": {k: s.get(k.upper() + "MAX") for k in "yuv"}})
927
+
928
+ def summary(frames: List[Dict[str, Any]]) -> Dict[str, Any]:
929
+ k = len(frames)
930
+ share = {p: sum(f[p] for f in frames) / k for p in ("y", "u", "v", "brng")}
931
+ worst = max(frames, key=lambda f: max(f["y"], (f["u"] + f["v"]) / 2))
932
+ def ext(which: str, fn: Any) -> Dict[str, Any]:
933
+ vals = {p: [f[which][p] for f in frames if f[which][p] is not None] for p in "yuv"}
934
+ return {p: (int(fn(v)) if v else None) for p, v in vals.items()}
935
+ return {"frames": k,
936
+ "out_of_range_pct": {"y": round(share["y"], 4), "u": round(share["u"], 4), "v": round(share["v"], 4),
937
+ "chroma": round((share["u"] + share["v"]) / 2, 4)},
938
+ "brng_pct": round(share["brng"], 4),
939
+ "worst_frame": {"time": None if worst["t"] is None else round(worst["t"], 3),
940
+ "y_pct": round(worst["y"], 4), "chroma_pct": round((worst["u"] + worst["v"]) / 2, 4)},
941
+ "min": ext("min", min), "max": ext("max", max)}
942
+
943
+ doc = {"standard": standard, "reference": LEGAL_RANGES[standard]["reference"], "bit_depth": depth,
944
+ "legal": {"y": list(lim["y"]), "c": list(lim["c"])}, "window_seconds": window, **summary(rows)}
945
+ windows: List[Dict[str, Any]] = []
946
+ if window and window > 0:
947
+ buckets: Dict[int, List[Dict[str, Any]]] = {}
948
+ for i, f in enumerate(rows):
949
+ buckets.setdefault(int((f["t"] if f["t"] is not None else i) // window), []).append(f)
950
+ for idx in sorted(buckets):
951
+ w = summary(buckets[idx])
952
+ windows.append({"start": round(idx * window, 3), "end": round((idx + 1) * window, 3), **w})
953
+ doc["windows"] = windows
954
+ return doc
955
+
956
+
957
+ def refuse_not_a_still(path: str, meta: Dict[str, Any], flag: str, instead: str) -> None:
958
+ """`flag` takes a still image and is read with `-loop 1`, an option of the image demuxers only:
959
+ a video or a GIF (one frame or many: the gif demuxer has no such option) given there failed as
960
+ "Option loop not found" / "Option framerate not found", naming neither the file nor the flag
961
+ (#404). `instead` says what takes a video."""
962
+ fmt = str(meta.get("format") or "")
963
+ if STATE.dry_run and meta.get("dry_run"):
964
+ return # a pending input: nothing was read
965
+ if fmt == "image2" or fmt.endswith("_pipe"):
966
+ return
967
+ if fmt == "gif":
968
+ die(f"{flag} {path} is a GIF, and {flag} reads a still image through the image demuxers, which do not "
969
+ "open GIF: convert it to PNG first (`look.py FILE --at 0 -o still.png` writes its first frame)", kind="input")
970
+ length = meta.get("duration")
971
+ die(f"{flag} {path} is not a still image: it is a {fmt.split(',')[0] or 'media'} file"
972
+ + (f" ({length:.3f}s)" if length else "") + f", and {flag} is read as one picture", kind="input", hint=instead)
973
+
974
+
975
+ def is_still_input(meta: Dict[str, Any]) -> bool:
976
+ """A probe document of one picture read by an image demuxer (_is_still()'s rule, on the
977
+ document): a still given where a clip is taken. Read with a plain `-i` it is one frame, so a
978
+ tool that shows it for a while opens it with still_loop_args() (#510)."""
979
+ fmt = str((meta or {}).get("format") or "")
980
+ return not (meta or {}).get("dry_run") and (fmt == "image2" or fmt.endswith("_pipe"))
981
+
982
+
983
+ def still_loop_args(path: str, seconds: float) -> List[str]:
984
+ """The input options that show a still picture for `seconds`: `-loop 1` repeats its one frame
985
+ (the image demuxers' option) and `-t` ends the repeat, so the input is bounded."""
986
+ return ["-loop", "1", *still_input_args(path), "-t", f"{max(seconds, 0.001):.3f}"]
987
+
988
+
989
+ def analyze_levels(path: str, seconds: float = 20.0) -> Dict[str, Any]:
990
+ """Sample luma/saturation statistics (signalstats) and guess whether the picture is Log-encoded.
991
+
992
+ Log gammas (S-Log3, V-Log, C-Log, HLG-looking flat profiles) put black around 90-95/255 and
993
+ white below ~235 with low saturation: the image looks grey and flat but is tagged as plain SDR.
994
+ """
995
+ ffmpeg = require_tool("ffmpeg")
996
+ cmd = [ffmpeg, "-hide_banner", "-nostdin", "-t", f"{seconds:.1f}", "-i", path, "-map", f"0:{PROBED_VIDEO}", "-an",
997
+ "-vf", "fps=2,signalstats,metadata=print:file=-", "-f", "null", "-"]
998
+ proc = run_analysis(cmd, check=False)
999
+ vals: Dict[str, List[float]] = {}
1000
+ for line in proc.stdout.splitlines():
1001
+ if "lavfi.signalstats." in line and "=" in line:
1002
+ key, val = line.split("lavfi.signalstats.", 1)[1].split("=", 1)
1003
+ try:
1004
+ vals.setdefault(key, []).append(float(val))
1005
+ except ValueError:
1006
+ pass
1007
+ if not vals.get("YAVG"):
1008
+ return {"error": "no frames analysed"}
1009
+ def mean(k: str) -> float:
1010
+ v = vals.get(k) or [0.0]
1011
+ return sum(v) / len(v)
1012
+ ymin, ymax, yavg, sat = min(vals.get("YMIN") or [0]), max(vals.get("YMAX") or [255]), mean("YAVG"), mean("SATAVG")
1013
+ # signalstats reports in the source bit depth; normalise everything to an 8-bit scale
1014
+ scale = 1.0
1015
+ if ymax > 255 or yavg > 255:
1016
+ scale = 1 / 4.0 if ymax <= 1023 else (1 / 16.0 if ymax <= 4095 else 1 / 256.0) # 10 / 12 / 16-bit
1017
+ ymin, ymax, yavg, sat = ymin * scale, ymax * scale, yavg * scale, sat * scale
1018
+ # 5th/95th percentile of per-frame lows/highs is more robust than the absolute min/max
1019
+ lows = sorted(x * scale for x in (vals.get("YLOW") or vals.get("YMIN") or [0]))
1020
+ highs = sorted(x * scale for x in (vals.get("YHIGH") or vals.get("YMAX") or [255]))
1021
+ p_low = lows[len(lows) // 20]
1022
+ p_high = highs[-1 - len(highs) // 20]
1023
+ looks_log = p_low >= 64 and p_high <= 235 and sat < 40
1024
+ return {
1025
+ "scale": "8-bit equivalent",
1026
+ "y_min": round(ymin, 1), "y_max": round(ymax, 1), "y_avg": round(yavg, 1), "y_low_p5": round(p_low, 1), "y_high_p95": round(p_high, 1),
1027
+ "saturation_avg": round(sat, 1),
1028
+ "looks_like_log": looks_log,
1029
+ "note": ("flat, low-contrast, desaturated picture tagged as SDR: probably a Log profile (S-Log/V-Log/C-Log). "
1030
+ "Apply the camera's conversion LUT with color.py --lut" if looks_log else "contrast and saturation look like normal display-referred SDR"),
1031
+ }
1032
+
1033
+
1034
+ def _tag_seconds(value: Any) -> "Optional[float]":
1035
+ """A Matroska DURATION tag ("00:00:04.008000000") in seconds, or None."""
1036
+ try:
1037
+ if "-" in str(value): # "-00:00:01": int("-00") is 0, so the sign would be lost
1038
+ return None
1039
+ h, m, sec = str(value).split(":")
1040
+ seconds = int(h) * 3600 + int(m) * 60 + float(sec)
1041
+ except (TypeError, ValueError):
1042
+ return None
1043
+ # float() reads "nan" and "inf": a length that is not a finite, non-negative number is none
1044
+ return seconds if math.isfinite(seconds) and seconds >= 0 else None
1045
+
1046
+
1047
+ def _to_float(v: Any) -> Optional[float]:
1048
+ try:
1049
+ return float(v) if v is not None else None
1050
+ except (TypeError, ValueError):
1051
+ return None
1052
+
1053
+
1054
+ def _to_int(v: Any) -> Optional[int]:
1055
+ try:
1056
+ return int(v) if v is not None else None
1057
+ except (TypeError, ValueError):
1058
+ return None
1059
+
1060
+
1061
+ def _fraction(v: Optional[str]) -> Optional[Fraction]:
1062
+ if not v or v in ("0/0", "0"):
1063
+ return None
1064
+ try:
1065
+ f = Fraction(v)
1066
+ return f if f > 0 else None
1067
+ except (ValueError, ZeroDivisionError):
1068
+ return None
1069
+
1070
+
1071
+ def _sar_string(v: Optional[str]) -> str:
1072
+ """ffprobe's sample_aspect_ratio as "N:D", "1:1" when unset (0:1, N/A, missing)."""
1073
+ f = _fraction((v or "").replace(":", "/"))
1074
+ return f"{f.numerator}:{f.denominator}" if f else "1:1"
1075
+
1076
+
1077
+ def pixel_aspect(video: Optional[Dict[str, Any]]) -> Fraction:
1078
+ """The stored pixel's width over its height (the SAR); 1 when the stream does not say."""
1079
+ return _fraction(str((video or {}).get("sample_aspect_ratio") or "").replace(":", "/")) or Fraction(1)
1080
+
1081
+
1082
+ def _square_size(video: Optional[Dict[str, Any]]) -> "Tuple[int, int, Fraction]":
1083
+ """(width, height, SAR) of the frame the filter graph receives: rotation applied (ffmpeg
1084
+ autorotates on decode, and its transpose turns the SAR over too), pixels not yet squared."""
1085
+ video = video or {}
1086
+ w, h = int(video.get("width") or 0), int(video.get("height") or 0)
1087
+ sar = pixel_aspect(video)
1088
+ if video.get("rotation") in (90, -90, 270, -270):
1089
+ w, h, sar = h, w, 1 / sar
1090
+ return w, h, sar
1091
+
1092
+
1093
+ def display_size(video: Optional[Dict[str, Any]]) -> "Tuple[int, int]":
1094
+ """The displayed frame in square pixels: rotation applied, and a non-square-pixel picture
1095
+ widened or narrowed to its display aspect at its own height (1440x1080 at 4:3 is 1920x1080,
1096
+ 720x480 at 8:9 is 640x480). It is the frame square_pixels() hands the rest of a graph, so a
1097
+ tool sizes, places and draws in it. 0x0 when unknown (a dry run's pending input)."""
1098
+ w, h, sar = _square_size(video)
1099
+ if w and h and sar != 1:
1100
+ w = max(2, int(round(w * sar / 2)) * 2)
1101
+ return w, h
1102
+
1103
+
1104
+ def square_pixels(video: Optional[Dict[str, Any]]) -> str:
1105
+ """The filter that makes a non-square-pixel picture square at its display aspect
1106
+ ("scale=640:360,setsar=1"), or "" when the pixels are square already. A tool that scales,
1107
+ crops, places or draws starts its video chain with it, so every such tool agrees on one
1108
+ frame (display_size()) and nothing is squashed or drawn stretched (#411). Tools that only
1109
+ re-encode keep the stored size and its SAR, which the encoder writes through."""
1110
+ w, h, sar = _square_size(video)
1111
+ if not (w and h) or sar == 1:
1112
+ return ""
1113
+ dw, dh = display_size(video)
1114
+ return f"scale={dw}:{dh},setsar=1"
1115
+
1116
+
1117
+ def square_pixels_note(video: Optional[Dict[str, Any]], what: str = "the input") -> Optional[str]:
1118
+ """The notes line for a square_pixels() scale, or None when there is none."""
1119
+ if not square_pixels(video):
1120
+ return None
1121
+ w, h, _ = _square_size(video)
1122
+ dw, dh = display_size(video)
1123
+ return (f"{what} stores non-square pixels (SAR {(video or {}).get('sample_aspect_ratio')}): "
1124
+ f"its {w}x{h} picture was scaled to {dw}x{dh} square pixels, its display aspect")
1125
+
1126
+
1127
+ def _is_still(fmt: Dict[str, Any], video: Dict[str, Any]) -> bool:
1128
+ """A single picture read by an image demuxer (image2, jpeg_pipe, png_pipe, ...)."""
1129
+ name = fmt.get("format_name") or ""
1130
+ return name == "image2" or name.endswith("_pipe")
1131
+
1132
+
1133
+ def _still_rotation(path: str) -> int:
1134
+ """The display rotation of a still's first decoded frame (an EXIF Orientation), 0 if none."""
1135
+ proc = run([require_tool("ffprobe"), "-v", "error", *still_input_args(path), "-select_streams", "v:0",
1136
+ "-read_intervals", "%+#1", "-show_entries", "frame_side_data=rotation", "-of", "json", path],
1137
+ quiet=True, check=False)
1138
+ try:
1139
+ frames = json.loads(proc.stdout or "{}").get("frames") or []
1140
+ for sd in (frames[0].get("side_data_list") or []) if frames else []:
1141
+ if "rotation" in sd:
1142
+ return int(round(float(sd["rotation"])))
1143
+ except (ValueError, TypeError, AttributeError):
1144
+ pass
1145
+ return 0
1146
+
1147
+
1148
+ def _aspect_string(w: Optional[int], h: Optional[int]) -> Optional[str]:
1149
+ if not w or not h:
1150
+ return None
1151
+ f = Fraction(w, h)
1152
+ return f"{f.numerator}:{f.denominator}"
1153
+
1154
+
1155
+ # --------------------------------------------------------------- structure detectors (1.16)
1156
+ # silencedetect and scdet, lifted out of silence.py and scenes.py byte-for-byte in 1.16.0 so that
1157
+ # metadata.py --auto-chapters can measure structure without importing another tool (no script in
1158
+ # scripts/ imports a sibling tool; only the _-prefixed modules are shared). silence.py and
1159
+ # scenes.py import them back from here, so their behaviour is unchanged.
1160
+
1161
+ SIL_RE = re.compile(r"silence_(start|end): ([0-9.]+)")
1162
+
1163
+
1164
+ def detect_silences(path: str, threshold: float, min_silence: float) -> "List[Tuple[float, float]]":
1165
+ if dry_run_input_pending(path):
1166
+ return []
1167
+ ffmpeg = require_tool("ffmpeg")
1168
+ cmd = [ffmpeg, "-hide_banner", "-nostdin", "-i", path, "-map", f"0:{PROBED_AUDIO}", "-vn", "-af",
1169
+ f"silencedetect=noise={threshold}dB:d={min_silence}", "-f", "null", "-"]
1170
+ proc = run_analysis(cmd, check=False, record=True)
1171
+ if proc.returncode != 0:
1172
+ die(f"silencedetect failed:\n{proc.stderr.strip()[-800:]}", kind="ffmpeg", **ffmpeg_failure_extra(proc.stderr))
1173
+ silences: "List[Tuple[float, float]]" = []
1174
+ start = None
1175
+ for kind, val in SIL_RE.findall(proc.stderr):
1176
+ if kind == "start":
1177
+ start = float(val)
1178
+ elif start is not None:
1179
+ silences.append((start, float(val)))
1180
+ start = None
1181
+ if start is not None: # silence runs to the end
1182
+ silences.append((start, float("inf")))
1183
+ return silences
1184
+
1185
+
1186
+ # 2.3.0's silence threshold: a track whose whole-file peak is at or below this is digital
1187
+ # silence (join.py / audio.py --silence-threshold default, check.py's audio row).
1188
+ SILENT_PEAK_DBFS = -50.0
1189
+
1190
+ # check.py --content thresholds (docs/design-decisions.md "check.py --content").
1191
+ CONTENT_BLACK_PIX_TH = 0.10 # blackdetect pixel threshold (share of the luma range)
1192
+ CONTENT_MIN_SPAN = 0.1 # blackdetect minimum run, seconds
1193
+ CONTENT_FREEZE_NOISE = "-60dB" # freezedetect noise tolerance
1194
+ CONTENT_FREEZE_MIN = 0.5 # freezedetect minimum run, seconds
1195
+ CONTENT_SILENCE_MIN = 0.5 # silencedetect minimum run, seconds
1196
+ # 2.17: a dropout is a short run of (near) digital silence with sound on both sides -- a join
1197
+ # that lost its audio, a glitched decode. Far quieter than the silence row's -50 dB, so a
1198
+ # recording's own pauses (room tone) do not count; a noise gate does produce them, which is
1199
+ # why the row only ever WARNs.
1200
+ CONTENT_DROPOUT_DB = -80.0
1201
+ CONTENT_DROPOUT_MIN, CONTENT_DROPOUT_MAX = 0.02, 1.0 # seconds
1202
+ CONTENT_DROPOUT_EDGE = 0.05 # a gap this close to the start or end is a lead-in/out, not a dropout
1203
+ CONTENT_DROPOUT_PAD = 2.0 # zeros appended before the dropout pass; > MAX, so a tail that runs into it never counts
1204
+
1205
+ # 2.23: a flash is one frame that differs from both of its neighbours while they match each other
1206
+ # (a stray frame from another shot, a white or black frame at a join, a decode glitch). Measured on
1207
+ # 64x36 grey frames as the mean absolute luma difference (0-255): moving footage stays at a few
1208
+ # units, a cut or a flash moves the whole frame by tens.
1209
+ CONTENT_FLASH_JUMP = 12.0 # both steps into and out of the frame are at least this
1210
+ CONTENT_FLASH_RETURN = 0.25 # ...and the frames either side differ by at most this share of the smaller step
1211
+ CONTENT_FLAT_STD = 4.0 # first frame: luma standard deviation (0-255) below this is one flat colour
1212
+ _DIFF_W, _DIFF_H = 64, 36
1213
+
1214
+ _BLACK_RE = re.compile(r"black_start:\s*([0-9.]+)\s+black_end:\s*([0-9.]+)")
1215
+ _FREEZE_RE = re.compile(r"lavfi\.freezedetect\.freeze_(start|end):\s*([0-9.]+)")
1216
+
1217
+
1218
+ def detect_content(path: str, duration: float, *, video: bool = True, audio: bool = True) -> Dict[str, Any]:
1219
+ """One decode pass of blackdetect + freezedetect (video) and silencedetect (audio, at
1220
+ SILENT_PEAK_DBFS). Returns {"black": [(s, e)], "frozen": [(s, e)], "silence": [(s, e)]}
1221
+ with open-ended spans closed at `duration`; a key is absent when its stream is. {} when the
1222
+ input is a pending dry-run placeholder."""
1223
+ if dry_run_input_pending(path) or not (video or audio):
1224
+ return {}
1225
+ ffmpeg = require_tool("ffmpeg")
1226
+ cmd = [ffmpeg, "-hide_banner", "-nostdin", "-i", path]
1227
+ if video:
1228
+ cmd += ["-map", "0:V:0", "-vf", f"blackdetect=d={CONTENT_MIN_SPAN}:pix_th={CONTENT_BLACK_PIX_TH},"
1229
+ f"freezedetect=n={CONTENT_FREEZE_NOISE}:d={CONTENT_FREEZE_MIN}"]
1230
+ if audio:
1231
+ cmd += ["-map", "0:a:0", "-af", f"silencedetect=noise={SILENT_PEAK_DBFS:g}dB:d={CONTENT_SILENCE_MIN}"]
1232
+ proc = run_analysis(cmd + ["-f", "null", "-"], check=False, record=True)
1233
+ if proc.returncode != 0:
1234
+ die(f"content detection failed:\n{proc.stderr.strip()[-800:]}", kind="ffmpeg", **ffmpeg_failure_extra(proc.stderr))
1235
+ end = max(duration, 0.0)
1236
+ out: Dict[str, Any] = {}
1237
+ if video:
1238
+ out["black"] = [(float(a), min(float(b), end) if end else float(b)) for a, b in _BLACK_RE.findall(proc.stderr)]
1239
+ frozen: "List[Tuple[float, float]]" = []
1240
+ start = None
1241
+ for kind, val in _FREEZE_RE.findall(proc.stderr):
1242
+ if kind == "start":
1243
+ start = float(val)
1244
+ elif start is not None:
1245
+ frozen.append((start, float(val)))
1246
+ start = None
1247
+ if start is not None:
1248
+ frozen.append((start, end))
1249
+ out["frozen"] = frozen
1250
+ if audio:
1251
+ sil: "List[Tuple[float, float]]" = []
1252
+ start = None
1253
+ for kind, val in SIL_RE.findall(proc.stderr):
1254
+ if kind == "start":
1255
+ start = float(val)
1256
+ elif start is not None:
1257
+ sil.append((start, min(float(val), end) if end else float(val)))
1258
+ start = None
1259
+ if start is not None:
1260
+ sil.append((start, end))
1261
+ out["silence"] = sil
1262
+ out["dropouts"] = _detect_dropouts(path, end)
1263
+ return out
1264
+
1265
+
1266
+ def _detect_dropouts(path: str, end: float) -> "List[Tuple[float, float]]":
1267
+ """Short (near) digital-silence gaps inside the first audio stream: one audio-only pass
1268
+ (silencedetect at CONTENT_DROPOUT_DB). A second silencedetect in the main pass would log
1269
+ under the same name as the silence row's, so its lines could not be told apart. The audio
1270
+ is padded with CONTENT_DROPOUT_PAD s of zeros first: a silent tail of audio that ends before
1271
+ the container does then runs into the pad and is too long to count, instead of closing at
1272
+ the audio's EOF and passing the container-duration edge test."""
1273
+ proc = run_analysis([require_tool("ffmpeg"), "-hide_banner", "-nostdin", "-i", path, "-map", "0:a:0", "-af",
1274
+ f"apad=pad_dur={CONTENT_DROPOUT_PAD:g},"
1275
+ f"silencedetect=noise={CONTENT_DROPOUT_DB:g}dB:d={CONTENT_DROPOUT_MIN}", "-f", "null", "-"],
1276
+ check=False, record=True)
1277
+ if proc.returncode != 0:
1278
+ die(f"dropout detection failed:\n{proc.stderr.strip()[-800:]}", kind="ffmpeg", **ffmpeg_failure_extra(proc.stderr))
1279
+ gaps: "List[Tuple[float, float]]" = []
1280
+ start = None
1281
+ for kind, val in SIL_RE.findall(proc.stderr):
1282
+ if kind == "start":
1283
+ start = float(val)
1284
+ elif start is not None:
1285
+ s, e = start, float(val)
1286
+ start = None
1287
+ inside = s > CONTENT_DROPOUT_EDGE and (not end or e < end - CONTENT_DROPOUT_EDGE)
1288
+ if inside and CONTENT_DROPOUT_MIN <= e - s <= CONTENT_DROPOUT_MAX:
1289
+ gaps.append((s, e))
1290
+ return gaps # a gap still open at the end is a tail, never a dropout
1291
+
1292
+
1293
+ def detect_flashes(path: str) -> "Optional[List[int]]":
1294
+ """Frame indexes of single-frame flashes in the first video stream: frame n differs from n-1 and
1295
+ from n+1 by at least CONTENT_FLASH_JUMP while n-1 and n+1 differ by at most
1296
+ CONTENT_FLASH_RETURN of the smaller step. One video-only pass; ffmpeg reduces each frame to
1297
+ three 16-bit numbers (|f[n]-f[n-1]| and the two clipped halves of f[n]-f[n-2]): 6 bytes a
1298
+ frame in the captured output (1.3 MB for an hour at 60 fps), read in place. The caller turns an index into a time;
1299
+ the comparison itself needs no frame rate. None when no frame decoded or the pass failed
1300
+ (nothing was compared; a failure is also a flash_pass_failed warning)."""
1301
+ if dry_run_input_pending(path):
1302
+ return []
1303
+ graph = (f"[0:V:0]scale={_DIFF_W}:{_DIFF_H}:flags=area,format=gray16le,split=3[a][b][c];"
1304
+ "[a]tblend=all_mode=difference,scale=1:1:flags=area[d];"
1305
+ "[b]tmix=frames=3:weights='-1 0 1':scale=1,scale=1:1:flags=area[p];"
1306
+ "[c]tmix=frames=3:weights='1 0 -1':scale=1,scale=1:1:flags=area[q];"
1307
+ "[d][p][q]hstack=inputs=3")
1308
+ proc = run_analysis([require_tool("ffmpeg"), "-hide_banner", "-loglevel", "error", "-nostdin", "-i", path,
1309
+ "-filter_complex", graph, "-fps_mode", "passthrough", "-f", "rawvideo", "-"],
1310
+ check=False, text=False, record=True)
1311
+ if proc.returncode != 0:
1312
+ # an unmeasured row, not the end of the report: the other content rows stand
1313
+ warn("flash detection failed: " + (proc.stderr.decode(errors="replace").strip().splitlines() or ["ffmpeg exited " + str(proc.returncode)])[-1][:300],
1314
+ "flash_pass_failed")
1315
+ return None
1316
+ # tblend has no output for frame 0, so record r is frame r+1: a zero record in front puts
1317
+ # every value at its own frame's index. passthrough keeps the rawvideo muxer from padding a
1318
+ # constant rate, which repeated records over timestamp gaps (a repeat is a zero step, and a
1319
+ # flash before a gap went unreported)
1320
+ if len(proc.stdout) < 6:
1321
+ return None
1322
+ data = bytes(6) + proc.stdout
1323
+ n = len(data) // 6
1324
+
1325
+ def record(i: int) -> "Tuple[float, float]":
1326
+ """(|f[i] - f[i-1]|, |f[i] - f[i-2]|), 0-255; read from the buffer, never kept per frame."""
1327
+ d, p, q = (int.from_bytes(data[i * 6 + k:i * 6 + k + 2], "little") / 256.0 for k in (0, 2, 4))
1328
+ return d, p + q
1329
+
1330
+ flashes = []
1331
+ into = record(1)[0] if n > 1 else 0.0
1332
+ for i in range(1, n - 1):
1333
+ out, back = record(i + 1)
1334
+ if into >= CONTENT_FLASH_JUMP and out >= CONTENT_FLASH_JUMP and back <= CONTENT_FLASH_RETURN * min(into, out):
1335
+ flashes.append(i)
1336
+ into = out
1337
+ return flashes
1338
+
1339
+
1340
+ def presentation_times(path: str, start: float) -> "List[float]":
1341
+ """The presentation time of every frame of the first video stream (attached pictures
1342
+ excluded), in order: its packets' pts sorted, those before the stream's own start (an edit
1343
+ list's hidden pre-roll, never shown) dropped. From packets, so no decode. [] when unreadable,
1344
+ also when one packet has no pts: skipping it would shift every later time onto the wrong frame."""
1345
+ proc = run([require_tool("ffprobe"), "-v", "error", "-select_streams", "V:0", "-show_entries", "packet=pts_time",
1346
+ "-of", "csv=p=0", path], quiet=True, check=False)
1347
+ times = []
1348
+ for line in (proc.stdout or "").split() if proc.returncode == 0 else []:
1349
+ try:
1350
+ times.append(float(line.split(",")[0]))
1351
+ except ValueError:
1352
+ return []
1353
+ return sorted(t for t in times if t >= start - 1e-6)
1354
+
1355
+
1356
+ def first_frame_stats(path: str) -> "Optional[Tuple[float, float]]":
1357
+ """(mean, standard deviation) of the first frame's luma, 0-255, at 64x36; None when it does
1358
+ not decode or the input is a pending dry-run placeholder."""
1359
+ if dry_run_input_pending(path):
1360
+ return None
1361
+ proc = run_analysis([require_tool("ffmpeg"), "-hide_banner", "-loglevel", "error", "-nostdin", "-i", path,
1362
+ "-map", "0:V:0", "-frames:v", "1", "-vf", f"scale={_DIFF_W}:{_DIFF_H}:flags=area,format=gray",
1363
+ "-f", "rawvideo", "-"], check=False, text=False, record=True)
1364
+ px = list(proc.stdout[:_DIFF_W * _DIFF_H])
1365
+ if proc.returncode != 0 or len(px) < _DIFF_W * _DIFF_H:
1366
+ return None
1367
+ return statistics.fmean(px), statistics.pstdev(px)
1368
+
1369
+
1370
+ SCORE_RE = re.compile(r"frame:(\d+)\s+pts:\d+\s+pts_time:([0-9.]+)")
1371
+
1372
+
1373
+ def detect_scenes(path: str, threshold: float, min_len: float, duration: float, ratio: float = 3.0) -> "List[float]":
1374
+ """Scene cuts = frames whose scdet score is above `threshold` AND stands out from its
1375
+ neighbourhood (score > ratio x median of the surrounding +-12 frames). Sustained motion,
1376
+ flashes and fast pans raise the score on many consecutive frames and are rejected;
1377
+ a real cut is a one-frame spike. On real footage this roughly doubles precision at
1378
+ equal recall compared with the raw scdet threshold."""
1379
+ ffmpeg = require_tool("ffmpeg")
1380
+ proc = run_analysis([ffmpeg, "-hide_banner", "-nostdin", "-i", path, "-map", f"0:{PROBED_VIDEO}", "-an", "-vf",
1381
+ "scale=320:-2,scdet=threshold=0,metadata=print:file=-", "-f", "null", "-"])
1382
+ # No `sc_pass=1` on scdet: on FFmpeg 5.x that option means "pass only the frames whose
1383
+ # score exceeds the threshold", so every truly static frame (score exactly 0 -- a title
1384
+ # card, colour bars) is dropped before metadata=print and the frame numbers are re-counted
1385
+ # without them. The +-12-frame neighbourhood around a real cut then fills with the moving
1386
+ # segment's scores instead of the still one's zeros, the cut fails the ratio test, and a
1387
+ # 4 s smptebars scene made the cuts on both sides of it disappear (found by the 5.1.1 CI
1388
+ # job, #146). 6.1+ passes every frame either way. Scores are still indexed by frame number
1389
+ # and any frame the filter did not report counts as 0, so a build that drops frames again
1390
+ # cannot shift the neighbourhood.
1391
+ by_frame: "Dict[int, Tuple[float, float]]" = {}
1392
+ cur = None
1393
+ for line in proc.stdout.splitlines():
1394
+ m = SCORE_RE.match(line)
1395
+ if m:
1396
+ cur = (int(m.group(1)), float(m.group(2)))
1397
+ continue
1398
+ if line.startswith("lavfi.scd.score=") and cur is not None:
1399
+ try:
1400
+ by_frame[cur[0]] = (cur[1], float(line.split("=", 1)[1]))
1401
+ except ValueError:
1402
+ pass
1403
+ cuts = [0.0]
1404
+ if not by_frame:
1405
+ return cuts
1406
+ n_frames = max(by_frame) + 1
1407
+ times: "List[float]" = [by_frame[i][0] if i in by_frame else -1.0 for i in range(n_frames)]
1408
+ scores: "List[float]" = [by_frame[i][1] if i in by_frame else 0.0 for i in range(n_frames)]
1409
+ w = 12
1410
+ for i, sc in enumerate(scores):
1411
+ if sc < threshold:
1412
+ continue
1413
+ lo, hi = max(0, i - w), min(len(scores), i + w + 1)
1414
+ neigh = sorted(scores[lo:i] + scores[i + 1:hi])
1415
+ med = neigh[len(neigh) // 2] if neigh else 0.0
1416
+ if sc < ratio * max(med, 0.5):
1417
+ continue
1418
+ # keep only the local maximum inside +-2 frames
1419
+ if any(scores[j] > sc for j in range(max(0, i - 2), min(len(scores), i + 3)) if j != i):
1420
+ continue
1421
+ t = times[i]
1422
+ if t - cuts[-1] >= min_len:
1423
+ cuts.append(t)
1424
+ if duration - cuts[-1] < min_len and len(cuts) > 1:
1425
+ cuts.pop()
1426
+ return cuts
1427
+
1428
+
1429
+ # What a stream-copy join compares (cut.py --segments, join.py --copy).
1430
+ # codecs that carry no out-of-band configuration in these containers, so no extradata on
1431
+ # either side is a match, not a difference
1432
+ IN_BAND_CONFIG = ("mp3", "mp2", "vp8", "vp9")
1433
+ TS_EXTS = (".ts", ".m2ts", ".mts")
1434
+ _SIG_FIELDS = {"video": ("codec_name", "profile", "pix_fmt", "width", "height", "r_frame_rate", "time_base",
1435
+ "sample_aspect_ratio", "color_space", "color_range", "color_transfer", "color_primaries"),
1436
+ "audio": ("codec_name", "profile", "sample_rate", "channels", "time_base")}
1437
+
1438
+
1439
+ def stream_signature(doc: Dict[str, Any]) -> "List[Dict[str, Any]]":
1440
+ """What a stream-copy join needs to be identical across parts, from one ffprobe document
1441
+ (-show_streams with -show_data_hash sha256): each stream's type, codec parameters, rotation
1442
+ and extradata hash. Shared by cut.py's --segments join and join.py --copy."""
1443
+ sig = []
1444
+ for st in doc.get("streams") or []:
1445
+ kind = st.get("codec_type")
1446
+ entry = {"type": kind, "extradata_hash": st.get("extradata_hash")}
1447
+ entry.update({f: st.get(f) for f in _SIG_FIELDS.get(kind, ("codec_name",))})
1448
+ if kind == "video":
1449
+ entry["rotation"] = next((sd.get("rotation") for sd in st.get("side_data_list") or []
1450
+ if "rotation" in sd), None)
1451
+ sig.append(entry)
1452
+ return sig
1453
+
1454
+
1455
+ def signatures_match(sigs: list, ext: str) -> bool:
1456
+ """True when every part can be joined by stream copy: same streams in the same order with the
1457
+ same parameters. A missing extradata hash only matches another missing one where the codec (or
1458
+ an MPEG-TS output) carries its configuration in-band -- PCM has none at all."""
1459
+ if not sigs or any(sig is None for sig in sigs):
1460
+ return False
1461
+ first = sigs[0]
1462
+ for sig in sigs[1:]:
1463
+ if len(sig) != len(first):
1464
+ return False
1465
+ for a, b in zip(first, sig):
1466
+ if {k: v for k, v in a.items() if k != "extradata_hash"} != {k: v for k, v in b.items() if k != "extradata_hash"}:
1467
+ return False
1468
+ ha, hb = a.get("extradata_hash"), b.get("extradata_hash")
1469
+ if ha or hb:
1470
+ if ha != hb:
1471
+ return False
1472
+ else:
1473
+ codec = str(a.get("codec_name") or "")
1474
+ if not (codec.startswith("pcm_") or codec in IN_BAND_CONFIG or ext.lower() in TS_EXTS):
1475
+ return False
1476
+ return True
1477
+
1478
+
1479
+ # check.py --compare (2.24): the output's picture against a reference, frame by frame.
1480
+ COMPARE_SSIM_WARN = 0.98 # mean SSIM below this: a visible difference somewhere is likely
1481
+ # the channel letters follow the negotiated format: Y U V (or y u v) for YUV, R G B for RGB
1482
+ _SSIM_SUMMARY = re.compile(r"SSIM [A-Za-z]:[0-9.]+ .*All:([0-9.]+)")
1483
+ _PSNR_SUMMARY = re.compile(r"PSNR [a-z]:\S+ .*average:(\S+)")
1484
+ _SSIM_FRAME = re.compile(r"n:(\d+) .*All:([0-9.]+)")
1485
+
1486
+
1487
+ def compare_pictures(path: str, reference: str) -> "Optional[Dict[str, Any]]":
1488
+ """SSIM (mean and the worst frame) and PSNR (mean) of `path`'s first video stream against
1489
+ `reference`'s, frame by frame in decode order, in one pass. ffmpeg's ssim and psnr filters
1490
+ need equal sizes; the caller checks that first. None when the pass fails."""
1491
+ import tempfile
1492
+ from _common.decision import escape_filter_path
1493
+ with tempfile.TemporaryDirectory(prefix="ffskill_compare_") as tmp:
1494
+ stats = os.path.join(tmp, "ssim.log")
1495
+ # frames paired by index (settb/setpts=N): ssim and psnr otherwise pair by timestamp, so a
1496
+ # shifted or irregular timestamp would meet the wrong reference frame
1497
+ # shortest=1: by default the shorter file's last frame is repeated against the rest of
1498
+ # the longer one, which measures pairs that do not exist. format=yuv444p on both: the
1499
+ # filters otherwise take the first input's format, so an RGB file against a YUV one
1500
+ # measured differently by argument order
1501
+ graph = ("[0:V:0]settb=1/1000,setpts=N,format=yuv444p,split[a0][a1];"
1502
+ "[1:V:0]settb=1/1000,setpts=N,format=yuv444p,split[b0][b1];"
1503
+ f"[a0][b0]ssim=shortest=1:stats_file={escape_filter_path(stats, bind=False)};[a1][b1]psnr=shortest=1")
1504
+ proc = run_analysis([require_tool("ffmpeg"), "-hide_banner", "-nostdin", "-i", path, "-i", reference,
1505
+ "-filter_complex", graph, "-f", "null", "-"], check=False, record=True)
1506
+ if proc.returncode != 0:
1507
+ return None
1508
+ ssim, psnr = _SSIM_SUMMARY.search(proc.stderr), _PSNR_SUMMARY.search(proc.stderr)
1509
+ frames = []
1510
+ try:
1511
+ with open(stats, encoding="utf-8") as fh:
1512
+ frames = [(int(m.group(1)), float(m.group(2))) for m in map(_SSIM_FRAME.search, fh) if m]
1513
+ except OSError:
1514
+ pass
1515
+ if not ssim or not frames:
1516
+ return None
1517
+ worst = min(frames, key=lambda f: f[1])
1518
+ mean_psnr = psnr.group(1) if psnr else None
1519
+ return {"ssim": float(ssim.group(1)), "worst_ssim": worst[1], "worst_frame": worst[0] - 1, "frames": len(frames),
1520
+ "psnr": None if mean_psnr is None else (float("inf") if mean_psnr == "inf" else float(mean_psnr))}
1521
+
1522
+
1523
+ # check.py --compare --expect-changed (#439): where the picture differs from the reference.
1524
+ CHANGE_GRID = (32, 18) # tiles across and down: one is 60x60 px at 1080p
1525
+ CHANGE_FLOOR = 24 # a tile whose largest channel difference (0-255, area mean) is above this changed
1526
+
1527
+
1528
+ def change_tiles(path: str, reference: str, floor: int, grid: "Tuple[int, int]" = CHANGE_GRID,
1529
+ squares: "Tuple[str, str]" = ("", "")) -> "Optional[Dict[str, Any]]":
1530
+ """Which tiles of which frames of `path` differ from `reference`, frame i against frame i in
1531
+ decode order (as compare_pictures() pairs them; the caller checks sizes and frame counts).
1532
+ Both pictures go to 8-bit RGB planes, are subtracted, and each frame of the difference is
1533
+ area-scaled to `grid`; a tile's value is the largest of its three channels. `squares` is each
1534
+ file's square_pixels() filter, so the grid covers the displayed picture (display_size()) and a
1535
+ caller's rectangle in displayed pixels names the tiles it means on a non-square-pixel file.
1536
+ {frames, changed {frame index: a bit mask of the tiles above `floor`, bit column + row * columns;
1537
+ change_mask_tiles() lists them}, peaks {frame index: its largest tile}, quiet_peak (the largest
1538
+ tile at or under the floor)}. A mask and not a list: two unrelated hours differ in every tile
1539
+ of every frame, which as tuples is tens of millions of objects.
1540
+ None when the pass fails, times out of its bytes mid-frame, or decodes no frame: nothing was
1541
+ compared, which the caller must not read as "nothing changed"."""
1542
+ import subprocess
1543
+ import threading
1544
+ from _common import runner as _runner
1545
+ gw, gh = grid
1546
+ sq_a, sq_b = (s + "," if s else "" for s in squares)
1547
+ graph = (f"[0:V:0]{sq_a}settb=1/1000,setpts=N,format=gbrp[a];[1:V:0]{sq_b}settb=1/1000,setpts=N,format=gbrp[b];"
1548
+ f"[a][b]blend=all_mode=difference:shortest=1,scale={gw}:{gh}:flags=area[o]")
1549
+ # passthrough: the frames carry index timestamps, and a constant-rate muxer would drop
1550
+ # nearly all of them as duplicates (12 of 300 came out without it)
1551
+ cmd = [require_tool("ffmpeg"), "-hide_banner", "-loglevel", "error", "-nostdin", "-i", path, "-i", reference,
1552
+ "-filter_complex", graph, "-map", "[o]", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]
1553
+ # read frame by frame as ffmpeg writes them: 1728 bytes a frame is 187 MB for an hour at
1554
+ # 30 fps, and only the frames with a changed tile are kept. Same wall-clock limit as run_analysis()
1555
+ _runner._refuse_url_media(cmd)
1556
+ cmd = _runner.guard_input_names(cmd)
1557
+ limit = _runner._limit_for(cmd)
1558
+ size, tiles = gw * gh * 3, gw * gh
1559
+ changed: Dict[int, int] = {}
1560
+ peaks: Dict[int, int] = {}
1561
+ quiet, n, pending = 0, 0, b""
1562
+ child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, **_runner.child_kwargs())
1563
+ _runner._watch(child, cmd)
1564
+ expired = threading.Event()
1565
+
1566
+ def _expire() -> None:
1567
+ expired.set()
1568
+ child.kill()
1569
+
1570
+ timer = threading.Timer(limit, _expire) if limit else None
1571
+ if timer:
1572
+ timer.daemon = True
1573
+ timer.start()
1574
+ try:
1575
+ while True:
1576
+ chunk = child.stdout.read(size * 64)
1577
+ if not chunk:
1578
+ break
1579
+ pending += chunk
1580
+ whole = len(pending) - len(pending) % size
1581
+ for i in range(0, whole, size):
1582
+ frame = pending[i:i + size]
1583
+ top = max(frame)
1584
+ if top <= floor:
1585
+ quiet = max(quiet, top)
1586
+ else:
1587
+ mask = 0
1588
+ for t in range(tiles):
1589
+ value = max(frame[3 * t:3 * t + 3])
1590
+ if value > floor:
1591
+ mask |= 1 << t
1592
+ elif value > quiet:
1593
+ quiet = value
1594
+ changed[n], peaks[n] = mask, top
1595
+ n += 1
1596
+ pending = pending[whole:]
1597
+ child.wait()
1598
+ finally:
1599
+ if timer:
1600
+ timer.cancel()
1601
+ _runner._unwatch(child)
1602
+ child.stdout.close()
1603
+ if expired.is_set():
1604
+ _runner._timed_out(cmd, limit or 0)
1605
+ if child.returncode != 0 or not n or pending:
1606
+ return None
1607
+ return {"frames": n, "changed": changed, "peaks": peaks, "quiet_peak": quiet}
1608
+
1609
+
1610
+ def change_mask_tiles(mask: int, grid: "Tuple[int, int]" = CHANGE_GRID) -> "List[Tuple[int, int]]":
1611
+ """change_tiles()'s bit mask as [(column, row)], row by row."""
1612
+ gw = grid[0]
1613
+ return [(t % gw, t // gw) for t in range(grid[0] * grid[1]) if mask >> t & 1]