Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- Probe completion uses reliable processed media time as well as wall-clock
runtime, with successful FFmpeg exit and usable measurements required for
accelerated probes. Profiles expose **Minimum Probe Completion (%)** under
**Settings -> Profiles -> Edit profile -> Stream Checking**, defaulting to
80%. Setting 0 disables only the duration rule; probe errors and enabled
blank/freeze checks still apply. Suggested by
[@teffi71](https://github.com/teffi71) in
[#544](https://github.com/krinkuto11/streamflow/issues/544).

- Single-channel changelog entries show the channel name in the card heading
and open their full stream measurements in one click. This also applies to
historical and manual checks; Teamarr Preflight keeps its reuse summary and
Expand Down
4 changes: 4 additions & 0 deletions backend/apps/automation/automation_config_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,8 +298,12 @@ def _normalize_profile_settings(self, extra_settings: Any) -> Dict[str, Any]:
extra = dict(self._normalize_extra_settings(extra_settings))
checking = extra.get('stream_checking')
if isinstance(checking, dict):
from apps.core.probe_completion import normalize_minimum_probe_completion_percent
extra['stream_checking'] = {
**checking,
'minimum_probe_completion_percent': normalize_minimum_probe_completion_percent(
checking.get('minimum_probe_completion_percent', 80),
),
'provider_stream_limit': self._coerce_non_negative_int(
checking.get('provider_stream_limit', 0),
),
Expand Down
89 changes: 89 additions & 0 deletions backend/apps/core/probe_completion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
"""Shared duration policy for probe retries and final stream classification."""

import math

DEFAULT_MINIMUM_PROBE_COMPLETION_PERCENT = 80


def _finite(value):
if isinstance(value, bool):
return None
try:
number = float(value)
except (TypeError, ValueError, OverflowError):
return None
return number if math.isfinite(number) else None


def normalize_minimum_probe_completion_percent(value):
number = _finite(value)
if number is None or not 0 <= number <= 100:
return DEFAULT_MINIMUM_PROBE_COMPLETION_PERCENT
return number


def media_window_seconds(progress_times, requested_seconds):
"""Accept bounded, continuous output progress, not an isolated timestamp.

Large initial offsets, jumps, backwards time and implausible overruns cannot
prove media coverage. Such inputs retain the wall-clock duration fallback.
"""
expected = _finite(requested_seconds)
times = [_finite(value) for value in progress_times]
if expected is None or expected <= 0 or len(times) < 2 or None in times:
return None
if times[0] < 0 or times[0] > min(5, expected * 0.2):
return None
if times[-1] > expected + max(2, expected * 0.1):
return None
for previous, current in zip(times, times[1:]):
if current < previous or current - previous > max(5, expected * 0.25):
return None
span = times[-1] - times[0]
return span if span > 0 else None


def probe_exit_failed(data):
code = data.get('ffmpeg_exit_code')
return data.get('ffmpeg_error_detected') is True or (
code is not None and _finite(code) != 0
)


def probe_window_completion(data, minimum_percent=None):
"""Return (complete, basis); missing legacy timing keeps its old behavior."""
if probe_exit_failed(data) or str(data.get('status') or '').lower() in {
'error', 'failed', 'timeout', 'stream_timeout', 'probe_timeout',
}:
return False, 'ffmpeg_error'
if minimum_percent is None:
minimum_percent = data.get('minimum_probe_completion_percent', 80)
percent = normalize_minimum_probe_completion_percent(minimum_percent)
if percent == 0:
return True, 'duration_check_disabled'

expected_raw = data.get('ffmpeg_duration', data.get('ffmpeg_duration_seconds'))
elapsed_raw = data.get('elapsed_time')
if expected_raw is None or elapsed_raw is None:
return True, 'legacy_without_timing'
expected, elapsed = _finite(expected_raw), _finite(elapsed_raw)
if expected is None or elapsed is None or elapsed < 0:
return False, 'invalid_timing'
if expected <= 0:
return True, 'legacy_without_timing'
required = expected * percent / 100
if elapsed >= required:
return True, 'wall_clock'

media = _finite(data.get('probe_media_seconds'))
# Media-time acceptance requires an explicitly successful FFmpeg process
# plus usable measurements; metadata from failed/partial probes cannot win.
width, _, height = str(data.get('resolution') or '').partition('x')
metrics = [_finite(value) for value in (
width, height, data.get('fps'), data.get('bitrate_kbps'),
)]
if (data.get('ffmpeg_exit_code') == 0 and media is not None
and required <= media <= expected + max(2, expected * 0.1)
and all(value is not None and value > 0 for value in metrics)):
return True, 'media_time'
return False, 'incomplete_window'
27 changes: 17 additions & 10 deletions backend/apps/core/stream_stats_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -547,20 +547,27 @@ def is_stream_dead(stream_data: Dict[str, Any], config: Dict[str, Any] = None) -
_analysis_failure_context(stream_data),
)

EARLY_EXIT_THRESHOLD = 0.8
elapsed = stream_data.get('elapsed_time')
expected = stream_data.get('ffmpeg_duration')
if (
elapsed is not None
and expected is not None
and expected > 0
and elapsed < expected * EARLY_EXIT_THRESHOLD
):
from apps.core.probe_completion import probe_exit_failed, probe_window_completion
if probe_exit_failed(stream_data):
return DeadStreamResult(True, 'offline', 'error', _analysis_failure_context(stream_data))
completed, basis = probe_window_completion(
stream_data, (config or {}).get('minimum_probe_completion_percent'),
)
if not completed:
return DeadStreamResult(
True,
'unstable',
'probe_exited_early',
{'actual_seconds': elapsed, 'expected_seconds': expected},
{
'actual_seconds': stream_data.get('elapsed_time'),
'expected_seconds': stream_data.get('ffmpeg_duration'),
'media_seconds': stream_data.get('probe_media_seconds'),
'minimum_completion_percent': (config or {}).get(
'minimum_probe_completion_percent',
stream_data.get('minimum_probe_completion_percent', 80),
),
'completion_basis': basis,
},
)

stream_stats = stream_data.get('stream_stats')
Expand Down
3 changes: 3 additions & 0 deletions backend/apps/stream/checker/bitrate_progress.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ def recheck_bitrate_stream(stream, _initial):
capacity_transition_lock=stream_statuses_lock,
probe_slots=getattr(self, '_preflight_probe_slots', None),
ffmpeg_duration=analysis_params.get('ffmpeg_duration', 30),
minimum_probe_completion_percent=_threshold_config.get(
'minimum_probe_completion_percent', 80,
),
timeout=analysis_params.get('timeout', 30),
retries=0,
retry_delay=0,
Expand Down
9 changes: 9 additions & 0 deletions backend/apps/stream/checker/classification.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ def _build_threshold_config_from_profile(self, stream_checking: Dict[str, Any])
second argument. Only non-zero thresholds are included.
"""
config: Dict[str, Any] = {}
from apps.core.probe_completion import normalize_minimum_probe_completion_percent
config['minimum_probe_completion_percent'] = normalize_minimum_probe_completion_percent(
stream_checking.get('minimum_probe_completion_percent', 80),
)
min_res = stream_checking.get('min_resolution', 'any')
if min_res in ('2160p', '4k'):
config['min_resolution_width'], config['min_resolution_height'] = 3840, 2160
Expand Down Expand Up @@ -101,6 +105,11 @@ def _is_stream_dead(self, stream_data: Dict[str, Any], channel_id: Optional[int]
if profile:
stream_checking = profile.get('stream_checking', {})
if stream_checking.get('enabled', False):
profile_config['minimum_probe_completion_percent'] = (
self._build_threshold_config_from_profile(stream_checking)[
'minimum_probe_completion_percent'
]
)
# Construct config from profile settings
# Convert min_res string (e.g., '1080p') to dimensions
min_res = stream_checking.get('min_resolution', '0x0')
Expand Down
3 changes: 3 additions & 0 deletions backend/apps/stream/checker/concurrent_channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -730,6 +730,9 @@ def inspection_result(analyzed, ordered_ids=None, dead_ids=()):
capacity_transition_lock=stream_statuses_lock,
probe_slots=getattr(self, '_preflight_probe_slots', None),
ffmpeg_duration=analysis_params.get('ffmpeg_duration', 30),
minimum_probe_completion_percent=_threshold_config.get(
'minimum_probe_completion_percent', 80,
),
timeout=analysis_params.get('timeout', 30),
retries=analysis_params.get('retries', 1),
retry_delay=analysis_params.get('retry_delay', 10),
Expand Down
9 changes: 9 additions & 0 deletions backend/apps/stream/checker/sequential_channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,9 @@ def _check_channel_sequential(
stream_id=stream['id'],
stream_name=stream.get('name', 'Unknown'),
ffmpeg_duration=analysis_params.get('ffmpeg_duration', 20),
minimum_probe_completion_percent=_threshold_config.get(
'minimum_probe_completion_percent', 80,
),
timeout=analysis_params.get('timeout', 30),
retries=analysis_params.get('retries', 1),
retry_delay=analysis_params.get('retry_delay', 10),
Expand Down Expand Up @@ -570,6 +573,9 @@ def recheck_sequential_bitrate(_stream, _initial):
stream_id=stream['id'],
stream_name=stream.get('name', 'Unknown'),
ffmpeg_duration=analysis_params.get('ffmpeg_duration', 20),
minimum_probe_completion_percent=_threshold_config.get(
'minimum_probe_completion_percent', 80,
),
timeout=analysis_params.get('timeout', 30),
retries=0,
retry_delay=0,
Expand Down Expand Up @@ -874,6 +880,9 @@ def sequential_recheck_started(initial, recheck_index, recheck_total):
stream_id=stream['id'],
stream_name=stream.get('name', 'Unknown'),
ffmpeg_duration=analysis_params.get('ffmpeg_duration', 20),
minimum_probe_completion_percent=_threshold_config.get(
'minimum_probe_completion_percent', 80,
),
timeout=analysis_params.get('timeout', 30),
retries=analysis_params.get('retries', 1),
retry_delay=analysis_params.get('retry_delay', 10),
Expand Down
26 changes: 24 additions & 2 deletions backend/apps/stream/stream_check_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@
from apps.core.logging_config import setup_logging
from apps.core.log_sanitizer import audit_ref as _audit_ref, scrub_urls, stream_ref, url_ref
from apps.core.stream_protocols import effective_stream_startup_buffer, has_supported_stream_protocol
from apps.core.probe_completion import (
media_window_seconds, normalize_minimum_probe_completion_percent,
probe_window_completion,
)

logger = setup_logging(__name__)

Expand Down Expand Up @@ -95,7 +99,7 @@
'cannot open',
'unknown hwaccel',
)
EARLY_EXIT_THRESHOLD = 0.8 # Consider ffmpeg exited early if elapsed < 80% of expected duration
EARLY_EXIT_THRESHOLD = 0.8 # Default for diagnostic/bitrate fallback timing
MAX_ERROR_LINES_TO_LOG = 5 # Maximum number of error lines to log from ffmpeg output
MAX_DEBUG_LINES_TO_LOG = 10 # Maximum number of debug lines to log from ffmpeg output

Expand Down Expand Up @@ -2008,6 +2012,13 @@ def apply_visual_probe() -> None:
progress_bitrate = None
last_stats_line = None # keeps updating; final line is the most stable average
last_media_time = 0.0
media_progress_times = []
result_data['ffmpeg_exit_code'] = result.returncode
result_data['ffmpeg_error_detected'] = bool(re.search(
r'Input/output error|Connection reset by peer|Connection timed out|'
r'Error opening input|Error during demuxing|Server returned [45]\d\d',
output or '', re.IGNORECASE,
))

# Track Input vs Output sections so we only parse input stream codecs,
# not decoded output formats (e.g. pcm_s16le instead of aac)
Expand All @@ -2017,6 +2028,7 @@ def apply_visual_probe() -> None:
progress_time = _parse_ffmpeg_progress_time(line)
if progress_time is not None:
last_media_time = max(last_media_time, progress_time)
media_progress_times.append(progress_time)

# ── Section tracking ─────────────────────────────────────────────
if 'Input #' in line:
Expand Down Expand Up @@ -2228,6 +2240,9 @@ def apply_visual_probe() -> None:
]
_log_ffmpeg_errors(output, logger, error_patterns)

result_data['probe_media_seconds'] = media_window_seconds(media_progress_times, duration)
if result.returncode != 0 or result_data['ffmpeg_error_detected']:
result_data['status'] = 'Error'
apply_visual_probe()

logger.debug(f" Analysis completed in {elapsed:.2f}s")
Expand Down Expand Up @@ -2829,6 +2844,7 @@ def analyze_stream(
preempt_check: Optional[Callable[[], bool]] = None,
defer_missing_bitrate_retry: bool = False,
retry_missing_bitrate: bool = True,
minimum_probe_completion_percent: float = 80,
) -> Dict[str, Any]:
"""
Perform complete stream analysis including codec, resolution, FPS, bitrate, and audio.
Expand Down Expand Up @@ -3018,6 +3034,12 @@ def analyze_stream(
'audio_bitrate': result_data['audio_bitrate'],
'status': result_data['status'],
'elapsed_time': result_data.get('elapsed_time', 0),
'ffmpeg_exit_code': result_data.get('ffmpeg_exit_code'),
'ffmpeg_error_detected': result_data.get('ffmpeg_error_detected', False),
'probe_media_seconds': result_data.get('probe_media_seconds'),
'minimum_probe_completion_percent': normalize_minimum_probe_completion_percent(
minimum_probe_completion_percent,
),
'ffmpeg_duration': ffmpeg_duration,
'ffmpeg_duration_seconds': result_data.get('ffmpeg_duration_seconds', ffmpeg_duration),
'timeout_seconds': result_data.get(
Expand Down Expand Up @@ -3145,7 +3167,7 @@ def analyze_stream(
# data that is not representative of sustained delivery.
# Give it another attempt rather than accepting the result.
elapsed = result_data.get('elapsed_time', ffmpeg_duration)
completed = elapsed >= ffmpeg_duration * EARLY_EXIT_THRESHOLD
completed, result['probe_completion_basis'] = probe_window_completion(result)
missing_bitrate = result.get('bitrate_kbps') is None
if completed and missing_bitrate and not retry_missing_bitrate:
logger.info(
Expand Down
14 changes: 14 additions & 0 deletions backend/apps/stream/stream_stats_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,13 @@ def _update_stream_stats(self, stream_data: Dict) -> bool:
"ffmpeg_output_bitrate": bitrate_value,
"bitrate_source": stream_data.get("bitrate_source"),
"quality_score": stream_data.get("score"),
"probe_completion_basis": stream_data.get("probe_completion_basis"),
"probe_media_seconds": stream_data.get("probe_media_seconds"),
"probe_elapsed_seconds": stream_data.get("elapsed_time"),
"probe_expected_seconds": stream_data.get("ffmpeg_duration"),
"minimum_probe_completion_percent": stream_data.get("minimum_probe_completion_percent"),
"ffmpeg_exit_code": stream_data.get("ffmpeg_exit_code"),
"ffmpeg_error_detected": stream_data.get("ffmpeg_error_detected"),
"quality_reason": stream_data.get("quality_reason"),
"quality_reason_detail": stream_data.get("quality_reason_detail"),
"quality_reason_context": stream_data.get("quality_reason_context"),
Expand Down Expand Up @@ -165,6 +172,13 @@ def _prepare_stream_stats_for_batch(self, stream_data: Dict) -> Optional[Dict[st
"ffmpeg_output_bitrate": bitrate_value,
"bitrate_source": stream_data.get("bitrate_source"),
"quality_score": stream_data.get("score"),
"probe_completion_basis": stream_data.get("probe_completion_basis"),
"probe_media_seconds": stream_data.get("probe_media_seconds"),
"probe_elapsed_seconds": stream_data.get("elapsed_time"),
"probe_expected_seconds": stream_data.get("ffmpeg_duration"),
"minimum_probe_completion_percent": stream_data.get("minimum_probe_completion_percent"),
"ffmpeg_exit_code": stream_data.get("ffmpeg_exit_code"),
"ffmpeg_error_detected": stream_data.get("ffmpeg_error_detected"),
"quality_reason": stream_data.get("quality_reason"),
"quality_reason_detail": stream_data.get("quality_reason_detail"),
"quality_reason_context": stream_data.get("quality_reason_context"),
Expand Down
Loading
Loading