@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,815 @@
1
+ #!/usr/bin/env python3
2
+ """Pre-delivery compliance check: does this file meet the platform's spec?
3
+
4
+ Checks duration, frame size / aspect, fps, codec, pixel format, colour tags,
5
+ file size, integrated loudness and true peak against the chosen platform
6
+ and prints a PASS/WARN/FAIL table. Exit code 1 when anything FAILs. A length
7
+ or file size over the platform table's limit is WARN (`basis: guidance`): upload
8
+ limits change and the uploader checks the current one; --max-duration / --max-mb
9
+ state the caller's own limit, which FAILs when a --platform is named (with none,
10
+ an over-length is WARN, as every judgement row is). Each
11
+ row's `fix` is the command that resolves it; a few of the less obvious FAILs
12
+ (video codec, pixel format, HDR colour, loudness) also carry a plain-language
13
+ `reason` -- "QuickTime and iOS commonly reject video that isn't 8-bit 4:2:0",
14
+ not a restatement of the spec value -- for a caller reporting this to someone
15
+ who doesn't already know why the spec says what it says.
16
+
17
+ Platforms: youtube, shorts, reels, tiktok, x, linkedin, facebook, broadcast (EBU R128),
18
+ podcast, custom -- one table, shared with export.py and the render.py templates
19
+
20
+ Examples:
21
+ python3 check.py final.mp4 --platform youtube
22
+ python3 check.py reel.mp4 --platform reels --json
23
+ python3 check.py spot.mov --platform broadcast
24
+ python3 check.py clip.mp4 --platform custom --max-duration 30 --aspect 1:1 --lufs -16
25
+ python3 check.py final.mp4 --platform reels --content
26
+
27
+ --content (opt-in) adds content rows from one decode pass: black (share of the
28
+ duration that is black: WARN > 10%, FAIL >= 95%), frozen (longest frozen span: WARN >
29
+ max(3 s, 30% of the duration), FAIL when the whole video is frozen) and silence (share
30
+ below -50 dBFS: WARN > 50%, FAIL >= 95%); and, from one more audio-only pass (2.17),
31
+ dropouts (gaps of digital silence, <= -80 dBFS for 20 ms to 1 s with sound on both sides:
32
+ WARN when there is any); and, from one more video pass and a one-frame decode (2.23), flashes
33
+ (single frames that differ from both neighbours while they match each other: WARN when there is
34
+ any) and first frame (one flat colour, the frame a feed's autoplay shows first: WARN). Without it
35
+ the row set is unchanged.
36
+
37
+ --levels bt709|ebu-r103 (opt-in) decodes every frame once more and adds a legal levels row: the share
38
+ of luma and of chroma samples outside the standard's legal range, counted exactly per frame, with
39
+ min/max Y/U/V (FAIL when any frame's share passes --levels-tolerance, 1 % by default). The JSON
40
+ `levels` document repeats it per clip and per --levels-window seconds (10 by default).
41
+ """
42
+ import argparse
43
+ import json
44
+ import os
45
+ import re
46
+ import sys
47
+ from fractions import Fraction
48
+ from typing import Any, Dict, List, Optional, Tuple
49
+
50
+ from _platforms import PLATFORMS, PLATFORM_CHOICES, TP_TOLERANCE_DB, spec_of, upload_limit_note, resolve as resolve_platform
51
+ from _common.probe import (CHANGE_FLOOR, CHANGE_GRID, change_mask_tiles, change_tiles, LEGAL_RANGE_CHOICES, measure_signal_range, COMPARE_SSIM_WARN, CONTENT_FLAT_STD, SILENT_PEAK_DBFS, compare_pictures, detect_content,
52
+ detect_flashes, first_frame_stats, presentation_times, measured_level_dbfs)
53
+ from _common.emit import file_identity, own_length
54
+ from _common.probe import PROBED_AUDIO
55
+ from _common.probe import display_size as shown_size, shorter_than_a_loudness_block
56
+ from _common import STATE, add_common, apply_common, die, emit, probe, require_tool, run_analysis, dry_run_input_pending
57
+
58
+ # The one delivery table (scripts/_platforms.py): check.py's rows, export.py's presets and the
59
+ # render.py templates all read it, so a platform's loudness spec is stated once. Only the
60
+ # destinations that are compliance targets appear here; youtube-hdr / youtube-av1 are export
61
+ # presets of the youtube target, not separate specs.
62
+ SPECS: Dict[str, Dict[str, Any]] = {name: spec_of(name) for name in sorted(PLATFORMS)
63
+ if PLATFORMS[name]["check"] == name}
64
+
65
+
66
+ def measure_loudness(path: str) -> Dict[str, float]:
67
+ if dry_run_input_pending(path):
68
+ return {}
69
+ ffmpeg = require_tool("ffmpeg")
70
+ # the first audio track, the one the audio row's probe facts describe (and the one export and
71
+ # loudness write): default selection measured the track with the most channels
72
+ proc = run_analysis([ffmpeg, "-hide_banner", "-nostdin", "-i", path, "-map", f"0:{PROBED_AUDIO}", "-vn",
73
+ "-af", "loudnorm=I=-14:TP=-1:LRA=11:print_format=json", "-f", "null", "-"], check=False, record=True)
74
+ m = re.search(r"\{[^{}]*\"input_i\"[^{}]*\}", proc.stderr, re.S)
75
+ if not m:
76
+ return {}
77
+ d = json.loads(m.group(0))
78
+ try:
79
+ return {"lufs": float(d["input_i"]), "tp": float(d["input_tp"]), "lra": float(d["input_lra"])}
80
+ except (KeyError, ValueError):
81
+ return {}
82
+
83
+
84
+ # --content thresholds (docs/design-decisions.md, "check.py --content").
85
+ BLACK_WARN, BLACK_FAIL = 0.10, 0.95 # share of the duration that is black
86
+ FROZEN_WARN_S, FROZEN_WARN_SHARE = 3.0, 0.30 # longest frozen span: WARN above max(3 s, 30%)
87
+ FROZEN_FAIL = 0.95 # a frozen span covering this share = whole video frozen
88
+ SILENCE_WARN, SILENCE_FAIL = 0.50, 0.95 # share of the duration below SILENT_PEAK_DBFS
89
+ # --levels: the share of one frame's luma (or chroma) samples that may sit outside the legal range
90
+ # before the row FAILs -- room for a filter's overshoot at a sharp edge, not a licence for a clipped sky
91
+ LEVELS_TOLERANCE_PCT = 1.0
92
+ # pixel formats whose planes are Y'CbCr (an RGB or grey picture has no luma/chroma codes to count)
93
+ _YUV_PREFIXES = ("yuv", "yuvj", "nv", "p01", "p21", "p41", "y21", "uyvy", "yuyv", "ayuv", "vuya", "xv")
94
+
95
+
96
+ STATE_NOTES: List[str] = []
97
+
98
+
99
+ def flash_times(flashes: List[int], v: Dict[str, Any], meta: Dict[str, Any], pts: "Optional[List[float]]" = None) -> str:
100
+ """The flashes row's first five times on look.py's timeline (seconds from the container
101
+ start). A flash frame's own presentation time when `pts` has it (presentation_times(): exact,
102
+ gaps in the timestamps included); otherwise index / average rate plus the video's lead over
103
+ the container, marked "~" (approximate), and `frame N` when there is no frame rate either."""
104
+ return ", ".join(frame_time(n, v, meta, pts) for n in flashes[:5]) + (" ..." if len(flashes) > 5 else "")
105
+
106
+
107
+ def frame_time(n: int, v: Dict[str, Any], meta: Dict[str, Any], pts: "Optional[List[float]]" = None) -> str:
108
+ """Frame `n` (decode order) on look.py's timeline, as flash_times() describes: exact from
109
+ `pts`, else "~" index / average rate plus the video's lead, else `frame N`."""
110
+ origin = float(meta.get("start_time") or 0.0)
111
+ if pts and n < len(pts):
112
+ return f"{max(0.0, pts[n] - origin):.2f}s"
113
+ fps = float(v.get("fps") or 0.0)
114
+ lead = max(0.0, float(v.get("start_time") or 0.0) - origin)
115
+ return f"~{lead + n / fps:.2f}s" if fps else f"frame {n}"
116
+
117
+
118
+ def display_size(v: Dict[str, Any]) -> "Tuple[int, int]":
119
+ """The frame size as decoded and auto-rotated, which is what --compare's ffmpeg pass sees."""
120
+ w, h = int(v.get("width") or 0), int(v.get("height") or 0)
121
+ return (h, w) if int(v.get("rotation") or 0) % 180 == 90 else (w, h)
122
+
123
+
124
+ def parse_expect_changed(values: "List[str]") -> "List[Dict[str, Any]]":
125
+ """--expect-changed values -> [{start, end, rect}] (rect [x, y, w, h] in displayed pixels, or
126
+ None for the whole frame); [] for `none`. Refuses anything it cannot read: a declaration that
127
+ was silently dropped would turn into a FAIL the caller cannot explain, or a PASS it did not earn."""
128
+ from _common.decision import parse_time
129
+ import math
130
+ if any(v.strip().lower() == "none" for v in values):
131
+ if len(values) > 1:
132
+ die("--expect-changed none says the picture must not change at all; it cannot be combined with a span")
133
+ return []
134
+ spans = []
135
+ for raw in values:
136
+ span, _, rect_text = raw.strip().partition("@")
137
+ start_text, sep, end_text = span.partition("-")
138
+ try:
139
+ if not sep or not start_text or not end_text:
140
+ raise ValueError(raw)
141
+ start, end = parse_time(start_text), parse_time(end_text)
142
+ except (ValueError, SystemExit):
143
+ die(f"--expect-changed takes START-END (seconds or H:MM:SS), optionally @X,Y,W,H, or none; got {raw!r}")
144
+ if not (math.isfinite(start) and math.isfinite(end)) or start < 0 or end < start:
145
+ die(f"--expect-changed {raw!r}: a span starts at 0 or later and ends at or after its start")
146
+ rect = None
147
+ if "@" in raw:
148
+ try:
149
+ rect = [int(n) for n in rect_text.split(",")]
150
+ except ValueError:
151
+ rect = []
152
+ if len(rect) != 4 or rect[0] < 0 or rect[1] < 0 or rect[2] <= 0 or rect[3] <= 0:
153
+ die(f"--expect-changed {raw!r}: the rectangle is X,Y,W,H in displayed pixels, whole numbers, W and H above 0")
154
+ spans.append({"start": start, "end": end, "rect": rect})
155
+ return spans
156
+
157
+
158
+ def _runs(frames: "List[int]") -> "List[Tuple[int, int]]":
159
+ """Sorted frame indices -> [(first, last)] of consecutive runs."""
160
+ out: "List[Tuple[int, int]]" = []
161
+ for n in frames:
162
+ if out and n == out[-1][1] + 1:
163
+ out[-1] = (out[-1][0], n)
164
+ else:
165
+ out.append((n, n))
166
+ return out
167
+
168
+
169
+ def change_scope(tiles: "Dict[str, Any]", declared: "List[Dict[str, Any]]", times: "List[float]",
170
+ size: "Tuple[int, int]", floor: int) -> "Dict[str, Any]":
171
+ """The measured tiles against the declaration. `times` has one more entry than there are
172
+ frames (frame n is shown from times[n] until times[n+1]). A declared span is closed at both
173
+ ends and widened to whole frames: frame n is inside when its interval touches the span.
174
+ Inside a span with a rectangle, only the tiles the rectangle touches may change."""
175
+ gw, gh = CHANGE_GRID
176
+ w, h = size
177
+ tw, th = w / gw, h / gh
178
+
179
+ def allowed_mask(rect: "Optional[List[int]]") -> int:
180
+ if rect is None:
181
+ return (1 << gw * gh) - 1
182
+ x, y, rw, rh = rect
183
+ return sum(1 << (c + r * gw) for c in range(gw) for r in range(gh)
184
+ if c * tw < x + rw and (c + 1) * tw > x and r * th < y + rh and (r + 1) * th > y)
185
+
186
+ spans = [dict(d, mask=allowed_mask(d["rect"]), seen=False) for d in declared]
187
+
188
+ def describe(frames: "Dict[int, int]") -> "List[Dict[str, Any]]":
189
+ out = []
190
+ for first, last in _runs(sorted(frames)):
191
+ union = 0
192
+ for n in range(first, last + 1):
193
+ union |= frames[n]
194
+ hit = change_mask_tiles(union)
195
+ c0, c1 = min(c for c, _ in hit), max(c for c, _ in hit)
196
+ r0, r1 = min(r for _, r in hit), max(r for _, r in hit)
197
+ x0, y0, x1, y1 = int(c0 * tw), int(r0 * th), int(round((c1 + 1) * tw)), int(round((r1 + 1) * th))
198
+ out.append({"start": round(times[first], 3), "end": round(times[last + 1], 3), "frames": last - first + 1,
199
+ "rect": [x0, y0, x1 - x0, y1 - y0], "peak": max(tiles["peaks"][n] for n in range(first, last + 1))})
200
+ return out
201
+
202
+ outside: "Dict[int, int]" = {}
203
+ for n, changed in tiles["changed"].items():
204
+ left = changed
205
+ for d in spans:
206
+ if times[n] <= d["end"] and times[n + 1] > d["start"]:
207
+ # against the frame's own tiles, not what earlier declarations left of them: two
208
+ # declarations that overlap would otherwise depend on their order, and the later
209
+ # one would read as "nothing changed there"
210
+ if changed & d["mask"]:
211
+ d["seen"] = True
212
+ left &= ~d["mask"]
213
+ if left:
214
+ outside[n] = left
215
+ return {"declared": [{"start": d["start"], "end": d["end"], "rect": d["rect"]} for d in declared],
216
+ "observed": describe(tiles["changed"]), "undeclared": describe(outside),
217
+ "declared_unchanged": [{"start": d["start"], "end": d["end"], "rect": d["rect"]} for d in spans if not d["seen"]],
218
+ "floor": floor, "tile": [gw, gh], "frames": tiles["frames"], "quiet_peak": tiles["quiet_peak"]}
219
+
220
+
221
+ def _span_total(spans: Any) -> float:
222
+ return sum(max(0.0, e - s) for s, e in spans)
223
+
224
+
225
+ def aspect_name(w: int, h: int) -> str:
226
+ f = Fraction(w, h)
227
+ for name, target in (("16:9", Fraction(16, 9)), ("9:16", Fraction(9, 16)), ("1:1", Fraction(1)), ("4:5", Fraction(4, 5)), ("4:3", Fraction(4, 3)), ("21:9", Fraction(21, 9))):
228
+ if abs(float(f) - float(target)) < 0.02:
229
+ return name
230
+ return f"{f.numerator}:{f.denominator}"
231
+
232
+
233
+ def levels_row(args: argparse.Namespace, v: Dict[str, Any], row: Any) -> "Optional[Dict[str, Any]]":
234
+ """--levels: measure the signal range (measure_signal_range) and add the legal levels row.
235
+ Returns the JSON `levels` document, or None when nothing was measured."""
236
+ expect = f"every frame <= {args.levels_tolerance:g}% of luma and of chroma samples outside {args.levels}"
237
+ pix = str(v.get("pix_fmt") or "")
238
+ if not v:
239
+ return None
240
+ if not pix.startswith(_YUV_PREFIXES):
241
+ row("legal levels", "WARN", f"not measured: {pix or 'unknown'} is not a Y'CbCr picture", expect,
242
+ "legal levels are measured on the Y'CbCr file a broadcaster receives: check the encoded delivery, not an RGB master",
243
+ reason="an RGB or grey picture has no luma and chroma codes to count")
244
+ return None
245
+ doc = measure_signal_range(args.input, args.levels, args.levels_window, pix_fmt=pix)
246
+ if doc is None:
247
+ row("legal levels", "WARN", "could not measure", expect, "re-run check.py --levels, or look.py the picture",
248
+ reason="the decode failed or stopped part-way, so the signal range of the whole file is unknown")
249
+ return None
250
+ pct, worst = doc["out_of_range_pct"], doc["worst_frame"]
251
+ over = worst["y_pct"] > args.levels_tolerance or worst["chroma_pct"] > args.levels_tolerance
252
+ at = "" if worst["time"] is None else f" at {worst['time']:.2f}s"
253
+ lo, hi = doc["min"], doc["max"]
254
+ value = (f"luma {pct['y']:.3f}%, chroma {pct['chroma']:.3f}% out of range (worst frame{at}: luma {worst['y_pct']:.3f}%, "
255
+ f"chroma {worst['chroma_pct']:.3f}%); Y {lo['y']}-{hi['y']}, U {lo['u']}-{hi['u']}, V {lo['v']}-{hi['v']}")
256
+ full = v.get("color_range") == "pc" or pix.startswith("yuvj")
257
+ if full:
258
+ STATE_NOTES.append("--levels: the picture is tagged full range (0-255 codes by design), so it was counted against "
259
+ "the limited-range limits a broadcast file uses; convert it to limited range before judging the row")
260
+ row("legal levels", "FAIL" if over else "PASS", value, expect,
261
+ f"color.py {args.input} --legalize {args.levels} (clamps after the 4:2:0 conversion and measures the result), or "
262
+ "pull the highlights and shadows in with a soft clip in the grade and check again" if over else "",
263
+ reason="a broadcaster's QC rejects or clips a picture whose levels leave the legal range" if over else "")
264
+ return doc
265
+
266
+
267
+ def encoding_differences(v: Dict[str, Any], rv: Dict[str, Any]) -> "List[str]":
268
+ """What makes two video streams "not encoded alike" for --expect-changed: part of a measured
269
+ difference is then the encoder's. The stored size is the file's own width and height, before
270
+ rotation: 1080x1920 turned to 1920x1080 against a stored 1920x1080 is the same displayed
271
+ picture stored another way (as is 1440x1080 at 4:3), compared and said."""
272
+ def stored(x: Dict[str, Any]) -> str:
273
+ return f"{x.get('width')}x{x.get('height')}"
274
+ pairs = (("codec", v.get("codec"), rv.get("codec")), ("pix_fmt", v.get("pix_fmt"), rv.get("pix_fmt")),
275
+ ("fps", v.get("fps"), rv.get("fps")), ("stored size", stored(v), stored(rv)))
276
+ return [f"{k} {a} against {b}" for k, a, b in pairs if a != b]
277
+
278
+
279
+ def change_scope_row(args: Any, declared: "List[Dict[str, Any]]", meta: Dict[str, Any], v: Dict[str, Any], row: Any) -> "Optional[Dict[str, Any]]":
280
+ """--expect-changed: measure where the picture differs from the reference and grade it against
281
+ the declaration. A comparison that could not be made is a FAIL, never a WARN or a PASS: the
282
+ flag exists to stop a false "nothing else changed", and a check that did not run would be one."""
283
+ want = "a change only where declared" if declared else "no change in the picture"
284
+ look = f"look.py --compare {args.compare} --at "
285
+
286
+ def not_compared(why: str, fix: str) -> None:
287
+ row("change_scope", "FAIL", f"not compared: {why}", want, fix,
288
+ reason="nothing was measured, so this does not say the rest of the picture is unchanged")
289
+
290
+ ref = probe(args.compare)
291
+ rv = ref.get("video") or {}
292
+ if not v or not rv:
293
+ return not_compared("one of the files has no picture", "--expect-changed needs a video stream in both files")
294
+ # the displayed picture: rotation applied and non-square pixels squared (a 1440x1080 file at
295
+ # 4:3 is 1920x1080), which is the frame a caller measures a rectangle on and the frame both
296
+ # pictures are brought to before they are subtracted
297
+ from _common.probe import display_size as shown_size, square_pixels
298
+ size = shown_size(v)
299
+ if size != shown_size(rv):
300
+ return not_compared("%dx%d against %dx%d (as displayed)" % (size + shown_size(rv)),
301
+ "compare two renders of the same frame size")
302
+ for d in declared:
303
+ if d["rect"] and (d["rect"][0] + d["rect"][2] > size[0] or d["rect"][1] + d["rect"][3] > size[1]):
304
+ # a rectangle that runs past the edge is a wrong size or a wrong file, and clipping it
305
+ # quietly would allow less than the caller believes it declared
306
+ die(f"--expect-changed: the rectangle {','.join(map(str, d['rect']))} does not fit inside the {size[0]}x{size[1]} picture")
307
+ origin = float(meta.get("start_time") or 0.0)
308
+ pts = presentation_times(args.input, float(v.get("start_time") or 0.0))
309
+ ref_pts = presentation_times(args.compare, float(rv.get("start_time") or 0.0))
310
+ nout, nref = v.get("nb_frames") or len(pts) or None, rv.get("nb_frames") or len(ref_pts) or None
311
+ if not nout or not nref:
312
+ return not_compared("a frame count could not be read", "remux the file that has no readable frame count (export.py --preset copy)")
313
+ if int(nout) != int(nref):
314
+ return not_compared(f"{nout} frames against the reference's {nref}",
315
+ "an edit that changes the length cannot be paired frame by frame; compare the parts separately")
316
+ tiles = change_tiles(args.input, args.compare, args.change_floor, squares=(square_pixels(v), square_pixels(rv)))
317
+ if tiles is None:
318
+ return not_compared("the comparison pass failed", look + "0")
319
+ n = tiles["frames"]
320
+ fps = float(v.get("fps") or 0.0)
321
+ if pts and len(pts) >= n:
322
+ times = [max(0.0, t - origin) for t in pts[:n]]
323
+ times.append(times[-1] + ((times[-1] - times[-2]) if n > 1 else (1.0 / fps if fps else 0.0)))
324
+ else:
325
+ # a span is placed by each frame's own time, and a change is reported at one; an average
326
+ # rate would put a frame near a span's edge on the wrong side of it, and is simply wrong
327
+ # on variable-rate video. `none` too: its FAIL names where the change is
328
+ return not_compared("the frame times could not be read", "remux the file (export.py --preset copy) and check it again")
329
+ doc = change_scope(tiles, declared, times, size, args.change_floor)
330
+
331
+ def span(d: "Dict[str, Any]") -> str:
332
+ return f"{d['start']:.2f}-{d['end']:.2f}"
333
+
334
+ def place(d: "Dict[str, Any]") -> str:
335
+ x, y, w, h = d["rect"]
336
+ return f"{span(d)} ({d['frames']} frame{'s' if d['frames'] != 1 else ''}, around x {x}-{x + w}, y {y}-{y + h})"
337
+
338
+ idle = "; ".join(f"declared {span(d)} but nothing changed there" for d in doc["declared_unchanged"])
339
+ differ = encoding_differences(v, rv)
340
+ if differ:
341
+ STATE_NOTES.append("--expect-changed: the two files are not encoded alike (" + ", ".join(differ) + "), so part of "
342
+ "what was measured is the encoder's difference, not the edit")
343
+ floor_note = f"floor {doc['floor']}, largest unchanged tile {doc['quiet_peak']}"
344
+ if doc["undeclared"]:
345
+ first = doc["undeclared"][0]
346
+ more = len(doc["undeclared"]) - 1
347
+ value = "changed " + place(first) + (f" and {more} more span{'s' if more != 1 else ''}" if more else "") + ": not declared"
348
+ row("change_scope", "FAIL", value + (f"; {idle}" if idle else "") + f" ({floor_note})", want,
349
+ look + f"{first['start']:g}", reason="the picture changed where the edit was not meant to reach")
350
+ elif idle:
351
+ row("change_scope", "WARN", idle + f" ({floor_note})", want, "look at that span: the edit probably did not apply",
352
+ reason="a declared change was not found")
353
+ else:
354
+ seen = ", ".join(span(d) for d in doc["observed"]) or "nothing"
355
+ value = (f"changed {seen} inside the declared span{'s' if len(declared) != 1 else ''}; nothing else above the floor"
356
+ if declared else "no tile above the floor in any frame") + f" ({floor_note}, {n} frames)"
357
+ row("change_scope", "WARN" if differ else "PASS", value, want,
358
+ "compare two renders made with the same encoder settings" if differ else "",
359
+ reason="the two files are not encoded alike: " + ", ".join(differ) if differ else "")
360
+ return doc
361
+
362
+
363
+ def main() -> int:
364
+ STATE_NOTES.clear() # module state: a second main() in one process starts without the first's notes
365
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
366
+ ap.add_argument("input")
367
+ ap.add_argument("--platform", choices=PLATFORM_CHOICES, default=None, help="delivery spec to check against (default: youtube, with judgement rows reported as WARN because no platform was named)")
368
+ ap.add_argument("--max-duration", type=float, help="the caller's own maximum length in seconds: over it FAILs when a --platform is named, WARNs with none (the platform table's limit is guidance, WARN)")
369
+ ap.add_argument("--aspect", help="override allowed aspect (e.g. 9:16 or 16:9,1:1)")
370
+ ap.add_argument("--lufs", type=float, help="override loudness target, in LUFS (-14 for most platforms)")
371
+ ap.add_argument("--tp", type=float, help="override true-peak ceiling, in dBTP (-1 for most platforms)")
372
+ ap.add_argument("--max-mb", type=float, help="the caller's own maximum file size in MB: over it FAILs (the platform table's limit is guidance, WARN)")
373
+ ap.add_argument("--no-loudness", action="store_true", help="skip the loudness measurement (faster)")
374
+ ap.add_argument("--content", action="store_true",
375
+ help="also check the content (one decode pass, plus an audio-only and a video-only one): black, frozen, silence, dropouts, flashes and first frame rows")
376
+ ap.add_argument("--levels", choices=LEGAL_RANGE_CHOICES, default=None,
377
+ help="also measure the broadcast signal range (one more decode of every frame): a legal levels row with "
378
+ "the share of luma and chroma samples outside bt709 (16-235 / 16-240) or ebu-r103 (luma -1..103 %%), "
379
+ "and min/max Y/U/V; the JSON levels document has it per clip and per --levels-window")
380
+ ap.add_argument("--levels-window", type=float, default=10.0, metavar="SECONDS",
381
+ help="--levels: report the shares for every window of this many seconds too (default 10; 0 = the whole clip only)")
382
+ ap.add_argument("--levels-tolerance", type=float, default=LEVELS_TOLERANCE_PCT, metavar="PCT",
383
+ help="--levels: the legal levels row FAILs when one frame has more than this percentage of its luma or of "
384
+ "its chroma samples out of range (default %(default)g; 0 = any sample)")
385
+ ap.add_argument("--compare", metavar="REFERENCE",
386
+ help="also measure the picture against REFERENCE, frame by frame (SSIM and PSNR, one pass): a "
387
+ "similarity row, WARN when the mean SSIM is under 0.98, with the worst frame's time")
388
+ ap.add_argument("--expect-changed", action="append", metavar="SPAN[@X,Y,W,H]|none",
389
+ help="with --compare: where the picture is allowed to differ from REFERENCE, as START-END in this "
390
+ "file's time (repeatable), optionally only inside a rectangle of displayed pixels, or `none`. A "
391
+ "change_scope row FAILs on a change anywhere else (with its time and place) or when the two "
392
+ "could not be compared, and WARNs when a declared span did not change")
393
+ ap.add_argument("--change-floor", type=int, default=CHANGE_FLOOR, metavar="N",
394
+ help="--expect-changed: a 60x60-ish tile (the frame in %dx%d) counts as changed when its largest "
395
+ "channel difference is above N of 255 (default %%(default)d)" % CHANGE_GRID)
396
+ ap.add_argument("--expect-identity", metavar="SIZE:MTIME_NS",
397
+ help="the output_identity a writing tool reported ({size}:{mtime_ns}): an identity row FAILs when "
398
+ "the file at INPUT is not that file (a later run replaced it, or a failed run left an older one)")
399
+ add_common(ap)
400
+ args = ap.parse_args()
401
+ apply_common(args)
402
+
403
+ # Eval 7: runs that only wanted the format rows got youtube's loudness / true-peak FAILs and
404
+ # spent a paragraph explaining why they left them alone. Without a named platform the
405
+ # judgement rows are advisory: WARN, not FAIL, and not counted as failed.
406
+ named = args.platform is not None
407
+ args.platform = resolve_platform(args.platform) or "youtube"
408
+ spec = dict(SPECS[args.platform])
409
+ if args.max_duration is not None:
410
+ spec["max_duration"] = args.max_duration
411
+ if args.aspect:
412
+ spec["aspects"] = [a.strip() for a in args.aspect.split(",")]
413
+ if args.lufs is not None:
414
+ spec["lufs"] = args.lufs
415
+ if args.tp is not None:
416
+ spec["tp"] = args.tp
417
+ if args.max_mb is not None:
418
+ spec["max_bytes"] = int(args.max_mb * 1024 * 1024)
419
+ if args.levels_window < 0:
420
+ die(f"--levels-window {args.levels_window:g}: a window is 0 (the whole clip only) or a number of seconds")
421
+ if not 0 <= args.levels_tolerance <= 100:
422
+ die(f"--levels-tolerance {args.levels_tolerance:g} is outside 0..100 (percent of a frame's samples)")
423
+
424
+ declared_changes = None
425
+ if args.expect_changed:
426
+ if not args.compare:
427
+ die("--expect-changed says where the picture may differ from a reference, so it needs --compare REFERENCE")
428
+ declared_changes = parse_expect_changed(args.expect_changed)
429
+ if not 1 <= args.change_floor <= 254:
430
+ die(f"--change-floor {args.change_floor} is outside 1..254 (a difference of 0-255 per channel)")
431
+
432
+ expected_identity = None
433
+ if args.expect_identity is not None:
434
+ # parsed before any measurement; "" (an unset shell variable) is malformed, not absent
435
+ try:
436
+ size, mtime_ns = (int(x) for x in args.expect_identity.split(":"))
437
+ except ValueError:
438
+ die(f"--expect-identity takes SIZE:MTIME_NS from a tool's output_identity, got {args.expect_identity!r}")
439
+ expected_identity = {"size": size, "mtime_ns": mtime_ns}
440
+
441
+ # read before anything is measured and again after: a file replaced mid-check is not the one graded
442
+ identity_before = None if dry_run_input_pending(args.input) else file_identity(args.input)
443
+ if identity_before is None and STATE.dry_run and not os.path.exists(args.input):
444
+ # a render/batch plan's earlier stage would write this file: there is nothing to grade yet,
445
+ # and grading the probe's empty answer divided by a 0 height
446
+ emit(None, platform=args.platform, checks=[], failed=0, warnings=0, ok=False,
447
+ notes=[f"[dry-run] {args.input} does not exist yet, so nothing was checked"])
448
+ return 0
449
+ meta = probe(args.input)
450
+ v, a = meta.get("video") or {}, meta.get("audio") or {}
451
+ rows: List[Dict[str, Any]] = []
452
+
453
+ # first frame / flashes: a fade from black or a strobe can be the edit, so neither is a mechanical fix
454
+ JUDGEMENT = {"duration", "aspect", "loudness", "true peak", "fps", "resolution", "first frame", "flashes"}
455
+ # #485: the rows whose limit is the platform table's upload limit rather than one the caller
456
+ # stated (--max-duration, --max-mb). Those are guidance: WARN at worst, never counted as failed.
457
+ guidance = {name for name, stated, limit in (("duration", args.max_duration, spec["max_duration"]),
458
+ ("file size", args.max_mb, spec["max_bytes"]))
459
+ if stated is None and limit}
460
+
461
+ def row(name: str, status: str, value: Any, expect: Any, fix: str = "", reason: str = "") -> None:
462
+ # "format" rows are safe to fix mechanically; "judgement" rows change the content
463
+ # (what is cut, what is cropped, how loud ambience gets) and need a decision.
464
+ # "fix" is the command that resolves it; "reason" (only on the FAILs a non-technical
465
+ # person would ask "so what?" about) is why it matters in plain terms, not the spec clause.
466
+ if status == "FAIL" and not named and name in JUDGEMENT:
467
+ status = "WARN"
468
+ # "basis" is where the expected value comes from: "requirement" (the delivery format, or a
469
+ # limit the caller stated) can FAIL; "guidance" (the table's upload limit) cannot.
470
+ basis = "guidance" if name in guidance else "requirement"
471
+ if basis == "guidance" and status != "PASS":
472
+ status = "WARN"
473
+ reason = (reason + "; " if reason else "") + upload_limit_note(args.platform)
474
+ rows.append({"check": name, "status": status, "value": value, "expected": expect, "fix": fix,
475
+ "reason": reason if status != "PASS" else "",
476
+ "kind": "judgement" if name in JUDGEMENT else "format", "basis": basis})
477
+
478
+ # A113: a length ffprobe did not report is not a length of 0 s that fits under every limit.
479
+ # The row says it was not measured (FAIL under a length limit the caller stated, WARN under the
480
+ # platform table's or without one), and the
481
+ # --content rows that are shares of the running time say so too instead of disappearing.
482
+ dur_read = meta.get("duration")
483
+ dur = dur_read or 0.0
484
+ if dur_read is None:
485
+ row("duration", "FAIL" if spec["max_duration"] else "WARN", "could not measure",
486
+ f"<= {spec['max_duration']:g}s" if spec["max_duration"] else "any",
487
+ "remux the file (export.py --preset copy) so the container states its length, then check again",
488
+ reason="the file does not state its length, so whether it is within the limit is unknown")
489
+ elif spec["max_duration"]:
490
+ row("duration", "PASS" if dur <= spec["max_duration"] else "FAIL", f"{dur:.2f}s", f"<= {spec['max_duration']:g}s", "choose what to keep with cut.py, or explicitly retime with fit.py --duration N --method speed")
491
+ else:
492
+ row("duration", "PASS", f"{dur:.2f}s", "any")
493
+
494
+ if v:
495
+ w, h = v["width"], v["height"]
496
+ if v.get("rotation") in (90, -90, 270, -270):
497
+ w, h = h, w
498
+ # A114: the aspect a viewer sees is the displayed frame's (rotation and SAR applied), not
499
+ # the stored grid's: 1440x1080 at SAR 4:3 is a 16:9 picture
500
+ asp = aspect_name(*shown_size(v)) if all(shown_size(v)) else aspect_name(w, h)
501
+ if spec["aspects"]:
502
+ row("aspect", "PASS" if asp in spec["aspects"] else "FAIL", asp, "/".join(spec["aspects"]), f"fit.py --aspect {spec['aspects'][0]} --fit pad (keeps everything, adds bars) or crop (fills the frame, loses the edges: check the subject with look.py)")
503
+ else:
504
+ row("aspect", "PASS", asp, "any")
505
+ short = min(w, h)
506
+ if spec["min_height"]:
507
+ row("resolution", "PASS" if short >= spec["min_height"] else "WARN", f"{w}x{h}", f"short side >= {spec['min_height']}", "upscaling will not add detail; re-export from the master")
508
+ fps = v.get("fps") or 0
509
+ if spec["fps_max"] and not fps:
510
+ # a rate ffprobe did not report is not 0 fps under every limit (the class of A113)
511
+ row("fps", "WARN", "could not measure", f"<= {spec['fps_max']}", "re-encode at a fixed rate (fit.py --fps N)",
512
+ reason="the stream states no frame rate, so whether it is within the limit is unknown")
513
+ elif spec["fps_max"]:
514
+ row("fps", "PASS" if fps <= spec["fps_max"] + 0.01 else "FAIL", f"{fps:g}", f"<= {spec['fps_max']}", "fit.py --fps 30 (drops half the frames of 60 fps motion; fine for talking heads, visible on sports/gaming)")
515
+ row("vfr", "PASS" if not v.get("variable_frame_rate_suspected") else "WARN", "variable" if v.get("variable_frame_rate_suspected") else "constant", "constant", "fit.py --fps N (any re-encode conforms it)")
516
+ if spec["codecs"]:
517
+ row("video codec", "PASS" if v.get("codec") in spec["codecs"] else "FAIL", v.get("codec"), "/".join(spec["codecs"]), "export.py --preset " + (PLATFORMS[args.platform].get("preset") or "youtube"),
518
+ reason="the platform's player may refuse to decode this codec at all, not just look worse")
519
+ pf = v.get("pix_fmt") or ""
520
+ if args.platform in ("reels", "tiktok", "x", "linkedin", "facebook"):
521
+ row("pixel format", "PASS" if pf == "yuv420p" else "FAIL", pf, "yuv420p (8-bit 4:2:0)", "export.py preset re-encodes to yuv420p",
522
+ reason="QuickTime and iOS commonly reject video that isn't 8-bit 4:2:0")
523
+ if spec["sdr_only"] and v.get("bt2020_or_hdr"):
524
+ row("colour", "FAIL", v.get("hdr_format"), "SDR BT.709", "color.py --to-sdr",
525
+ reason="a platform or player without HDR support will show this washed-out, too dark, or with wrong colours -- not a rendering glitch, a colour space mismatch")
526
+ else:
527
+ tags = (v.get("color_primaries"), v.get("color_transfer"))
528
+ untagged = not tags[0] and not tags[1]
529
+ # The matrix (color_space) is a tag too (#325): a player that honours it decodes with it,
530
+ # so a file whose only tag is a BT.601 matrix is BT.601, not "untagged".
531
+ matrix = v.get("color_space")
532
+ matrix_709 = matrix in (None, "bt709")
533
+ shown = (f"{matrix} matrix, primaries/transfer untagged" if untagged and matrix else
534
+ f"{tags[0]}/{tags[1]}" + ("" if matrix in (None, tags[0]) else f", {matrix} matrix"))
535
+ if v.get("bt2020_or_hdr") or (tags == ("bt709", "bt709") and matrix_709) or args.platform in ("podcast", "custom"):
536
+ row("colour", "PASS", f"{tags[0]}/{tags[1]}" + (f" ({v.get('hdr_format')})" if v.get("bt2020_or_hdr") else ""), "bt709/bt709 tagged (or HDR)")
537
+ elif untagged and matrix_709 and (v.get("bit_depth") or 8) == 8:
538
+ # untagged 8-bit video is treated as BT.709 by every player and platform; nothing to fix
539
+ row("colour", "PASS", shown + " (players assume bt709)" if matrix else "untagged (players assume bt709)", "bt709/bt709 tagged (or HDR)")
540
+ elif matrix in ("smpte170m", "bt470bg"):
541
+ # The pixels are BT.601-encoded. A re-encode here converts them to the BT.709 it tags
542
+ # (bt709_matrix_filter); --retag bt709 is a stream copy and only relabels the matrix.
543
+ row("colour", "WARN", shown, "bt709/bt709 tagged (or HDR)",
544
+ "export.py (any re-encode here converts the BT.601 matrix to BT.709); color.py --retag bt709 only relabels it: right only if the pixels really are BT.709",
545
+ reason="a player that honours the BT.601 tag and one that ignores it on HD video (decoding it as BT.709) show different colours")
546
+ else:
547
+ row("colour", "WARN", shown, "bt709/bt709 tagged (or HDR)", "color.py --retag bt709 when the picture really is 709; color.py --to-sdr when it is HDR")
548
+ elif args.platform not in ("podcast", "custom"):
549
+ row("video", "FAIL", "none", "video stream", "")
550
+
551
+ size = meta.get("size_bytes") or 0
552
+ if spec["max_bytes"] and meta.get("size_bytes") is None:
553
+ row("file size", "FAIL", "could not measure", f"<= {spec['max_bytes'] / 1024 / 1024:.0f} MB", "",
554
+ reason="the file's size could not be read, so whether it is within the limit is unknown")
555
+ elif spec["max_bytes"]:
556
+ row("file size", "PASS" if size <= spec["max_bytes"] else "FAIL", f"{size / 1024 / 1024:.1f} MB", f"<= {spec['max_bytes'] / 1024 / 1024:.0f} MB", "export.py --crf 24 or lower resolution")
557
+
558
+ if a:
559
+ row("audio", "PASS", f"{a.get('codec')} {a.get('channels')}ch {a.get('sample_rate')}Hz", "present")
560
+ if args.platform == "podcast":
561
+ # Podcast rows, informational: neither can fail a delivery, both are things a
562
+ # publisher notices after the fact. A 5.1 podcast master is the common one -- every
563
+ # player downmixes it, none of them the same way, and the centre-heavy dialogue
564
+ # comes back at a level nobody checked.
565
+ ch = a.get("channels") or 0
566
+ row("channels", "PASS" if ch in (1, 2) else "WARN", f"{ch}ch", "1 (mono) or 2 (stereo)",
567
+ "audio.py --downmix (5.1/7.1 to stereo with the ITU-R BS.775 weights) or audio.py --mono",
568
+ reason="podcast players downmix 5.1 unpredictably")
569
+ if args.platform == "podcast":
570
+ chapters = meta.get("chapters") or []
571
+ row("chapters", "PASS" if chapters else "WARN", f"{len(chapters)}" if chapters else "none", ">= 1 chapter marker",
572
+ "metadata.py episode.m4a --chapters chapters.txt (`TIME TITLE` per line; streams copied)",
573
+ reason="chapter markers are optional, but a podcast app shows them as the episode's seekable table of contents")
574
+ # Subtitles, informational and on every platform: a soft subtitle track that carries no
575
+ # language tag is the defect caption.py --mode mux's multi-track form exists to prevent -- a
576
+ # player lists it as "Track 2" and a viewer cannot tell which language it is. Never counted in
577
+ # `failed`: no platform refuses a delivery over it.
578
+ subs = meta.get("subtitle_stream_details") or []
579
+ if not subs:
580
+ row("subtitles", "WARN", "none", ">= 1 language-tagged subtitle track",
581
+ "caption.py video.mp4 --mode mux --srt subs.srt:en -o video_subs.mkv (streams are copied)",
582
+ reason="subtitles are optional, but they are the cheapest accessibility win a delivery has")
583
+ else:
584
+ untagged = [str(s["index"]) for s in subs if not s.get("language")]
585
+ listed = ", ".join((s.get("language") or "untagged") for s in subs)
586
+ row("subtitles", "WARN" if untagged else "PASS", f"{len(subs)} ({listed})",
587
+ "every track tagged with its language",
588
+ "caption.py video.mp4 --mode mux --srt subs.srt:en -o video_subs.mkv, or re-mux with `--srt file:lang` per track"
589
+ if untagged else "",
590
+ reason=("stream(s) " + ", ".join(untagged) + " carry no language tag: a player lists them "
591
+ "by number and the viewer has to guess") if untagged else "")
592
+
593
+ if a:
594
+ audio_row = next(r for r in rows if r["check"] == "audio")
595
+
596
+ def silent_audio(peak: float) -> None:
597
+ # a present-but-silent track is the failed-TTS / muted-export case: "present" is not a pass
598
+ # FAIL under a platform with a loudness target (it would fail loudness anyway); WARN
599
+ # otherwise: a muted screen recording or a b-roll clip is a legitimate silent track
600
+ audio_row.update(status="FAIL" if spec["lufs"] is not None else "WARN", value=audio_row["value"] + f", silent (peak {peak:.1f} dB)",
601
+ expected=f"present, peak above {SILENT_PEAK_DBFS:g} dBFS",
602
+ fix="audio.py --replace with the real track, or re-export from the master",
603
+ reason="the audio track exists but carries no sound: viewers hear nothing")
604
+ loudness_ran = False
605
+ if a.get("sample_rate") and a["sample_rate"] not in (44100, 48000):
606
+ row("sample rate", "WARN", a["sample_rate"], "44100 or 48000", "loudness.py --sample-rate 48000")
607
+ # A117: --tp alone (custom has no loudness target) asks for the true-peak row, which
608
+ # needs the same measurement pass; without it the run reported 0 failed having measured nothing
609
+ tp_only = spec["lufs"] is None and args.tp is not None
610
+ if not args.no_loudness and (spec["lufs"] is not None or tp_only):
611
+ lm = measure_loudness(args.input)
612
+ loudness_ran = bool(lm)
613
+ if lm and lm["tp"] <= SILENT_PEAK_DBFS:
614
+ silent_audio(lm["tp"])
615
+ if lm and tp_only:
616
+ row("true peak", "PASS" if lm["tp"] <= spec["tp"] + TP_TOLERANCE_DB else "FAIL", f"{lm['tp']:.1f} dBTP", f"<= {spec['tp']:g} dBTP (+{TP_TOLERANCE_DB:g} dB tolerance)", f"loudness.py --tp {spec['tp']:g}")
617
+ elif not lm and tp_only:
618
+ row("true peak", "WARN", "could not measure", f"<= {spec['tp']:g} dBTP", "re-run check.py, or verify true peak manually",
619
+ reason="ffmpeg's loudness measurement didn't produce a readable result -- this was not actually checked")
620
+ elif (lm and lm["lufs"] == float("-inf") and lm["tp"] > SILENT_PEAK_DBFS
621
+ and shorter_than_a_loudness_block(own_length(a) or dur_read)):
622
+ # A257: shorter than one 400 ms gating block: a true peak but no integrated
623
+ # loudness. Not silence, and not a -inf LUFS that FAILs the target. Decided on
624
+ # the sound's length: a longer track whose every block is under the gate reads
625
+ # -inf too, and that one still FAILs the target below
626
+ row("loudness", "WARN", "could not measure (shorter than one 400 ms loudness block)",
627
+ f"{spec['lufs']:g} ± {spec['lufs_tol']:g} LUFS", "",
628
+ reason="integrated loudness is gated over 400 ms blocks; a clip this short has none")
629
+ row("true peak", "PASS" if lm["tp"] <= spec["tp"] + TP_TOLERANCE_DB else "FAIL", f"{lm['tp']:.1f} dBTP", f"<= {spec['tp']:g} dBTP (+{TP_TOLERANCE_DB:g} dB tolerance)", f"loudness.py --tp {spec['tp']:g}")
630
+ elif lm:
631
+ diff = abs(lm["lufs"] - spec["lufs"])
632
+ row("loudness", "PASS" if diff <= spec["lufs_tol"] else "FAIL", f"{lm['lufs']:.1f} LUFS", f"{spec['lufs']:g} ± {spec['lufs_tol']:g} LUFS", f"loudness.py -I {spec['lufs']:g} for speech or music; leave ambience/near-silence (<= -40 LUFS) alone and say so",
633
+ reason="the platform will auto-normalise it to its own target anyway, which can pump or duck the mix in ways you did not choose")
634
+ row("true peak", "PASS" if lm["tp"] <= spec["tp"] + TP_TOLERANCE_DB else "FAIL", f"{lm['tp']:.1f} dBTP", f"<= {spec['tp']:g} dBTP (+{TP_TOLERANCE_DB:g} dB tolerance)", f"loudness.py --tp {spec['tp']:g}")
635
+ else:
636
+ # ffmpeg's loudnorm JSON didn't parse out of stderr (unexpected/garbled output).
637
+ # Dropping the loudness/true-peak rows silently here would report an overall PASS
638
+ # for a platform that has a loudness requirement, without ever having checked it --
639
+ # a false PASS is worse than noise. WARN so the gap is visible in the report.
640
+ row("loudness", "WARN", "could not measure", f"{spec['lufs']:g} ± {spec['lufs_tol']:g} LUFS", "re-run check.py, or verify loudness manually",
641
+ reason="ffmpeg's loudness measurement didn't produce a readable result -- this was not actually checked")
642
+ row("true peak", "WARN", "could not measure", f"<= {spec['tp']:g} dBTP", "re-run check.py, or verify true peak manually")
643
+ if not loudness_ran and not dry_run_input_pending(args.input):
644
+ # loudness skipped (--no-loudness, or a spec with no target): one cheap volumedetect pass
645
+ lv = measured_level_dbfs(args.input, seconds=None)
646
+ if lv and lv["peak_dbfs"] <= SILENT_PEAK_DBFS:
647
+ silent_audio(lv["peak_dbfs"])
648
+ elif args.platform in ("podcast",):
649
+ row("audio", "FAIL", "none", "audio stream", "audio.py --replace")
650
+ else:
651
+ row("audio", "WARN", "none", "audio stream", "audio.py --replace (silent uploads are often rejected)")
652
+
653
+ if args.content:
654
+ cd = detect_content(args.input, dur, video=bool(v), audio=bool(a))
655
+ span = dur if dur > 0 else 0.0
656
+ if not span and not dry_run_input_pending(args.input):
657
+ # A113: black, frozen and silence are shares of the running time; with no length
658
+ # read there is nothing to divide by, and dropping the rows read as nothing to report
659
+ for name, stream in (("black", v), ("frozen", v), ("silence", a)):
660
+ if stream:
661
+ row(name, "WARN", "could not measure", "a share of the running time",
662
+ "remux the file (export.py --preset copy) so the container states its length, then check again",
663
+ reason="the file does not state its length, so this share of it could not be worked out")
664
+ if "black" in cd and span:
665
+ share = _span_total(cd["black"]) / span
666
+ row("black", "FAIL" if share >= BLACK_FAIL else ("WARN" if share > BLACK_WARN else "PASS"),
667
+ f"{share * 100:.0f}% black", f"<= {BLACK_WARN * 100:.0f}% black",
668
+ "look.py the black spans; trim them with cut.py or re-export from the master",
669
+ reason="an all-black or mostly black picture is usually a failed render or a missing clip")
670
+ if "frozen" in cd and span:
671
+ longest = max((e - s for s, e in cd["frozen"]), default=0.0)
672
+ limit = max(FROZEN_WARN_S, FROZEN_WARN_SHARE * span)
673
+ row("frozen", "FAIL" if longest >= FROZEN_FAIL * span else ("WARN" if longest > limit else "PASS"),
674
+ f"longest {longest:.1f}s", f"<= {limit:.1f}s frozen",
675
+ "look.py the frozen span: a still title card is fine, a stuck decode is not",
676
+ reason="a picture that never changes is usually a stuck frame, not the edit")
677
+ if v and not dry_run_input_pending(args.input): # a plan's not-yet-written input: no rows, as above
678
+ first = first_frame_stats(args.input)
679
+ if first is None:
680
+ row("first frame", "WARN", "could not measure", f"spread >= {CONTENT_FLAT_STD:g} (not one flat colour)",
681
+ "look.py the first frame", reason="the first frame did not decode, so whether it is flat is unknown")
682
+ else:
683
+ mean, spread = first
684
+ flat = spread < CONTENT_FLAT_STD
685
+ row("first frame", "WARN" if flat else "PASS", f"luma {mean:.0f}, spread {spread:.1f}",
686
+ f"spread >= {CONTENT_FLAT_STD:g} (not one flat colour)",
687
+ "a fade from black is a choice; where autoplay or the preview shows the first frame, start on "
688
+ "a picture (cut.py --start a few frames in, or move a title card to frame 0)" if flat else "",
689
+ reason="a feed shows the first frame before anything plays, and a flat one reads as a broken upload" if flat else "")
690
+ flashes = detect_flashes(args.input)
691
+ pts = presentation_times(args.input, float(v.get("start_time") or 0.0)) if flashes else None
692
+ at = flash_times(flashes or [], v, meta, pts)
693
+ if flashes is None:
694
+ row("flashes", "WARN", "could not measure", "no single frame unlike both its neighbours",
695
+ "look.py the video: no frame decoded, so nothing was compared",
696
+ reason="the video did not decode, so whether it has flashes is unknown")
697
+ else:
698
+ row("flashes", "WARN" if flashes else "PASS", f"{len(flashes)}" + (f": {at}" if flashes else ""),
699
+ "no single frame unlike both its neighbours",
700
+ "look.py at those times: a stray frame at a cut or join is an edit error (re-cut with cut.py "
701
+ "--accurate, or join.py again); a camera flash or a strobe in the footage is fine" if flashes else "",
702
+ reason="one frame that matches neither neighbour is usually a frame left over at a cut, or a decode glitch" if flashes else "")
703
+ if "silence" in cd and span:
704
+ share = _span_total(cd["silence"]) / span
705
+ row("silence", "FAIL" if share >= SILENCE_FAIL else ("WARN" if share > SILENCE_WARN else "PASS"),
706
+ f"{share * 100:.0f}% silent", f"<= {SILENCE_WARN * 100:.0f}% below {SILENT_PEAK_DBFS:g} dBFS",
707
+ "silence.py to cut the gaps, or audio.py --replace when the track is empty",
708
+ reason="most of the running time has no audible sound")
709
+ if "dropouts" in cd:
710
+ gaps = cd["dropouts"]
711
+ at = ", ".join(f"{s:.2f}s ({(e - s) * 1000:.0f} ms)" for s, e in gaps[:5]) + (" ..." if len(gaps) > 5 else "")
712
+ row("dropouts", "WARN" if gaps else "PASS", f"{len(gaps)}" + (f": {at}" if gaps else ""),
713
+ "no digital-silence gap under 1 s with sound on both sides",
714
+ "listen at those times: a gap at a cut or join is lost audio (re-cut with cut.py --accurate, or join.py "
715
+ "again); a noise gate makes these on purpose" if gaps else "",
716
+ reason="a short stretch of digital silence in the middle of the sound is usually lost audio at a join or a glitched decode" if gaps else "")
717
+
718
+ levels_doc = None
719
+ if args.levels and not dry_run_input_pending(args.input):
720
+ levels_doc = levels_row(args, v, row)
721
+
722
+ if args.compare and not dry_run_input_pending(args.input) and not dry_run_input_pending(args.compare):
723
+ ref = probe(args.compare)
724
+ rv = ref.get("video") or {}
725
+ if not v or not rv:
726
+ row("similarity", "WARN", "not compared", "two pictures", "--compare needs a video stream in both files",
727
+ reason="one of the files has no picture")
728
+ elif display_size(v) != display_size(rv):
729
+ row("similarity", "WARN", "not compared: %dx%d vs %dx%d (as displayed)" % (display_size(v) + display_size(rv)),
730
+ "the same frame size", "compare against a reference at the delivery size (fit.py or export.py it first)",
731
+ reason="SSIM and PSNR compare pixels, so the two frames must be the same size")
732
+ else:
733
+ cmp_ = compare_pictures(args.input, args.compare)
734
+ if cmp_ is None:
735
+ row("similarity", "WARN", "could not measure", f"mean SSIM >= {COMPARE_SSIM_WARN:g}",
736
+ "look.py --compare at a few times", reason="the comparison pass failed")
737
+ else:
738
+ pts = presentation_times(args.input, float(v.get("start_time") or 0.0))
739
+ at = frame_time(cmp_["worst_frame"], v, meta, pts)
740
+ seek = "0" if at.startswith("frame") else at.lstrip("~").rstrip("s")
741
+ psnr = "identical" if cmp_["psnr"] == float("inf") else (f"{cmp_['psnr']:.1f} dB" if cmp_["psnr"] is not None else "?")
742
+ low = cmp_["ssim"] < COMPARE_SSIM_WARN
743
+ row("similarity", "WARN" if low else "PASS",
744
+ f"SSIM {cmp_['ssim']:.4f} (worst {cmp_['worst_ssim']:.4f} at {at}), PSNR {psnr}, {cmp_['frames']} frames",
745
+ f"mean SSIM >= {COMPARE_SSIM_WARN:g}",
746
+ f"look.py --compare {args.compare} --at {seek}" if low else "",
747
+ reason="the picture differs visibly from the reference somewhere" if low else "")
748
+ # frames counted from the packets when a container does not state nb_frames
749
+ nout = v.get("nb_frames") or len(pts) or None
750
+ nref = rv.get("nb_frames") or len(presentation_times(args.compare, float(rv.get("start_time") or 0.0))) or None
751
+ if nref and nout and int(nref) != int(nout):
752
+ STATE_NOTES.append(f"--compare: {nout} frames against the reference's {nref}; frames were paired in "
753
+ f"order, so an added or dropped frame shifts every later pair, and only the "
754
+ f"first {min(int(nref), int(nout))} were compared")
755
+ scope_doc = None
756
+ if declared_changes is not None and not dry_run_input_pending(args.input) and not dry_run_input_pending(args.compare):
757
+ scope_doc = change_scope_row(args, declared_changes, meta, v, row)
758
+ # read after every measurement, --compare's included, so a replacement at any point shows
759
+ identity = None if dry_run_input_pending(args.input) else file_identity(args.input)
760
+ if identity is not None and identity != identity_before and expected_identity is None:
761
+ STATE_NOTES.append("the file changed while it was being checked: input_identity is the file as it was "
762
+ "at the end, and the rows may describe an earlier one; check it again")
763
+ if expected_identity is not None:
764
+ size, mtime_ns = expected_identity["size"], expected_identity["mtime_ns"]
765
+ if identity is not None:
766
+ changed = identity != identity_before
767
+ same = identity == {"size": size, "mtime_ns": mtime_ns} and not changed
768
+ row("identity", "PASS" if same else "FAIL", f"{identity['size']}:{identity['mtime_ns']}", f"{size}:{mtime_ns}",
769
+ "" if same else "re-run the tool that writes this file and check what it reports, not what the path holds",
770
+ reason="" if same else ("the file changed while it was being checked" if changed
771
+ else "the file at this path is not the one the run being checked wrote"))
772
+ elif not dry_run_input_pending(args.input):
773
+ row("identity", "FAIL", "no regular file at this path", f"{size}:{mtime_ns}",
774
+ "re-run the tool that writes this file and check what it reports, not what the path holds",
775
+ reason="the file at this path is not the one the run being checked wrote")
776
+ failed = [r for r in rows if r["status"] == "FAIL"]
777
+ warned = [r for r in rows if r["status"] == "WARN"]
778
+ notes: List[str] = []
779
+ if not named:
780
+ notes.append("no --platform given: youtube's spec was assumed, so judgement rows (duration, aspect, fps, resolution, loudness, true peak) are WARN, not FAIL; name a platform to enforce them")
781
+ notes += STATE_NOTES
782
+ if not args.json:
783
+ width = max(len(r["check"]) for r in rows)
784
+ print(f"{args.input} — {args.platform}" + ("" if named else " (assumed)"))
785
+ for r in rows:
786
+ line = f" {r['status']:4s} {r['check']:{width}s} {r['value']} (expected {r['expected']})"
787
+ if r["status"] != "PASS" and r["kind"] == "judgement":
788
+ line += " [judgement]"
789
+ if r["status"] != "PASS" and r["basis"] == "guidance":
790
+ line += " [guidance]"
791
+ if r["status"] != "PASS" and r["reason"]:
792
+ line += f" ({r['reason']})"
793
+ if r["status"] != "PASS" and r["fix"]:
794
+ line += f" -> {r['fix']}"
795
+ print(line)
796
+ print(f" {len(rows)} checks, {len(failed)} failed, {len(warned)} warnings")
797
+ for n in notes:
798
+ print(f" note: {n}")
799
+ extra: Dict[str, Any] = {"notes": notes} if notes else {}
800
+ if levels_doc is not None:
801
+ extra["levels"] = levels_doc
802
+ if scope_doc is not None:
803
+ extra["change_scope"] = scope_doc
804
+ if identity is not None:
805
+ extra["input_identity"] = identity
806
+ if failed:
807
+ die(f"{len(failed)} of {len(rows)} {args.platform} checks failed: {', '.join(r['check'] for r in failed)}",
808
+ kind="verification", output=None, dry_run=STATE.dry_run,
809
+ platform=args.platform, checks=rows, failed=len(failed), warnings=len(warned), ok=False, **extra)
810
+ emit(None, platform=args.platform, checks=rows, failed=len(failed), warnings=len(warned), ok=True, **extra)
811
+ return 0
812
+
813
+
814
+ if __name__ == "__main__":
815
+ sys.exit(main())