streamprobe 0.3.1__py3-none-any.whl

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.
@@ -0,0 +1,5 @@
1
+ """StreamProbe: local capture, server-side live stream analysis."""
2
+
3
+ from streamprobe.version import VERSION as __version__
4
+
5
+ __all__ = ["__version__"]
@@ -0,0 +1,4 @@
1
+ from streamprobe.cli import main
2
+
3
+ if __name__ == "__main__":
4
+ main(prog_name="streamprobe")
streamprobe/analyze.py ADDED
@@ -0,0 +1,459 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ from streamprobe import metrics, parsers
8
+ from streamprobe.config import Settings
9
+ from streamprobe.errors import AnalysisError
10
+ from streamprobe.media import CommandResult, ffprobe_json, run_command
11
+
12
+ ProgressFn = Callable[[str, dict[str, Any]], None]
13
+
14
+
15
+ def _ffmpeg_base(settings: Settings) -> list[str]:
16
+ return [
17
+ settings.ffmpeg_path,
18
+ "-nostdin",
19
+ "-hide_banner",
20
+ "-y",
21
+ "-threads",
22
+ "2",
23
+ "-filter_threads",
24
+ "2",
25
+ ]
26
+
27
+
28
+ def _audio_loudness_pass(
29
+ path: Path, duration: float, workdir: Path, settings: Settings
30
+ ) -> tuple[CommandResult, dict[str, Any]]:
31
+ metadata_path = workdir / "loudness.txt"
32
+ if metadata_path.exists():
33
+ metadata_path.unlink()
34
+ args = [
35
+ *_ffmpeg_base(settings),
36
+ "-loglevel",
37
+ "error",
38
+ "-protocol_whitelist",
39
+ "file,pipe",
40
+ "-i",
41
+ str(path),
42
+ "-map",
43
+ "0:a:0",
44
+ "-vn",
45
+ "-af",
46
+ f"ebur128=peak=true:metadata=1,ametadata=mode=print:file={metadata_path}",
47
+ "-t",
48
+ f"{duration:.3f}",
49
+ "-f",
50
+ "null",
51
+ "-",
52
+ ]
53
+ result = run_command(args, timeout=120)
54
+ return result, parsers.parse_loudness(metadata_path)
55
+
56
+
57
+ def _audio_stats_pass(
58
+ path: Path, duration: float, settings: Settings
59
+ ) -> tuple[CommandResult, dict[str, Any], list[dict[str, float]]]:
60
+ args = [
61
+ *_ffmpeg_base(settings),
62
+ "-loglevel",
63
+ "info",
64
+ "-protocol_whitelist",
65
+ "file,pipe",
66
+ "-i",
67
+ str(path),
68
+ "-map",
69
+ "0:a:0",
70
+ "-vn",
71
+ "-af",
72
+ (
73
+ "silencedetect=n=-45dB:d=1.0,"
74
+ "astats=metadata=0:reset=0:"
75
+ "measure_perchannel=Peak_level+RMS_level+Peak_count+Abs_Peak_count+Flat_factor:"
76
+ "measure_overall=Peak_level+RMS_level+Peak_count+Abs_Peak_count+Flat_factor"
77
+ ),
78
+ "-t",
79
+ f"{duration:.3f}",
80
+ "-f",
81
+ "null",
82
+ "-",
83
+ ]
84
+ result = run_command(args, timeout=120)
85
+ return result, parsers.parse_astats(result.stderr), parsers.parse_silences(result.stderr, duration)
86
+
87
+
88
+ def _video_pass(
89
+ path: Path, duration: float, workdir: Path, settings: Settings
90
+ ) -> tuple[CommandResult, dict[str, Any], list[dict[str, float]]]:
91
+ metadata_path = workdir / "video.txt"
92
+ if metadata_path.exists():
93
+ metadata_path.unlink()
94
+ filter_graph = (
95
+ "[0:v:0]split=2[det][br];"
96
+ "[det]freezedetect=n=0.001:d=2,blackdetect=d=0.5:pix_th=0.10,showinfo[vout];"
97
+ f"[br]fps=2,scale=320:-2,signalstats,metadata=mode=print:key=lavfi.signalstats.YAVG:file={metadata_path}[bout]"
98
+ )
99
+ args = [
100
+ *_ffmpeg_base(settings),
101
+ "-loglevel",
102
+ "info",
103
+ "-protocol_whitelist",
104
+ "file,pipe",
105
+ "-i",
106
+ str(path),
107
+ "-filter_complex",
108
+ filter_graph,
109
+ "-map",
110
+ "[vout]",
111
+ "-map",
112
+ "[bout]",
113
+ "-t",
114
+ f"{duration:.3f}",
115
+ "-an",
116
+ "-f",
117
+ "null",
118
+ "-",
119
+ ]
120
+ result = run_command(args, timeout=150)
121
+ events = parsers.parse_video_events(result.stderr, duration)
122
+ brightness = parsers.parse_video_metadata(metadata_path)
123
+ return result, events, brightness
124
+
125
+
126
+ def _thumbnail(path: Path, t: float, out: Path, settings: Settings, from_end: bool = False) -> bool:
127
+ seek = ["-sseof", "-1.0"] if from_end else ["-ss", f"{max(0.0, t):.3f}"]
128
+ args = [
129
+ *_ffmpeg_base(settings),
130
+ "-loglevel",
131
+ "error",
132
+ *seek,
133
+ "-protocol_whitelist",
134
+ "file,pipe",
135
+ "-i",
136
+ str(path),
137
+ "-frames:v",
138
+ "1",
139
+ "-vf",
140
+ "scale=640:-2",
141
+ "-q:v",
142
+ "3",
143
+ str(out),
144
+ ]
145
+ result = run_command(args, timeout=40)
146
+ return result.returncode == 0 and out.exists() and out.stat().st_size > 1000
147
+
148
+
149
+ def _waveform(path: Path, out: Path, settings: Settings) -> bool:
150
+ args = [
151
+ *_ffmpeg_base(settings),
152
+ "-loglevel",
153
+ "error",
154
+ "-protocol_whitelist",
155
+ "file,pipe",
156
+ "-i",
157
+ str(path),
158
+ "-filter_complex",
159
+ "showwavespic=s=1200x240:split_channels=1:colors=0x6EA8FF|0x3DE0A0:filter=peak",
160
+ "-frames:v",
161
+ "1",
162
+ str(out),
163
+ ]
164
+ result = run_command(args, timeout=60)
165
+ return result.returncode == 0 and out.exists() and out.stat().st_size > 1000
166
+
167
+
168
+ def _spectrogram(path: Path, duration: float, out: Path, settings: Settings) -> bool:
169
+ args = [
170
+ *_ffmpeg_base(settings),
171
+ "-loglevel",
172
+ "error",
173
+ "-protocol_whitelist",
174
+ "file,pipe",
175
+ "-i",
176
+ str(path),
177
+ "-t",
178
+ f"{min(30.0, duration):.3f}",
179
+ "-filter_complex",
180
+ "showspectrumpic=s=1200x360:legend=1:scale=log:fscale=log",
181
+ "-frames:v",
182
+ "1",
183
+ str(out),
184
+ ]
185
+ result = run_command(args, timeout=90)
186
+ return result.returncode == 0 and out.exists() and out.stat().st_size > 1000
187
+
188
+
189
+ _PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
190
+ _JPEG_SIGNATURE = b"\xff\xd8\xff"
191
+
192
+
193
+ def image_size(path: Path) -> tuple[int, int] | None:
194
+ try:
195
+ data = path.read_bytes()[:32]
196
+ except OSError:
197
+ return None
198
+ if data.startswith(_PNG_SIGNATURE) and len(data) >= 24:
199
+ return (int.from_bytes(data[16:20], "big"), int.from_bytes(data[20:24], "big"))
200
+ if data.startswith(_JPEG_SIGNATURE):
201
+ return (0, 0)
202
+ return None
203
+
204
+
205
+ def _safe_asset(path: Path, assets_dir: Path, name: str) -> str | None:
206
+ if not path.exists() or path.stat().st_size < 1000:
207
+ path.unlink(missing_ok=True)
208
+ return None
209
+ if image_size(path) is None:
210
+ path.unlink(missing_ok=True)
211
+ return None
212
+ final = assets_dir / name
213
+ final.parent.mkdir(parents=True, exist_ok=True)
214
+ if path != final:
215
+ path.replace(final)
216
+ return name
217
+
218
+
219
+ def analyze_media(
220
+ path: Path,
221
+ duration: float,
222
+ workdir: Path,
223
+ assets_dir: Path,
224
+ settings: Settings,
225
+ progress: ProgressFn | None = None,
226
+ ) -> dict[str, Any]:
227
+ warnings: list[str] = []
228
+ partial = False
229
+ assets_dir.mkdir(parents=True, exist_ok=True)
230
+
231
+ if progress:
232
+ progress("analyzing_video", {"detail": "probing container"})
233
+ probe = ffprobe_json(path, ["-show_format", "-show_streams"], settings)
234
+ parsed = parsers.parse_container(probe)
235
+ video_info = parsed["video"]
236
+ audio_info = parsed["audio"]
237
+
238
+ video_packets: list[dict[str, Any]] = []
239
+ video_frames: list[dict[str, Any]] = []
240
+ audio_packets: list[dict[str, Any]] = []
241
+ if video_info:
242
+ try:
243
+ video_packets = parsers.parse_packets(
244
+ ffprobe_json(
245
+ path,
246
+ [
247
+ "-select_streams",
248
+ "v:0",
249
+ "-show_packets",
250
+ "-show_entries",
251
+ "packet=stream_index,pts_time,dts_time,duration_time,size,flags",
252
+ ],
253
+ settings,
254
+ )
255
+ )
256
+ video_frames = parsers.parse_frames(
257
+ ffprobe_json(
258
+ path,
259
+ [
260
+ "-select_streams",
261
+ "v:0",
262
+ "-show_frames",
263
+ "-show_entries",
264
+ "frame=best_effort_timestamp_time,pts_time,duration_time,key_frame,pict_type",
265
+ ],
266
+ settings,
267
+ )
268
+ )
269
+ except AnalysisError as exc:
270
+ warnings.append(f"video packets/frames unavailable: {exc.code}")
271
+ partial = True
272
+ if audio_info:
273
+ try:
274
+ audio_packets = parsers.parse_packets(
275
+ ffprobe_json(
276
+ path,
277
+ [
278
+ "-select_streams",
279
+ "a:0",
280
+ "-show_packets",
281
+ "-show_entries",
282
+ "packet=stream_index,pts_time,dts_time,duration_time,size,flags",
283
+ ],
284
+ settings,
285
+ )
286
+ )
287
+ except AnalysisError as exc:
288
+ warnings.append(f"audio packets unavailable: {exc.code}")
289
+ partial = True
290
+
291
+ video_base = metrics.first_dts(video_packets)
292
+ audio_base = metrics.first_dts(audio_packets)
293
+ bases = [value for value in (video_base, audio_base) if value is not None]
294
+ chart_base = min(bases) if bases else 0.0
295
+ video_offset = max(0.0, (video_base - chart_base)) if video_base is not None else 0.0
296
+ audio_offset = max(0.0, (audio_base - chart_base)) if audio_base is not None else 0.0
297
+
298
+ video: dict[str, Any] | None = None
299
+ if video_info:
300
+ nominal = video_info.get("fpsNominal")
301
+ frame_stats = metrics.frame_stats(video_frames, nominal)
302
+ kf = metrics.keyframe_stats(video_frames)
303
+ video_br_series = metrics.build_bitrate_series(video_packets, chart_base, duration)
304
+ video_br = metrics.bitrate_stats(video_br_series, duration)
305
+ events: dict[str, Any] = {"freezes": [], "blacks": [], "resolutions": [], "lastFrameTime": None}
306
+ brightness: list[dict[str, float]] = []
307
+ if progress:
308
+ progress("analyzing_video", {"detail": "freeze / black / brightness"})
309
+ try:
310
+ result, events, brightness = _video_pass(path, duration, workdir, settings)
311
+ if result.timed_out:
312
+ warnings.append("video filter pass timed out")
313
+ partial = True
314
+ except AnalysisError as exc:
315
+ warnings.append(f"video filter pass failed: {exc.code}")
316
+ partial = True
317
+
318
+ def shifted(items: list[dict[str, float]]) -> list[dict[str, float]]:
319
+ return [
320
+ {
321
+ **item,
322
+ "start": round(item["start"] + video_offset, 2),
323
+ "end": round(item["end"] + video_offset, 2),
324
+ }
325
+ for item in items
326
+ ]
327
+
328
+ brightness = [
329
+ {"t": round(point["t"] + video_offset, 2), "yavg": point["yavg"]} for point in brightness
330
+ ]
331
+ resolutions = [
332
+ {"t": round(item["t"] + video_offset, 2), "size": item["size"]}
333
+ for item in events.get("resolutions", [])
334
+ ]
335
+ thumbs: list[str] = []
336
+ if progress:
337
+ progress("analyzing_video", {"detail": "thumbnails"})
338
+ for index, t in enumerate((0.5, duration / 2, max(0.5, duration - 1.0))):
339
+ out = workdir / f"thumb-{index}.jpg"
340
+ if _thumbnail(path, t, out, settings, from_end=index == 2):
341
+ name = _safe_asset(out, assets_dir, f"thumb-{index}.jpg")
342
+ if name:
343
+ thumbs.append(name)
344
+ video = {
345
+ **video_info,
346
+ "fpsActual": frame_stats["fpsActual"],
347
+ "vfr": frame_stats["vfr"],
348
+ "frameIntervalMedian": frame_stats["frameIntervalMedian"],
349
+ "framesAnalyzed": frame_stats["framesAnalyzed"],
350
+ "gaps": frame_stats["gaps"],
351
+ "keyframeCount": kf["count"],
352
+ "keyframeIntervalSec": kf["intervalMedian"],
353
+ "keyframeIntervalMaxSec": kf["intervalMax"],
354
+ "avgBitrateKbps": video_br["avgKbps"],
355
+ "peakBitrateKbps": video_br["peakKbps"],
356
+ "bitrateCv": video_br["cv"],
357
+ "bitrateSeries": video_br_series,
358
+ "fpsSeries": metrics.build_fps_series(video_frames, chart_base, duration),
359
+ "freezes": shifted(events.get("freezes", [])),
360
+ "blackFrames": shifted(events.get("blacks", [])),
361
+ "brightnessSeries": brightness,
362
+ "resolutions": resolutions,
363
+ "thumbs": thumbs,
364
+ }
365
+
366
+ audio: dict[str, Any] | None = None
367
+ if audio_info:
368
+ if progress:
369
+ progress("analyzing_audio", {"detail": "loudness"})
370
+ loudness_result, loudness = _audio_loudness_pass(path, duration, workdir, settings)
371
+ if loudness_result.timed_out:
372
+ warnings.append("loudness pass timed out")
373
+ partial = True
374
+ if progress:
375
+ progress("analyzing_audio", {"detail": "silence / channel stats"})
376
+ stats_result, astats, silences = _audio_stats_pass(path, duration, settings)
377
+ if stats_result.timed_out:
378
+ warnings.append("audio stats pass timed out")
379
+ partial = True
380
+ if not astats.get("complete"):
381
+ warnings.append("astats did not reach EOF")
382
+ partial = True
383
+ loudness_series = [
384
+ {"t": round(item["t"] + audio_offset, 2), "m": item["m"], "s": item["s"]}
385
+ for item in loudness.get("series", [])
386
+ ]
387
+ silences_shifted = [
388
+ {
389
+ "start": round(item["start"] + audio_offset, 2),
390
+ "end": round(item["end"] + audio_offset, 2),
391
+ "duration": item["duration"],
392
+ }
393
+ for item in silences
394
+ ]
395
+ audio_bitrate_series = metrics.build_bitrate_series(audio_packets, chart_base, duration)
396
+ audio_bitrate = metrics.bitrate_stats(audio_bitrate_series, duration)
397
+ per_channel = [
398
+ {
399
+ "channel": item.get("channel"),
400
+ "rmsDb": item.get("rmsLevelDb"),
401
+ "peakDb": item.get("peakLevelDb"),
402
+ "flatFactor": item.get("flatFactor"),
403
+ "peakCount": item.get("peakCount"),
404
+ }
405
+ for item in astats.get("channels", [])
406
+ ]
407
+ overall = astats.get("overall", {})
408
+ waveform = None
409
+ spectrogram = None
410
+ if progress:
411
+ progress("analyzing_audio", {"detail": "waveform / spectrogram"})
412
+ wave_path = workdir / "waveform.png"
413
+ if _waveform(path, wave_path, settings):
414
+ waveform = _safe_asset(wave_path, assets_dir, "waveform.png")
415
+ spec_path = workdir / "spectrogram.png"
416
+ if _spectrogram(path, duration, spec_path, settings):
417
+ spectrogram = _safe_asset(spec_path, assets_dir, "spectrogram.png")
418
+ audio = {
419
+ **audio_info,
420
+ "partial": partial,
421
+ "integratedLufs": loudness.get("integrated"),
422
+ "lra": loudness.get("lra"),
423
+ "truePeakDbtp": loudness.get("truePeakDbtp"),
424
+ "samplePeakDbfs": overall.get("peakLevelDb"),
425
+ "warmupExcludedMs": loudness.get("warmupMs"),
426
+ "clippingSamples": None,
427
+ "loudnessSeries": loudness_series,
428
+ "silences": silences_shifted,
429
+ "silenceTotalSec": metrics.silence_total(silences_shifted),
430
+ "perChannel": per_channel,
431
+ "flatFactor": overall.get("flatFactor"),
432
+ "bitrateSeries": audio_bitrate_series,
433
+ "avgBitrateKbps": audio_bitrate["avgKbps"],
434
+ "peakBitrateKbps": audio_bitrate["peakKbps"],
435
+ "waveform": waveform,
436
+ "spectrogram": spectrogram,
437
+ }
438
+
439
+ av_offset = metrics.av_offset_ms(video_packets, audio_packets)
440
+ video_jumps = metrics.jumps(video_packets, 0.5)
441
+ audio_jumps = metrics.jumps(audio_packets, 0.5)
442
+ sync = {
443
+ "avStartOffsetMs": av_offset,
444
+ "confidence": "low",
445
+ "videoJumps": video_jumps["count"],
446
+ "audioJumps": audio_jumps["count"],
447
+ "videoJumpEvents": video_jumps["events"],
448
+ "audioJumpEvents": audio_jumps["events"],
449
+ }
450
+ if progress:
451
+ progress("analyzing_video", {"detail": "complete"})
452
+ return {
453
+ "container": parsed["container"],
454
+ "video": video or {"present": False},
455
+ "audio": audio or {"present": False, "partial": False},
456
+ "sync": sync,
457
+ "partial": partial,
458
+ "warnings": warnings,
459
+ }