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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- Quality checks apply the current profile's channel limit, soft provider cap
and measured-resolution ordering even when every source is within the grace
period. Cached measurements still avoid repeat probes; unchanged stream IDs
no longer bypass selection and ordering. Reported by
[@sm0keb0x](https://github.com/sm0keb0x) in
[#548](https://github.com/krinkuto11/streamflow/issues/548).

- RTSP and RTSPS sources, including cable tuners, can pass provider profile URL
resolution and FFmpeg quality probing. Default identity rewrites preserve the
original URL; alternate-profile isolation and capacity limits remain enforced.
Expand Down
78 changes: 3 additions & 75 deletions backend/apps/stream/checker/concurrent_channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -492,81 +492,9 @@ def inspection_result(analyzed, ordered_ids=None, dead_ids=()):
else:
logger.info(f"All {len(streams)} streams have been recently checked (within 2h immunity), using cached scores")

# Optimization: Skip check entirely if all conditions are met:
# 1. No new streams to analyze (all have been checked)
# 2. Stream count matches previous check (no additions/deletions)
# 3. Set of stream IDs is identical (no stream replacements)
previous_stream_count = len(checked_stream_ids)
current_stream_count = len(current_stream_ids)

if (current_stream_count == previous_stream_count and
set(current_stream_ids) == set(checked_stream_ids)):
logger.info(f"Channel {channel_name} unchanged since last check - skipping reorder")
# Update timestamp but keep existing checked_stream_ids
self._complete_channel_check(
channel_id,
lambda: self.update_tracker.mark_channel_checked(
channel_id,
stream_count=current_stream_count,
checked_stream_ids=checked_stream_ids
),
queue_entry_token=queue_entry_token,
)
# Best effort to reconstruct stats for skipped/cached streams
cached_stats = []
for s in streams_already_checked:
# Try to find existing stats if available in stream object
# Otherwise use placeholders
extracted_stats = extract_stream_stats(s)
formatted_stats = format_stream_stats_for_display(extracted_stats)

cached_for_score = {
'stream_id': s.get('id'),
'stream_name': s.get('name'),
'stream_url': s.get('url'),
'bitrate_kbps': extracted_stats.get('bitrate_kbps'),
'scoring_bitrate_kbps': (
self._previous_stream_bitrate(s)
if extracted_stats.get('bitrate_kbps') is None
else None
),
'resolution': extracted_stats.get('resolution'),
'fps': extracted_stats.get('fps'),
'video_codec': extracted_stats.get('video_codec'),
'audio_codec': extracted_stats.get('audio_codec'),
'hdr_format': extracted_stats.get('hdr_format'),
'status': 'cached'
}

temp_score = self._calculate_stream_score(cached_for_score, priority_m3u_ids, priority_mode, scoring_weights)

stat = {
'stream_id': s.get('id'),
'stream_name': s.get('name'),
'resolution': formatted_stats['resolution'],
'fps': formatted_stats['fps'],
'video_codec': formatted_stats['video_codec'],
'bitrate': formatted_stats['bitrate'],
'm3u_account': self._get_m3u_account_name(s.get('id'), udi) if hasattr(self, '_get_m3u_account_name') else 'N/A',
'score': temp_score
}
cached_stats.append(stat)

return {
'dead_streams_count': 0,
'revived_streams_count': 0,
'dead_streams': [],
'revived_streams': [],
'skipped_streams_count': len(streams_already_checked) + len(active_viewer_skipped_streams),
'skipped_streams': (
[{'id': s['id'], 'name': s.get('name', f"Stream {s['id']}")} for s in streams_already_checked]
+ active_viewer_skipped_streams
),
'preflight_inspection': inspection_result([]),
'checked_streams': cached_stats
}
else:
logger.info(f"Channel composition changed (prev: {previous_stream_count}, curr: {current_stream_count}) - will reorder")
# Reuse measurements, but always apply the current profile's
# ranking and limits to the complete assignment. An unchanged
# source list does not imply unchanged selection policy.

# Streams that are actively analyzed in this pass. Used to gate
# dead_stream_ids mutations — only streams checked in THIS pass may
Expand Down
74 changes: 74 additions & 0 deletions backend/tests/test_concurrent_limiter_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,80 @@ def test_preflight_reuse_avoids_probes_and_keeps_cached_ranking(monkeypatch, seq
assert rows[2]['measurement_source'] == 'current_check'


@pytest.mark.parametrize('mode', ['targeted', 'incremental', 'cached', 'manual'])
@pytest.mark.parametrize('sequential', [False, True])
@pytest.mark.parametrize('provider_cap', [0, 3])
def test_grace_period_applies_limits_and_resolution_order_to_all_candidates(
monkeypatch, mode, sequential, provider_cap,
):
"""Skipping probes must not exempt existing assignments from profile policy."""
from apps.stream.stream_checker_service import StreamCheckerService

channel_id = 548
streams = [
{'id': sid, 'name': f'Feed {sid}', 'url': f'http://provider.invalid/{sid}',
'm3u_account': 1 if sid <= 10 else 2,
'stream_stats': {'resolution': '1920x1080' if sid <= 10 else '1280x720',
'source_fps': 25, 'ffmpeg_output_bitrate': 4000,
'video_codec': 'h264', 'audio_codec': 'aac'}}
for sid in range(1, 21)
]
# Put the higher-score 720p sources first to exercise resolution-first sorting.
streams.reverse()
udi = _make_bitrate_runtime_udi(channel_id, streams)
profile = {'id': 'limits', 'name': 'Limits', 'stream_checking': {
'enabled': True, 'stream_limit': 10, 'provider_stream_limit': provider_cap,
'm3u_priority_mode': 'equal', 'grace_period': True,
'remove_dead_streams': True, 'allow_revive': True,
}}
automation = Mock()
automation.get_effective_configuration.return_value = {'profile': profile, 'periods': []}
monkeypatch.setattr('apps.stream.stream_checker_service.get_udi_manager', lambda: udi)
monkeypatch.setattr('apps.stream.stream_checker_service.get_automation_config_manager', lambda: automation)
monkeypatch.setattr('apps.stream.stream_checker_service.fetch_channel_streams', lambda cid: streams)
monkeypatch.setattr('apps.stream.stream_checker_service._get_base_url', lambda: 'http://dispatcharr.invalid')
monkeypatch.setattr('apps.stream.stream_checker_service.get_session_manager', lambda: Mock(
is_channel_in_active_session=Mock(return_value=False)))
writer = Mock(return_value=True)
monkeypatch.setattr('apps.stream.stream_checker_service.update_channel_streams', writer)
monkeypatch.setattr('apps.stream.stream_checker_service.batch_update_stream_stats', Mock(return_value=(20, 0)))
checked_ids = list(range(1, 21 if mode == 'cached' else 11))
service = StreamCheckerService()
_configure_bitrate_runtime_service(service, {'channels': {str(channel_id): {
'checked_stream_ids': checked_ids, 'last_check': datetime.now().isoformat(),
}}})
service._check_channel_limits = Mock(return_value=None)
service._get_active_viewer_protected_stream_ids = Mock(return_value=set())
service._run_deferred_bitrate_rechecks = Mock()
service._calculate_stream_score = lambda row, *a, **kw: .9 if row['stream_id'] > 10 else .5
probed = []

def probe(**kwargs):
sid = kwargs['stream_id']
probed.append(sid)
return {'stream_id': sid, 'stream_name': f'Feed {sid}',
'stream_url': f'http://provider.invalid/{sid}', 'status': 'OK',
'resolution': '1920x1080' if sid <= 10 else '1280x720',
'fps': 25, 'bitrate_kbps': 4000, 'video_codec': 'h264', 'audio_codec': 'aac'}

monkeypatch.setattr('apps.stream.stream_checker_service.analyze_stream', probe)
scheduler = Mock()
scheduler.check_streams_with_limits.side_effect = lambda **kw: [
probe(stream_id=item['id']) for item in kw['streams']
]
monkeypatch.setattr('apps.stream.concurrent_stream_limiter.get_smart_scheduler', lambda **kw: scheduler)
operation = service._check_channel_sequential if sequential else service._check_channel_concurrent
result = operation(channel_id, force_check_override=mode == 'manual',
target_stream_ids=list(range(11, 21)) if mode == 'targeted' else None)
assert 'error' not in result
assert len(probed) == (0 if mode == 'cached' else 20 if mode == 'manual' else 10)
writer.assert_called_once()
selected = writer.call_args.args[1]
assert len(selected) == 10
# Soft cap: select three from each provider, then fill in resolution order.
assert selected == ([10, 9, 8, 7, 6, 5, 4, 20, 19, 18] if provider_cap else list(range(10, 0, -1)))


def _configure_bitrate_runtime_service(service, tracker_updates):
service.config.config.setdefault('concurrent_streams', {}).update({
'enabled': True,
Expand Down
Loading