Compare commits

..
2 Commits
Author SHA1 Message Date
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
7 changed files with 102 additions and 17 deletions
@@ -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);
}); });
@@ -53,7 +53,13 @@ public class StreamProxyController : ControllerBase
try try
{ {
// Build the base proxy URL for this item (use original itemId from path to maintain URL structure) // Build the base proxy URL for this item (use original itemId from path to maintain URL structure)
var baseProxyUrl = $"{Request.Scheme}://{Request.Host}/Plugins/SRFPlay/Proxy/{itemId}"; // Always include the actualItemId as a query parameter to ensure proper resolution during transcoding
var baseProxyUrl = $"{Request.Scheme}://{Request.Host}/Plugins/SRFPlay/Proxy/{itemId}?itemId={actualItemId}";
if (actualItemId != itemId)
{
_logger.LogDebug("Path itemId {PathId} differs from resolved itemId {ResolvedId}, adding query parameter", itemId, actualItemId);
}
var manifestContent = await _proxyService.GetRewrittenManifestAsync(actualItemId, baseProxyUrl, cancellationToken).ConfigureAwait(false); var manifestContent = await _proxyService.GetRewrittenManifestAsync(actualItemId, baseProxyUrl, cancellationToken).ConfigureAwait(false);
@@ -179,7 +185,9 @@ public class StreamProxyController : ControllerBase
return queryItemId.ToString(); return queryItemId.ToString();
} }
// Use the path item ID as-is // If path ID and query ID don't match, it's likely a transcoding session
// Try to use the proxy service fallback to find the correct stream
_logger.LogDebug("No itemId query parameter found, using path ID as-is: {PathItemId}", pathItemId);
return pathItemId; return pathItemId;
} }
@@ -191,6 +199,11 @@ 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 the itemId query parameter from the current request to propagate it
var itemIdParam = Request.Query.TryGetValue("itemId", out var itemId) && !string.IsNullOrEmpty(itemId)
? $"?itemId={itemId}"
: 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 +220,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}{itemIdParam}");
} }
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()}{itemIdParam}");
} }
} }
@@ -5,6 +5,7 @@ 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 +25,7 @@ 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;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="SRFMediaProvider"/> class. /// Initializes a new instance of the <see cref="SRFMediaProvider"/> class.
@@ -32,17 +34,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,12 +179,21 @@ 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); // Create proxy URL as absolute HTTP URL (required for ffmpeg)
// Use the actual server URL so remote clients can access it
// Include item ID as query parameter to preserve it during transcoding
var proxyUrl = $"{serverUrl}/Plugins/SRFPlay/Proxy/{itemIdStr}/master.m3u8?itemId={itemIdStr}";
_logger.LogInformation(
"Using proxy URL for item {ItemId}: {ProxyUrl} (PublicServerUrl configured: {IsPublicConfigured})",
itemIdStr,
proxyUrl,
!string.IsNullOrWhiteSpace(config.PublicServerUrl));
// 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);
@@ -403,6 +403,19 @@ 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 itemId query parameter from proxyBaseUrl to propagate it
var itemIdParam = string.Empty;
var queryMarker = "?itemId=";
if (proxyBaseUrl.Contains(queryMarker, StringComparison.Ordinal))
{
var queryStart = proxyBaseUrl.IndexOf(queryMarker, StringComparison.Ordinal);
if (queryStart >= 0)
{
itemIdParam = proxyBaseUrl[queryStart..];
proxyBaseUrl = proxyBaseUrl[..queryStart]; // Remove query from base URL
}
}
// 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 +429,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}{itemIdParam}";
} }
// Relative URL - rewrite to proxy // Relative URL - rewrite to proxy
return $"\n{proxyBaseUrl}/{url}"; return $"\n{proxyBaseUrl}/{url}{itemIdParam}";
}); });
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;