Compare commits

...
3 Commits
Author SHA1 Message Date
dtourolle 89a911b9c4 working livestreams!
🏗️ Build Plugin / build (push) Successful in 3m27s
🧪 Test Plugin / test (push) Successful in 1m38s
🚀 Release Plugin / build-and-release (push) Successful in 3m29s
2025-11-22 14:14:43 +01:00
dtourolle b8ac466c90 Fix issue with Jellyfin using local IP adress not server public URL, now pulic URL is set in plugin.
🏗️ Build Plugin / build (push) Successful in 3m21s
🧪 Test Plugin / test (push) Successful in 1m36s
🚀 Release Plugin / build-and-release (push) Successful in 3m9s
2025-11-21 20:17:05 +01:00
dtourolle e26f2a2ab1 passthrough not transcode
🚀 Release Plugin / build-and-release (push) Successful in 3m19s
🏗️ Build Plugin / build (push) Successful in 3m8s
🧪 Test Plugin / test (push) Successful in 1m43s
2025-11-16 20:53:23 +01:00
9 changed files with 339 additions and 40 deletions
+6 -11
View File
@@ -140,6 +140,11 @@ public class SRFApiClient : IDisposable
var fullUrl = $"{BaseUrl}{url}"; var fullUrl = $"{BaseUrl}{url}";
_logger.LogInformation("Fetching media composition for URN: {Urn} from {Url}", urn, fullUrl); _logger.LogInformation("Fetching media composition for URN: {Urn} from {Url}", urn, fullUrl);
// HttpClient consistently fails with 404, use curl directly
// This is likely due to routing/network configuration on the Jellyfin server
return await FetchWithCurlAsync(fullUrl, cancellationToken).ConfigureAwait(false);
/* HttpClient fallback disabled - always returns 404
var response = await _httpClient.GetAsync(url, cancellationToken).ConfigureAwait(false); var response = await _httpClient.GetAsync(url, cancellationToken).ConfigureAwait(false);
// Log response headers to diagnose geo-blocking // Log response headers to diagnose geo-blocking
@@ -178,17 +183,7 @@ public class SRFApiClient : IDisposable
} }
return result; return result;
} */
catch (HttpRequestException ex)
{
_logger.LogError(
ex,
"HTTP error fetching media composition for URN: {Urn} - StatusCode: {StatusCode}, trying curl fallback",
urn,
ex.StatusCode);
var fullUrl = $"{BaseUrl}/mediaComposition/byUrn/{urn}.json";
return await FetchWithCurlAsync(fullUrl, cancellationToken).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -7,6 +7,7 @@ using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Jellyfin.Plugin.SRFPlay.Services; using Jellyfin.Plugin.SRFPlay.Services;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Channels; using MediaBrowser.Model.Channels;
@@ -27,6 +28,7 @@ public class SRFPlayChannel : IChannel, IHasCacheKey
private readonly StreamUrlResolver _streamResolver; private readonly StreamUrlResolver _streamResolver;
private readonly StreamProxyService _proxyService; private readonly StreamProxyService _proxyService;
private readonly CategoryService? _categoryService; private readonly CategoryService? _categoryService;
private readonly IServerApplicationHost _appHost;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="SRFPlayChannel"/> class. /// Initializes a new instance of the <see cref="SRFPlayChannel"/> class.
@@ -35,12 +37,14 @@ public class SRFPlayChannel : IChannel, IHasCacheKey
/// <param name="contentRefreshService">The content refresh service.</param> /// <param name="contentRefreshService">The content refresh service.</param>
/// <param name="streamResolver">The stream resolver.</param> /// <param name="streamResolver">The stream resolver.</param>
/// <param name="proxyService">The stream proxy service.</param> /// <param name="proxyService">The stream proxy service.</param>
/// <param name="appHost">The server application host.</param>
/// <param name="categoryService">The category service (optional).</param> /// <param name="categoryService">The category service (optional).</param>
public SRFPlayChannel( public SRFPlayChannel(
ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
ContentRefreshService contentRefreshService, ContentRefreshService contentRefreshService,
StreamUrlResolver streamResolver, StreamUrlResolver streamResolver,
StreamProxyService proxyService, StreamProxyService proxyService,
IServerApplicationHost appHost,
CategoryService? categoryService = null) CategoryService? categoryService = null)
{ {
_loggerFactory = loggerFactory; _loggerFactory = loggerFactory;
@@ -48,6 +52,7 @@ public class SRFPlayChannel : IChannel, IHasCacheKey
_contentRefreshService = contentRefreshService; _contentRefreshService = contentRefreshService;
_streamResolver = streamResolver; _streamResolver = streamResolver;
_proxyService = proxyService; _proxyService = proxyService;
_appHost = appHost;
_categoryService = categoryService; _categoryService = categoryService;
if (_categoryService == null) if (_categoryService == null)
@@ -471,9 +476,14 @@ public class SRFPlayChannel : IChannel, IHasCacheKey
// Register stream with proxy service // Register stream with proxy service
_proxyService.RegisterStream(itemId, streamUrl); _proxyService.RegisterStream(itemId, streamUrl);
// Get the server URL for proxy - prefer configured public URL for remote clients
var serverUrl = !string.IsNullOrWhiteSpace(config.PublicServerUrl)
? config.PublicServerUrl.TrimEnd('/') // Use configured public URL (important for Android/remote clients)
: _appHost.GetSmartApiUrl(string.Empty); // Fall back to Jellyfin's smart URL resolution
// Create proxy URL as absolute HTTP URL (required for ffmpeg) // Create proxy URL as absolute HTTP URL (required for ffmpeg)
// Use localhost as Jellyfin should be able to access its own endpoints // Use the actual server URL so remote clients can access it
var proxyUrl = $"http://localhost:8096/Plugins/SRFPlay/Proxy/{itemId}/master.m3u8"; var proxyUrl = $"{serverUrl}/Plugins/SRFPlay/Proxy/{itemId}/master.m3u8";
// Build overview // Build overview
var overview = chapter.Description ?? chapter.Lead; var overview = chapter.Description ?? chapter.Lead;
@@ -142,4 +142,11 @@ public class PluginConfiguration : BasePluginConfiguration
[System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA2227:Collection properties should be read only", Justification = "Required for configuration serialization")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA2227:Collection properties should be read only", Justification = "Required for configuration serialization")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1002:Do not expose generic lists", Justification = "Configuration DTO")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1002:Do not expose generic lists", Justification = "Configuration DTO")]
public System.Collections.Generic.List<string> EnabledTopics { get; set; } public System.Collections.Generic.List<string> EnabledTopics { get; set; }
/// <summary>
/// Gets or sets the public/external server URL for remote clients (e.g., https://jellyfin.example.com:8920).
/// If not set, the plugin will use Jellyfin's GetSmartApiUrl() which may return local addresses.
/// This is important for Android and other remote clients to access streams.
/// </summary>
public string PublicServerUrl { get; set; } = string.Empty;
} }
@@ -82,6 +82,17 @@
<input id="ProxyPassword" name="ProxyPassword" type="password" is="emby-input" autocomplete="off" /> <input id="ProxyPassword" name="ProxyPassword" type="password" is="emby-input" autocomplete="off" />
<div class="fieldDescription">Password for proxy authentication (leave empty if not required)</div> <div class="fieldDescription">Password for proxy authentication (leave empty if not required)</div>
</div> </div>
<br />
<h2>Network Settings</h2>
<div class="inputContainer">
<label class="inputLabel inputLabelUnfocused" for="PublicServerUrl">Public Server URL (Optional)</label>
<input id="PublicServerUrl" name="PublicServerUrl" type="text" is="emby-input" placeholder="e.g., https://jellyfin.example.com:8920" />
<div class="fieldDescription">
The public/external URL for remote clients (Android, iOS, etc.) to access streaming proxy.
<br />If not set, the plugin will use Jellyfin's automatic URL detection which may return local addresses.
<br /><strong>Important for Android/remote playback!</strong>
</div>
</div>
<div> <div>
<button is="emby-button" type="submit" class="raised button-submit block emby-button"> <button is="emby-button" type="submit" class="raised button-submit block emby-button">
<span>Save</span> <span>Save</span>
@@ -110,6 +121,7 @@
document.querySelector('#ProxyAddress').value = config.ProxyAddress || ''; document.querySelector('#ProxyAddress').value = config.ProxyAddress || '';
document.querySelector('#ProxyUsername').value = config.ProxyUsername || ''; document.querySelector('#ProxyUsername').value = config.ProxyUsername || '';
document.querySelector('#ProxyPassword').value = config.ProxyPassword || ''; document.querySelector('#ProxyPassword').value = config.ProxyPassword || '';
document.querySelector('#PublicServerUrl').value = config.PublicServerUrl || '';
Dashboard.hideLoadingMsg(); Dashboard.hideLoadingMsg();
}); });
}); });
@@ -129,6 +141,7 @@
config.ProxyAddress = document.querySelector('#ProxyAddress').value; config.ProxyAddress = document.querySelector('#ProxyAddress').value;
config.ProxyUsername = document.querySelector('#ProxyUsername').value; config.ProxyUsername = document.querySelector('#ProxyUsername').value;
config.ProxyPassword = document.querySelector('#ProxyPassword').value; config.ProxyPassword = document.querySelector('#ProxyPassword').value;
config.PublicServerUrl = document.querySelector('#PublicServerUrl').value;
ApiClient.updatePluginConfiguration(SRFPlayConfig.pluginUniqueId, config).then(function (result) { ApiClient.updatePluginConfiguration(SRFPlayConfig.pluginUniqueId, config).then(function (result) {
Dashboard.processPluginConfigurationUpdateResult(result); Dashboard.processPluginConfigurationUpdateResult(result);
}); });
@@ -45,21 +45,42 @@ public class StreamProxyController : ControllerBase
[FromRoute] string itemId, [FromRoute] string itemId,
CancellationToken cancellationToken) CancellationToken cancellationToken)
{ {
_logger.LogInformation("Proxy request for master manifest - ItemId: {ItemId}", itemId); _logger.LogInformation("Proxy request for master manifest - Path ItemId: {PathItemId}, Query params: {QueryString}", itemId, Request.QueryString);
// Try to resolve the actual item ID (path ID might be a session ID during transcoding) // Try to resolve the actual item ID (path ID might be a session ID during transcoding)
var actualItemId = ResolveItemId(itemId); var actualItemId = ResolveItemId(itemId);
try try
{ {
// Build the base proxy URL for this item (use original itemId from path to maintain URL structure) // Get the correct scheme (https if configured, otherwise use request scheme)
var baseProxyUrl = $"{Request.Scheme}://{Request.Host}/Plugins/SRFPlay/Proxy/{itemId}"; var scheme = GetProxyScheme();
// Build the base proxy URL for this item
// Preserve query parameters (token or itemId) from the original request
string baseProxyUrl;
if (Request.Query.TryGetValue("token", out var token) && !string.IsNullOrEmpty(token))
{
baseProxyUrl = $"{scheme}://{Request.Host}/Plugins/SRFPlay/Proxy/{itemId}?token={token}";
_logger.LogDebug("Using token-based proxy URL with token: {Token}", token.ToString());
}
else if (actualItemId != itemId)
{
// Legacy: If path ID differs from resolved ID, add itemId query parameter
baseProxyUrl = $"{scheme}://{Request.Host}/Plugins/SRFPlay/Proxy/{itemId}?itemId={actualItemId}";
_logger.LogInformation("Path itemId {PathId} differs from resolved itemId {ResolvedId}, adding query parameter", itemId, actualItemId);
}
else
{
// Simple case: no query parameters needed
baseProxyUrl = $"{scheme}://{Request.Host}/Plugins/SRFPlay/Proxy/{itemId}";
_logger.LogDebug("Path itemId matches resolved itemId: {ItemId}", itemId);
}
var manifestContent = await _proxyService.GetRewrittenManifestAsync(actualItemId, baseProxyUrl, cancellationToken).ConfigureAwait(false); var manifestContent = await _proxyService.GetRewrittenManifestAsync(actualItemId, baseProxyUrl, cancellationToken).ConfigureAwait(false);
if (manifestContent == null) if (manifestContent == null)
{ {
_logger.LogWarning("Manifest not found for item {ItemId}", itemId); _logger.LogWarning("Manifest not found for path itemId {PathItemId}, resolved itemId {ResolvedItemId} - stream may not be registered", itemId, actualItemId);
return NotFound(); return NotFound();
} }
@@ -108,7 +129,8 @@ public class StreamProxyController : ControllerBase
// Convert to string and rewrite URLs // Convert to string and rewrite URLs
var manifestContent = System.Text.Encoding.UTF8.GetString(manifestData); var manifestContent = System.Text.Encoding.UTF8.GetString(manifestData);
var baseProxyUrl = $"{Request.Scheme}://{Request.Host}/Plugins/SRFPlay/Proxy/{itemId}"; var scheme = GetProxyScheme();
var baseProxyUrl = $"{scheme}://{Request.Host}/Plugins/SRFPlay/Proxy/{itemId}";
var rewrittenContent = RewriteSegmentUrls(manifestContent, baseProxyUrl); var rewrittenContent = RewriteSegmentUrls(manifestContent, baseProxyUrl);
_logger.LogDebug("Returning variant manifest for item {ItemId} ({Length} bytes)", itemId, rewrittenContent.Length); _logger.LogDebug("Returning variant manifest for item {ItemId} ({Length} bytes)", itemId, rewrittenContent.Length);
@@ -165,6 +187,31 @@ public class StreamProxyController : ControllerBase
} }
} }
/// <summary>
/// Gets the correct scheme for proxy URLs (https if public URL is configured with https).
/// </summary>
/// <returns>The scheme to use (http or https).</returns>
private string GetProxyScheme()
{
// Check if PublicServerUrl is configured and uses HTTPS
var config = Plugin.Instance?.Configuration;
if (config != null && !string.IsNullOrWhiteSpace(config.PublicServerUrl))
{
if (config.PublicServerUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
return "https";
}
}
// Fall back to request scheme, but prefer https if forwarded headers indicate it
if (Request.Headers.TryGetValue("X-Forwarded-Proto", out var forwardedProto))
{
return forwardedProto.ToString().ToLowerInvariant();
}
return Request.Scheme;
}
/// <summary> /// <summary>
/// Resolves the actual item ID from the request. /// Resolves the actual item ID from the request.
/// </summary> /// </summary>
@@ -172,14 +219,24 @@ public class StreamProxyController : ControllerBase
/// <returns>The resolved item ID.</returns> /// <returns>The resolved item ID.</returns>
private string ResolveItemId(string pathItemId) private string ResolveItemId(string pathItemId)
{ {
// Check if there's an itemId query parameter (fallback for transcoding sessions) // Check for token parameter first (preferred method)
if (Request.Query.TryGetValue("token", out var token) && !string.IsNullOrEmpty(token))
{
// Try to resolve the original item ID from the token via the proxy service
// We'll need to add a method to StreamProxyService to look up by token
_logger.LogInformation("Found token parameter: {Token}, will use path ID {PathItemId} for lookup", token.ToString(), pathItemId);
return pathItemId; // Use path ID for now; token prevents Jellyfin from rewriting the URL
}
// Check if there's an itemId query parameter (legacy fallback)
if (Request.Query.TryGetValue("itemId", out var queryItemId) && !string.IsNullOrEmpty(queryItemId)) if (Request.Query.TryGetValue("itemId", out var queryItemId) && !string.IsNullOrEmpty(queryItemId))
{ {
_logger.LogDebug("Using itemId from query parameter: {QueryItemId} (path had: {PathItemId})", queryItemId.ToString(), pathItemId); _logger.LogInformation("Using itemId from query parameter: {QueryItemId} (path had: {PathItemId})", queryItemId.ToString(), pathItemId);
return queryItemId.ToString(); return queryItemId.ToString();
} }
// Use the path item ID as-is // No query parameters - use path ID as-is (TRANSCODING SESSION ID CASE)
_logger.LogWarning("⚠️ No query parameters found, using path ID as-is: {PathItemId} (likely transcoding session ID)", pathItemId);
return pathItemId; return pathItemId;
} }
@@ -191,6 +248,21 @@ public class StreamProxyController : ControllerBase
/// <returns>The rewritten manifest.</returns> /// <returns>The rewritten manifest.</returns>
private string RewriteSegmentUrls(string manifestContent, string baseProxyUrl) private string RewriteSegmentUrls(string manifestContent, string baseProxyUrl)
{ {
// Extract query parameters from the current request to propagate them
string queryParams;
if (Request.Query.TryGetValue("token", out var token) && !string.IsNullOrEmpty(token))
{
queryParams = $"?token={token}";
}
else if (Request.Query.TryGetValue("itemId", out var itemId) && !string.IsNullOrEmpty(itemId))
{
queryParams = $"?itemId={itemId}";
}
else
{
queryParams = string.Empty;
}
var lines = manifestContent.Split('\n'); var lines = manifestContent.Split('\n');
var result = new System.Text.StringBuilder(); var result = new System.Text.StringBuilder();
@@ -207,12 +279,12 @@ public class StreamProxyController : ControllerBase
var uri = new Uri(line.Trim()); var uri = new Uri(line.Trim());
var segments = uri.AbsolutePath.Split('/'); var segments = uri.AbsolutePath.Split('/');
var fileName = segments[^1]; var fileName = segments[^1];
result.AppendLine(CultureInfo.InvariantCulture, $"{baseProxyUrl}/{fileName}"); result.AppendLine(CultureInfo.InvariantCulture, $"{baseProxyUrl}/{fileName}{queryParams}");
} }
else else
{ {
// Relative URL - rewrite to proxy // Relative URL - rewrite to proxy
result.AppendLine(CultureInfo.InvariantCulture, $"{baseProxyUrl}/{line.Trim()}"); result.AppendLine(CultureInfo.InvariantCulture, $"{baseProxyUrl}/{line.Trim()}{queryParams}");
} }
} }
@@ -0,0 +1,134 @@
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Plugin.SRFPlay.Services;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Plugin.SRFPlay.Providers;
/// <summary>
/// Live stream wrapper for SRF Play streams to handle transcoding sessions.
/// </summary>
internal sealed class SRFLiveStream : ILiveStream
{
private readonly ILogger _logger;
private readonly StreamProxyService _proxyService;
private readonly string _originalItemId;
private MediaSourceInfo? _mediaSource;
/// <summary>
/// Initializes a new instance of the <see cref="SRFLiveStream"/> class.
/// </summary>
/// <param name="logger">The logger.</param>
/// <param name="proxyService">The stream proxy service.</param>
/// <param name="originalItemId">The original item ID.</param>
/// <param name="openToken">The open token.</param>
/// <param name="loggerFactory">The logger factory.</param>
public SRFLiveStream(
ILogger logger,
StreamProxyService proxyService,
string originalItemId,
string openToken,
ILoggerFactory loggerFactory)
{
_logger = logger;
_proxyService = proxyService;
_originalItemId = originalItemId;
OriginalStreamId = openToken;
UniqueId = openToken;
}
/// <inheritdoc />
public int ConsumerCount { get; set; }
/// <inheritdoc />
public string OriginalStreamId { get; set; }
/// <inheritdoc />
public string UniqueId { get; }
/// <inheritdoc />
public string TunerHostId => string.Empty;
/// <inheritdoc />
public bool EnableStreamSharing => false;
/// <inheritdoc />
public MediaSourceInfo MediaSource
{
get => _mediaSource ?? throw new InvalidOperationException("MediaSource not set");
set
{
_mediaSource = value;
_logger.LogInformation(
"SRFLiveStream MediaSource set - Id: {MediaSourceId}, Path: {Path}, OriginalItemId: {OriginalItemId}",
value.Id,
value.Path,
_originalItemId);
// When Jellyfin assigns a live stream ID (for transcoding), register the stream with that ID too
if (value.Id != _originalItemId)
{
_logger.LogInformation(
"Transcoding session detected - LiveStream ID {LiveStreamId} differs from original item ID {OriginalItemId}. Registering stream with both IDs.",
value.Id,
_originalItemId);
// Get the authenticated URL from the original registration
var authenticatedUrl = _proxyService.GetAuthenticatedUrl(_originalItemId);
if (authenticatedUrl != null)
{
// Register the same stream URL with the transcoding session ID
_proxyService.RegisterStream(value.Id, authenticatedUrl);
_logger.LogInformation("Registered stream for transcoding session ID: {LiveStreamId}", value.Id);
}
else
{
_logger.LogWarning("Could not find authenticated URL for original item {OriginalItemId}", _originalItemId);
}
}
}
}
/// <inheritdoc />
public Task Close()
{
_logger.LogInformation("Closing SRF live stream for item {OriginalItemId}", _originalItemId);
return Task.CompletedTask;
}
/// <inheritdoc />
public Task Open(CancellationToken cancellationToken)
{
_logger.LogInformation("Opening SRF live stream for item {OriginalItemId}", _originalItemId);
return Task.CompletedTask;
}
/// <inheritdoc />
public Stream GetStream()
{
throw new NotSupportedException("Direct stream access not supported for SRF streams");
}
/// <inheritdoc />
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the unmanaged resources used by the SRFLiveStream and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">True to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
private void Dispose(bool disposing)
{
if (disposing)
{
_logger.LogDebug("Disposing SRF live stream for item {OriginalItemId}", _originalItemId);
}
}
}
@@ -1,10 +1,12 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Jellyfin.Plugin.SRFPlay.Api; using Jellyfin.Plugin.SRFPlay.Api;
using Jellyfin.Plugin.SRFPlay.Services; using Jellyfin.Plugin.SRFPlay.Services;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto; using MediaBrowser.Model.Dto;
@@ -24,6 +26,8 @@ public class SRFMediaProvider : IMediaSourceProvider
private readonly MetadataCache _metadataCache; private readonly MetadataCache _metadataCache;
private readonly StreamUrlResolver _streamResolver; private readonly StreamUrlResolver _streamResolver;
private readonly StreamProxyService _proxyService; private readonly StreamProxyService _proxyService;
private readonly IServerApplicationHost _appHost;
private readonly Dictionary<string, string> _openTokenToItemId = new();
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="SRFMediaProvider"/> class. /// Initializes a new instance of the <see cref="SRFMediaProvider"/> class.
@@ -32,17 +36,20 @@ public class SRFMediaProvider : IMediaSourceProvider
/// <param name="metadataCache">The metadata cache.</param> /// <param name="metadataCache">The metadata cache.</param>
/// <param name="streamResolver">The stream URL resolver.</param> /// <param name="streamResolver">The stream URL resolver.</param>
/// <param name="proxyService">The stream proxy service.</param> /// <param name="proxyService">The stream proxy service.</param>
/// <param name="appHost">The server application host.</param>
public SRFMediaProvider( public SRFMediaProvider(
ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
MetadataCache metadataCache, MetadataCache metadataCache,
StreamUrlResolver streamResolver, StreamUrlResolver streamResolver,
StreamProxyService proxyService) StreamProxyService proxyService,
IServerApplicationHost appHost)
{ {
_loggerFactory = loggerFactory; _loggerFactory = loggerFactory;
_logger = loggerFactory.CreateLogger<SRFMediaProvider>(); _logger = loggerFactory.CreateLogger<SRFMediaProvider>();
_metadataCache = metadataCache; _metadataCache = metadataCache;
_streamResolver = streamResolver; _streamResolver = streamResolver;
_proxyService = proxyService; _proxyService = proxyService;
_appHost = appHost;
} }
/// <summary> /// <summary>
@@ -174,16 +181,29 @@ public class SRFMediaProvider : IMediaSourceProvider
var itemIdStr = item.Id.ToString("N"); // Use hex format without dashes var itemIdStr = item.Id.ToString("N"); // Use hex format without dashes
_proxyService.RegisterStream(itemIdStr, streamUrl); _proxyService.RegisterStream(itemIdStr, streamUrl);
// Create proxy URL as absolute HTTP URL (required for ffmpeg) // Get the server URL for proxy - prefer configured public URL for remote clients
// Use localhost as Jellyfin should be able to access its own endpoints var serverUrl = !string.IsNullOrWhiteSpace(config.PublicServerUrl)
// Include item ID as query parameter to preserve it during transcoding ? config.PublicServerUrl.TrimEnd('/') // Use configured public URL (important for Android/remote clients)
var proxyUrl = $"http://localhost:8096/Plugins/SRFPlay/Proxy/{itemIdStr}/master.m3u8?itemId={itemIdStr}"; : _appHost.GetSmartApiUrl(string.Empty); // Fall back to Jellyfin's smart URL resolution
_logger.LogInformation("Using proxy URL for item {ItemId}: {ProxyUrl}", itemIdStr, proxyUrl);
// Detect if this is a live stream // Detect if this is a live stream
var isLiveStream = chapter.Type == "SCHEDULED_LIVESTREAM" || urn.Contains("livestream", StringComparison.OrdinalIgnoreCase); var isLiveStream = chapter.Type == "SCHEDULED_LIVESTREAM" || urn.Contains("livestream", StringComparison.OrdinalIgnoreCase);
// Generate an open token for this media source (used to track transcoding sessions)
var openToken = Guid.NewGuid().ToString("N");
_openTokenToItemId[openToken] = itemIdStr;
_logger.LogDebug("Created open token {OpenToken} for item {ItemId}", openToken, itemIdStr);
// Create proxy URL using token instead of item ID in path
// This prevents Jellyfin from rewriting the URL during transcoding
var proxyUrl = $"{serverUrl}/Plugins/SRFPlay/Proxy/{itemIdStr}/master.m3u8?token={openToken}";
_logger.LogInformation(
"Using proxy URL for item {ItemId}: {ProxyUrl} (PublicServerUrl configured: {IsPublicConfigured})",
itemIdStr,
proxyUrl,
!string.IsNullOrWhiteSpace(config.PublicServerUrl));
// Create media source using proxy URL - enables DirectPlay! // Create media source using proxy URL - enables DirectPlay!
var mediaSource = new MediaSourceInfo var mediaSource = new MediaSourceInfo
{ {
@@ -200,10 +220,11 @@ public class SRFMediaProvider : IMediaSourceProvider
RunTimeTicks = chapter.Duration > 0 ? TimeSpan.FromMilliseconds(chapter.Duration).Ticks : null, RunTimeTicks = chapter.Duration > 0 ? TimeSpan.FromMilliseconds(chapter.Duration).Ticks : null,
VideoType = VideoType.VideoFile, VideoType = VideoType.VideoFile,
IsInfiniteStream = isLiveStream, // True for live streams! IsInfiniteStream = isLiveStream, // True for live streams!
RequiresOpening = false, RequiresOpening = true, // Enable to handle transcoding sessions
RequiresClosing = false, RequiresClosing = false,
SupportsProbing = false, // Disable probing for proxy URLs SupportsProbing = false, // Disable probing for proxy URLs
ReadAtNativeFramerate = isLiveStream, // Read at native framerate for live streams ReadAtNativeFramerate = isLiveStream, // Read at native framerate for live streams
OpenToken = openToken, // Token to identify this media source
MediaStreams = new List<MediaBrowser.Model.Entities.MediaStream> MediaStreams = new List<MediaBrowser.Model.Entities.MediaStream>
{ {
new MediaBrowser.Model.Entities.MediaStream new MediaBrowser.Model.Entities.MediaStream
@@ -267,10 +288,27 @@ public class SRFMediaProvider : IMediaSourceProvider
} }
/// <inheritdoc /> /// <inheritdoc />
public Task<ILiveStream> OpenMediaSource(string openToken, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken) public async Task<ILiveStream> OpenMediaSource(string openToken, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken)
{ {
_logger.LogWarning("OpenMediaSource called with openToken: {OpenToken} - This should not be called for HTTP streams!", openToken); _logger.LogInformation("OpenMediaSource called with openToken: {OpenToken}", openToken);
// Not needed for static HTTP streams
throw new NotImplementedException(); // Look up the original item ID from the open token
if (!_openTokenToItemId.TryGetValue(openToken, out var originalItemId))
{
_logger.LogError("Open token {OpenToken} not found in registry", openToken);
throw new InvalidOperationException($"Open token {openToken} not found");
}
_logger.LogInformation("Open token {OpenToken} maps to original item ID: {ItemId}", openToken, originalItemId);
// Create a live stream wrapper
var liveStream = new SRFLiveStream(
_logger,
_proxyService,
originalItemId,
openToken,
_loggerFactory);
return await Task.FromResult<ILiveStream>(liveStream).ConfigureAwait(false);
} }
} }
@@ -100,12 +100,17 @@ public class StreamProxyService : IDisposable
/// <returns>The authenticated URL, or null if not found or expired.</returns> /// <returns>The authenticated URL, or null if not found or expired.</returns>
public string? GetAuthenticatedUrl(string itemId) public string? GetAuthenticatedUrl(string itemId)
{ {
_logger.LogInformation("GetAuthenticatedUrl called for itemId: {ItemId}", itemId);
// Try direct lookup first // Try direct lookup first
if (_streamMappings.TryGetValue(itemId, out var streamInfo)) if (_streamMappings.TryGetValue(itemId, out var streamInfo))
{ {
_logger.LogInformation("✅ Found stream by direct lookup for itemId: {ItemId}", itemId);
return ValidateAndReturnStream(itemId, streamInfo); return ValidateAndReturnStream(itemId, streamInfo);
} }
_logger.LogWarning("❌ No direct match for itemId: {ItemId}, trying fallbacks... (Registered streams: {Count})", itemId, _streamMappings.Count);
// Fallback: Try to find by GUID variations (with/without dashes) // Fallback: Try to find by GUID variations (with/without dashes)
// This handles cases where Jellyfin uses different GUID formats // This handles cases where Jellyfin uses different GUID formats
var normalizedId = NormalizeGuid(itemId); var normalizedId = NormalizeGuid(itemId);
@@ -403,6 +408,16 @@ public class StreamProxyService : IDisposable
var baseUri = new Uri(originalBaseUrl); var baseUri = new Uri(originalBaseUrl);
var baseUrl = $"{baseUri.Scheme}://{baseUri.Host}{string.Join('/', baseUri.AbsolutePath.Split('/')[..^1])}"; var baseUrl = $"{baseUri.Scheme}://{baseUri.Host}{string.Join('/', baseUri.AbsolutePath.Split('/')[..^1])}";
// Extract query parameters from proxyBaseUrl to propagate them
var queryParams = string.Empty;
var queryStart = proxyBaseUrl.IndexOf('?', StringComparison.Ordinal);
if (queryStart >= 0)
{
queryParams = proxyBaseUrl[queryStart..];
proxyBaseUrl = proxyBaseUrl[..queryStart]; // Remove query from base URL
_logger.LogDebug("Extracted query parameters from proxy URL: {QueryParams}", queryParams);
}
// Pattern to match .m3u8 and .ts/.mp4 segment references // Pattern to match .m3u8 and .ts/.mp4 segment references
var pattern = @"(?:^|\n)([^#\n][^\n]*\.(?:m3u8|ts|mp4|m4s|aac)[^\n]*)"; var pattern = @"(?:^|\n)([^#\n][^\n]*\.(?:m3u8|ts|mp4|m4s|aac)[^\n]*)";
@@ -416,11 +431,11 @@ public class StreamProxyService : IDisposable
{ {
// Rewrite absolute URLs to proxy // Rewrite absolute URLs to proxy
var relativePath = url.Replace(baseUrl + "/", string.Empty, StringComparison.Ordinal); var relativePath = url.Replace(baseUrl + "/", string.Empty, StringComparison.Ordinal);
return $"\n{proxyBaseUrl}/{relativePath}"; return $"\n{proxyBaseUrl}/{relativePath}{queryParams}";
} }
// Relative URL - rewrite to proxy // Relative URL - rewrite to proxy
return $"\n{proxyBaseUrl}/{url}"; return $"\n{proxyBaseUrl}/{url}{queryParams}";
}); });
return rewritten; return rewritten;
@@ -87,6 +87,17 @@ public class StreamUrlResolver : IDisposable
chapter.Id, chapter.Id,
hlsResources.Count); hlsResources.Count);
// Log all HLS resources with their quality info to help debug quality selection
foreach (var resource in hlsResources)
{
_logger.LogInformation(
"Available HLS resource - Quality={Quality}, Protocol={Protocol}, Streaming={Streaming}, URL={Url}",
resource.Quality ?? "NULL",
resource.Protocol ?? "NULL",
resource.Streaming ?? "NULL",
resource.Url);
}
if (hlsResources.Count == 0) if (hlsResources.Count == 0)
{ {
_logger.LogWarning("No HLS resources found for chapter: {ChapterId}", chapter.Id); _logger.LogWarning("No HLS resources found for chapter: {ChapterId}", chapter.Id);
@@ -114,6 +125,10 @@ public class StreamUrlResolver : IDisposable
} }
// Select based on quality preference // Select based on quality preference
_logger.LogInformation(
"Selecting stream with quality preference: {QualityPreference}",
qualityPreference);
Resource? selectedResource = qualityPreference switch Resource? selectedResource = qualityPreference switch
{ {
QualityPreference.HD => SelectHDResource(hlsResources) ?? SelectBestAvailableResource(hlsResources), QualityPreference.HD => SelectHDResource(hlsResources) ?? SelectBestAvailableResource(hlsResources),
@@ -124,10 +139,10 @@ public class StreamUrlResolver : IDisposable
if (selectedResource != null) if (selectedResource != null)
{ {
_logger.LogDebug( _logger.LogInformation(
"Selected stream for chapter {ChapterId}: Quality={Quality}, Protocol={Protocol}, URL={Url}", "Selected stream for chapter {ChapterId}: Quality={Quality}, Protocol={Protocol}, URL={Url}",
chapter.Id, chapter.Id,
selectedResource.Quality, selectedResource.Quality ?? "NULL",
selectedResource.Protocol, selectedResource.Protocol,
selectedResource.Url); selectedResource.Url);
return selectedResource.Url; return selectedResource.Url;