BaseStreamingService.cs 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Common.Extensions;
  10. using MediaBrowser.Common.Net;
  11. using MediaBrowser.Controller;
  12. using MediaBrowser.Controller.Configuration;
  13. using MediaBrowser.Controller.Devices;
  14. using MediaBrowser.Controller.Dlna;
  15. using MediaBrowser.Controller.Library;
  16. using MediaBrowser.Controller.MediaEncoding;
  17. using MediaBrowser.Controller.Net;
  18. using MediaBrowser.Model.Configuration;
  19. using MediaBrowser.Model.Diagnostics;
  20. using MediaBrowser.Model.Dlna;
  21. using MediaBrowser.Model.Dto;
  22. using MediaBrowser.Model.Entities;
  23. using MediaBrowser.Model.IO;
  24. using MediaBrowser.Model.MediaInfo;
  25. using MediaBrowser.Model.Serialization;
  26. using Microsoft.Extensions.Logging;
  27. namespace MediaBrowser.Api.Playback
  28. {
  29. /// <summary>
  30. /// Class BaseStreamingService
  31. /// </summary>
  32. public abstract class BaseStreamingService : BaseApiService
  33. {
  34. /// <summary>
  35. /// Gets or sets the application paths.
  36. /// </summary>
  37. /// <value>The application paths.</value>
  38. protected IServerConfigurationManager ServerConfigurationManager { get; private set; }
  39. /// <summary>
  40. /// Gets or sets the user manager.
  41. /// </summary>
  42. /// <value>The user manager.</value>
  43. protected IUserManager UserManager { get; private set; }
  44. /// <summary>
  45. /// Gets or sets the library manager.
  46. /// </summary>
  47. /// <value>The library manager.</value>
  48. protected ILibraryManager LibraryManager { get; private set; }
  49. /// <summary>
  50. /// Gets or sets the iso manager.
  51. /// </summary>
  52. /// <value>The iso manager.</value>
  53. protected IIsoManager IsoManager { get; private set; }
  54. /// <summary>
  55. /// Gets or sets the media encoder.
  56. /// </summary>
  57. /// <value>The media encoder.</value>
  58. protected IMediaEncoder MediaEncoder { get; private set; }
  59. protected IFileSystem FileSystem { get; private set; }
  60. protected IDlnaManager DlnaManager { get; private set; }
  61. protected IDeviceManager DeviceManager { get; private set; }
  62. protected ISubtitleEncoder SubtitleEncoder { get; private set; }
  63. protected IMediaSourceManager MediaSourceManager { get; private set; }
  64. protected IZipClient ZipClient { get; private set; }
  65. protected IJsonSerializer JsonSerializer { get; private set; }
  66. public static IServerApplicationHost AppHost;
  67. public static IHttpClient HttpClient;
  68. protected IAuthorizationContext AuthorizationContext { get; private set; }
  69. protected EncodingHelper EncodingHelper { get; set; }
  70. /// <summary>
  71. /// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
  72. /// </summary>
  73. protected BaseStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer, IAuthorizationContext authorizationContext)
  74. {
  75. JsonSerializer = jsonSerializer;
  76. AuthorizationContext = authorizationContext;
  77. ZipClient = zipClient;
  78. MediaSourceManager = mediaSourceManager;
  79. DeviceManager = deviceManager;
  80. SubtitleEncoder = subtitleEncoder;
  81. DlnaManager = dlnaManager;
  82. FileSystem = fileSystem;
  83. ServerConfigurationManager = serverConfig;
  84. UserManager = userManager;
  85. LibraryManager = libraryManager;
  86. IsoManager = isoManager;
  87. MediaEncoder = mediaEncoder;
  88. EncodingHelper = new EncodingHelper(MediaEncoder, FileSystem, SubtitleEncoder);
  89. }
  90. /// <summary>
  91. /// Gets the command line arguments.
  92. /// </summary>
  93. protected abstract string GetCommandLineArguments(string outputPath, EncodingOptions encodingOptions, StreamState state, bool isEncoding);
  94. /// <summary>
  95. /// Gets the type of the transcoding job.
  96. /// </summary>
  97. /// <value>The type of the transcoding job.</value>
  98. protected abstract TranscodingJobType TranscodingJobType { get; }
  99. /// <summary>
  100. /// Gets the output file extension.
  101. /// </summary>
  102. /// <param name="state">The state.</param>
  103. /// <returns>System.String.</returns>
  104. protected virtual string GetOutputFileExtension(StreamState state)
  105. {
  106. return Path.GetExtension(state.RequestedUrl);
  107. }
  108. /// <summary>
  109. /// Gets the output file path.
  110. /// </summary>
  111. private string GetOutputFilePath(StreamState state, EncodingOptions encodingOptions, string outputFileExtension)
  112. {
  113. var folder = ServerConfigurationManager.ApplicationPaths.TranscodingTempPath;
  114. var data = GetCommandLineArguments("dummy\\dummy", encodingOptions, state, false);
  115. data += "-" + (state.Request.DeviceId ?? string.Empty);
  116. data += "-" + (state.Request.PlaySessionId ?? string.Empty);
  117. var dataHash = data.GetMD5().ToString("N");
  118. if (EnableOutputInSubFolder)
  119. {
  120. return Path.Combine(folder, dataHash, dataHash + (outputFileExtension ?? string.Empty).ToLower());
  121. }
  122. return Path.Combine(folder, dataHash + (outputFileExtension ?? string.Empty).ToLower());
  123. }
  124. protected virtual bool EnableOutputInSubFolder => false;
  125. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  126. protected virtual string GetDefaultH264Preset()
  127. {
  128. return "superfast";
  129. }
  130. private async Task AcquireResources(StreamState state, CancellationTokenSource cancellationTokenSource)
  131. {
  132. if (state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  133. {
  134. state.IsoMount = await IsoManager.Mount(state.MediaPath, cancellationTokenSource.Token).ConfigureAwait(false);
  135. }
  136. if (state.MediaSource.RequiresOpening && string.IsNullOrWhiteSpace(state.Request.LiveStreamId))
  137. {
  138. var liveStreamResponse = await MediaSourceManager.OpenLiveStream(new LiveStreamRequest
  139. {
  140. OpenToken = state.MediaSource.OpenToken
  141. }, cancellationTokenSource.Token).ConfigureAwait(false);
  142. EncodingHelper.AttachMediaSourceInfo(state, liveStreamResponse.MediaSource, state.RequestedUrl);
  143. if (state.VideoRequest != null)
  144. {
  145. EncodingHelper.TryStreamCopy(state);
  146. }
  147. }
  148. if (state.MediaSource.BufferMs.HasValue)
  149. {
  150. await Task.Delay(state.MediaSource.BufferMs.Value, cancellationTokenSource.Token).ConfigureAwait(false);
  151. }
  152. }
  153. /// <summary>
  154. /// Starts the FFMPEG.
  155. /// </summary>
  156. /// <param name="state">The state.</param>
  157. /// <param name="outputPath">The output path.</param>
  158. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  159. /// <param name="workingDirectory">The working directory.</param>
  160. /// <returns>Task.</returns>
  161. protected async Task<TranscodingJob> StartFfMpeg(StreamState state,
  162. string outputPath,
  163. CancellationTokenSource cancellationTokenSource,
  164. string workingDirectory = null)
  165. {
  166. FileSystem.CreateDirectory(FileSystem.GetDirectoryName(outputPath));
  167. await AcquireResources(state, cancellationTokenSource).ConfigureAwait(false);
  168. if (state.VideoRequest != null && !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  169. {
  170. var auth = AuthorizationContext.GetAuthorizationInfo(Request);
  171. if (auth.User != null)
  172. {
  173. if (!auth.User.Policy.EnableVideoPlaybackTranscoding)
  174. {
  175. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType, state);
  176. throw new ArgumentException("User does not have access to video transcoding");
  177. }
  178. }
  179. }
  180. var encodingOptions = ApiEntryPoint.Instance.GetEncodingOptions();
  181. var transcodingId = Guid.NewGuid().ToString("N");
  182. var commandLineArgs = GetCommandLineArguments(outputPath, encodingOptions, state, true);
  183. var process = ApiEntryPoint.Instance.ProcessFactory.Create(new ProcessOptions
  184. {
  185. CreateNoWindow = true,
  186. UseShellExecute = false,
  187. // Must consume both stdout and stderr or deadlocks may occur
  188. //RedirectStandardOutput = true,
  189. RedirectStandardError = true,
  190. RedirectStandardInput = true,
  191. FileName = MediaEncoder.EncoderPath,
  192. Arguments = commandLineArgs,
  193. IsHidden = true,
  194. ErrorDialog = false,
  195. EnableRaisingEvents = true,
  196. WorkingDirectory = !string.IsNullOrWhiteSpace(workingDirectory) ? workingDirectory : null
  197. });
  198. var transcodingJob = ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath,
  199. state.Request.PlaySessionId,
  200. state.MediaSource.LiveStreamId,
  201. transcodingId,
  202. TranscodingJobType,
  203. process,
  204. state.Request.DeviceId,
  205. state,
  206. cancellationTokenSource);
  207. var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  208. Logger.LogInformation(commandLineLogMessage);
  209. var logFilePrefix = "ffmpeg-transcode";
  210. if (state.VideoRequest != null && string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase) && string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
  211. {
  212. logFilePrefix = "ffmpeg-directstream";
  213. }
  214. else if (state.VideoRequest != null && string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  215. {
  216. logFilePrefix = "ffmpeg-remux";
  217. }
  218. var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + "-" + Guid.NewGuid() + ".txt");
  219. FileSystem.CreateDirectory(FileSystem.GetDirectoryName(logFilePath));
  220. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  221. state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true);
  222. var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(Request.AbsoluteUri + Environment.NewLine + Environment.NewLine + JsonSerializer.SerializeToString(state.MediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine);
  223. await state.LogFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationTokenSource.Token).ConfigureAwait(false);
  224. process.Exited += (sender, args) => OnFfMpegProcessExited(process, transcodingJob, state);
  225. try
  226. {
  227. process.Start();
  228. }
  229. catch (Exception ex)
  230. {
  231. Logger.LogError(ex, "Error starting ffmpeg");
  232. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType, state);
  233. throw;
  234. }
  235. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  236. //process.BeginOutputReadLine();
  237. state.TranscodingJob = transcodingJob;
  238. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  239. new JobLogger(Logger).StartStreamingLog(state, process.StandardError.BaseStream, state.LogFileStream);
  240. // Wait for the file to exist before proceeeding
  241. while (!FileSystem.FileExists(state.WaitForPath ?? outputPath) && !transcodingJob.HasExited)
  242. {
  243. await Task.Delay(100, cancellationTokenSource.Token).ConfigureAwait(false);
  244. }
  245. if (state.IsInputVideo && transcodingJob.Type == TranscodingJobType.Progressive && !transcodingJob.HasExited)
  246. {
  247. await Task.Delay(1000, cancellationTokenSource.Token).ConfigureAwait(false);
  248. if (state.ReadInputAtNativeFramerate && !transcodingJob.HasExited)
  249. {
  250. await Task.Delay(1500, cancellationTokenSource.Token).ConfigureAwait(false);
  251. }
  252. }
  253. if (!transcodingJob.HasExited)
  254. {
  255. StartThrottler(state, transcodingJob);
  256. }
  257. return transcodingJob;
  258. }
  259. private void StartThrottler(StreamState state, TranscodingJob transcodingJob)
  260. {
  261. if (EnableThrottling(state))
  262. {
  263. transcodingJob.TranscodingThrottler = state.TranscodingThrottler = new TranscodingThrottler(transcodingJob, Logger, ServerConfigurationManager, ApiEntryPoint.Instance.TimerFactory, FileSystem);
  264. state.TranscodingThrottler.Start();
  265. }
  266. }
  267. private bool EnableThrottling(StreamState state)
  268. {
  269. return false;
  270. //// do not use throttling with hardware encoders
  271. //return state.InputProtocol == MediaProtocol.File &&
  272. // state.RunTimeTicks.HasValue &&
  273. // state.RunTimeTicks.Value >= TimeSpan.FromMinutes(5).Ticks &&
  274. // state.IsInputVideo &&
  275. // state.VideoType == VideoType.VideoFile &&
  276. // !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase) &&
  277. // string.Equals(GetVideoEncoder(state), "libx264", StringComparison.OrdinalIgnoreCase);
  278. }
  279. /// <summary>
  280. /// Processes the exited.
  281. /// </summary>
  282. /// <param name="process">The process.</param>
  283. /// <param name="job">The job.</param>
  284. /// <param name="state">The state.</param>
  285. private void OnFfMpegProcessExited(IProcess process, TranscodingJob job, StreamState state)
  286. {
  287. if (job != null)
  288. {
  289. job.HasExited = true;
  290. }
  291. Logger.LogDebug("Disposing stream resources");
  292. state.Dispose();
  293. try
  294. {
  295. Logger.LogInformation("FFMpeg exited with code {0}", process.ExitCode);
  296. }
  297. catch
  298. {
  299. Logger.LogError("FFMpeg exited with an error.");
  300. }
  301. // This causes on exited to be called twice:
  302. //try
  303. //{
  304. // // Dispose the process
  305. // process.Dispose();
  306. //}
  307. //catch (Exception ex)
  308. //{
  309. // Logger.LogError(ex, "Error disposing ffmpeg.");
  310. //}
  311. }
  312. /// <summary>
  313. /// Parses the parameters.
  314. /// </summary>
  315. /// <param name="request">The request.</param>
  316. private void ParseParams(StreamRequest request)
  317. {
  318. var vals = request.Params.Split(';');
  319. var videoRequest = request as VideoStreamRequest;
  320. for (var i = 0; i < vals.Length; i++)
  321. {
  322. var val = vals[i];
  323. if (string.IsNullOrWhiteSpace(val))
  324. {
  325. continue;
  326. }
  327. if (i == 0)
  328. {
  329. request.DeviceProfileId = val;
  330. }
  331. else if (i == 1)
  332. {
  333. request.DeviceId = val;
  334. }
  335. else if (i == 2)
  336. {
  337. request.MediaSourceId = val;
  338. }
  339. else if (i == 3)
  340. {
  341. request.Static = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  342. }
  343. else if (i == 4)
  344. {
  345. if (videoRequest != null)
  346. {
  347. videoRequest.VideoCodec = val;
  348. }
  349. }
  350. else if (i == 5)
  351. {
  352. request.AudioCodec = val;
  353. }
  354. else if (i == 6)
  355. {
  356. if (videoRequest != null)
  357. {
  358. videoRequest.AudioStreamIndex = int.Parse(val, UsCulture);
  359. }
  360. }
  361. else if (i == 7)
  362. {
  363. if (videoRequest != null)
  364. {
  365. videoRequest.SubtitleStreamIndex = int.Parse(val, UsCulture);
  366. }
  367. }
  368. else if (i == 8)
  369. {
  370. if (videoRequest != null)
  371. {
  372. videoRequest.VideoBitRate = int.Parse(val, UsCulture);
  373. }
  374. }
  375. else if (i == 9)
  376. {
  377. request.AudioBitRate = int.Parse(val, UsCulture);
  378. }
  379. else if (i == 10)
  380. {
  381. request.MaxAudioChannels = int.Parse(val, UsCulture);
  382. }
  383. else if (i == 11)
  384. {
  385. if (videoRequest != null)
  386. {
  387. videoRequest.MaxFramerate = float.Parse(val, UsCulture);
  388. }
  389. }
  390. else if (i == 12)
  391. {
  392. if (videoRequest != null)
  393. {
  394. videoRequest.MaxWidth = int.Parse(val, UsCulture);
  395. }
  396. }
  397. else if (i == 13)
  398. {
  399. if (videoRequest != null)
  400. {
  401. videoRequest.MaxHeight = int.Parse(val, UsCulture);
  402. }
  403. }
  404. else if (i == 14)
  405. {
  406. request.StartTimeTicks = long.Parse(val, UsCulture);
  407. }
  408. else if (i == 15)
  409. {
  410. if (videoRequest != null)
  411. {
  412. videoRequest.Level = val;
  413. }
  414. }
  415. else if (i == 16)
  416. {
  417. if (videoRequest != null)
  418. {
  419. videoRequest.MaxRefFrames = int.Parse(val, UsCulture);
  420. }
  421. }
  422. else if (i == 17)
  423. {
  424. if (videoRequest != null)
  425. {
  426. videoRequest.MaxVideoBitDepth = int.Parse(val, UsCulture);
  427. }
  428. }
  429. else if (i == 18)
  430. {
  431. if (videoRequest != null)
  432. {
  433. videoRequest.Profile = val;
  434. }
  435. }
  436. else if (i == 19)
  437. {
  438. // cabac no longer used
  439. }
  440. else if (i == 20)
  441. {
  442. request.PlaySessionId = val;
  443. }
  444. else if (i == 21)
  445. {
  446. // api_key
  447. }
  448. else if (i == 22)
  449. {
  450. request.LiveStreamId = val;
  451. }
  452. else if (i == 23)
  453. {
  454. // Duplicating ItemId because of MediaMonkey
  455. }
  456. else if (i == 24)
  457. {
  458. if (videoRequest != null)
  459. {
  460. videoRequest.CopyTimestamps = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  461. }
  462. }
  463. else if (i == 25)
  464. {
  465. if (!string.IsNullOrWhiteSpace(val) && videoRequest != null)
  466. {
  467. if (Enum.TryParse(val, out SubtitleDeliveryMethod method))
  468. {
  469. videoRequest.SubtitleMethod = method;
  470. }
  471. }
  472. }
  473. else if (i == 26)
  474. {
  475. request.TranscodingMaxAudioChannels = int.Parse(val, UsCulture);
  476. }
  477. else if (i == 27)
  478. {
  479. if (videoRequest != null)
  480. {
  481. videoRequest.EnableSubtitlesInManifest = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  482. }
  483. }
  484. else if (i == 28)
  485. {
  486. request.Tag = val;
  487. }
  488. else if (i == 29)
  489. {
  490. if (videoRequest != null)
  491. {
  492. videoRequest.RequireAvc = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  493. }
  494. }
  495. else if (i == 30)
  496. {
  497. request.SubtitleCodec = val;
  498. }
  499. else if (i == 31)
  500. {
  501. if (videoRequest != null)
  502. {
  503. videoRequest.RequireNonAnamorphic = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  504. }
  505. }
  506. else if (i == 32)
  507. {
  508. if (videoRequest != null)
  509. {
  510. videoRequest.DeInterlace = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  511. }
  512. }
  513. else if (i == 33)
  514. {
  515. request.TranscodeReasons = val;
  516. }
  517. }
  518. }
  519. /// <summary>
  520. /// Parses query parameters as StreamOptions
  521. /// <summary>
  522. /// <param name="request">The stream request.</param>
  523. private void ParseStreamOptions(StreamRequest request)
  524. {
  525. foreach (var param in Request.QueryString)
  526. {
  527. if (char.IsLower(param.Name[0]))
  528. {
  529. // This was probably not parsed initially and should be a StreamOptions
  530. // TODO: This should be incorporated either in the lower framework for parsing requests
  531. // or the generated URL should correctly serialize it
  532. request.StreamOptions[param.Name] = param.Value;
  533. }
  534. }
  535. }
  536. /// <summary>
  537. /// Parses the dlna headers.
  538. /// </summary>
  539. /// <param name="request">The request.</param>
  540. private void ParseDlnaHeaders(StreamRequest request)
  541. {
  542. if (!request.StartTimeTicks.HasValue)
  543. {
  544. var timeSeek = GetHeader("TimeSeekRange.dlna.org");
  545. request.StartTimeTicks = ParseTimeSeekHeader(timeSeek);
  546. }
  547. }
  548. /// <summary>
  549. /// Parses the time seek header.
  550. /// </summary>
  551. private long? ParseTimeSeekHeader(string value)
  552. {
  553. if (string.IsNullOrWhiteSpace(value))
  554. {
  555. return null;
  556. }
  557. if (value.IndexOf("npt=", StringComparison.OrdinalIgnoreCase) != 0)
  558. {
  559. throw new ArgumentException("Invalid timeseek header");
  560. }
  561. value = value.Substring(4).Split(new[] { '-' }, 2)[0];
  562. if (value.IndexOf(':') == -1)
  563. {
  564. // Parses npt times in the format of '417.33'
  565. if (double.TryParse(value, NumberStyles.Any, UsCulture, out var seconds))
  566. {
  567. return TimeSpan.FromSeconds(seconds).Ticks;
  568. }
  569. throw new ArgumentException("Invalid timeseek header");
  570. }
  571. // Parses npt times in the format of '10:19:25.7'
  572. var tokens = value.Split(new[] { ':' }, 3);
  573. double secondsSum = 0;
  574. var timeFactor = 3600;
  575. foreach (var time in tokens)
  576. {
  577. if (double.TryParse(time, NumberStyles.Any, UsCulture, out var digit))
  578. {
  579. secondsSum += digit * timeFactor;
  580. }
  581. else
  582. {
  583. throw new ArgumentException("Invalid timeseek header");
  584. }
  585. timeFactor /= 60;
  586. }
  587. return TimeSpan.FromSeconds(secondsSum).Ticks;
  588. }
  589. /// <summary>
  590. /// Gets the state.
  591. /// </summary>
  592. /// <param name="request">The request.</param>
  593. /// <param name="cancellationToken">The cancellation token.</param>
  594. /// <returns>StreamState.</returns>
  595. protected async Task<StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
  596. {
  597. ParseDlnaHeaders(request);
  598. if (!string.IsNullOrWhiteSpace(request.Params))
  599. {
  600. ParseParams(request);
  601. }
  602. ParseStreamOptions(request);
  603. var url = Request.PathInfo;
  604. if (string.IsNullOrEmpty(request.AudioCodec))
  605. {
  606. request.AudioCodec = EncodingHelper.InferAudioCodec(url);
  607. }
  608. var enableDlnaHeaders = !string.IsNullOrWhiteSpace(request.Params) /*||
  609. string.Equals(Request.Headers.Get("GetContentFeatures.DLNA.ORG"), "1", StringComparison.OrdinalIgnoreCase)*/;
  610. var state = new StreamState(MediaSourceManager, Logger, TranscodingJobType)
  611. {
  612. Request = request,
  613. RequestedUrl = url,
  614. UserAgent = Request.UserAgent,
  615. EnableDlnaHeaders = enableDlnaHeaders
  616. };
  617. var auth = AuthorizationContext.GetAuthorizationInfo(Request);
  618. if (!auth.UserId.Equals(Guid.Empty))
  619. {
  620. state.User = UserManager.GetUserById(auth.UserId);
  621. }
  622. //if ((Request.UserAgent ?? string.Empty).IndexOf("iphone", StringComparison.OrdinalIgnoreCase) != -1 ||
  623. // (Request.UserAgent ?? string.Empty).IndexOf("ipad", StringComparison.OrdinalIgnoreCase) != -1 ||
  624. // (Request.UserAgent ?? string.Empty).IndexOf("ipod", StringComparison.OrdinalIgnoreCase) != -1)
  625. //{
  626. // state.SegmentLength = 6;
  627. //}
  628. if (state.VideoRequest != null)
  629. {
  630. if (!string.IsNullOrWhiteSpace(state.VideoRequest.VideoCodec))
  631. {
  632. state.SupportedVideoCodecs = state.VideoRequest.VideoCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
  633. state.VideoRequest.VideoCodec = state.SupportedVideoCodecs.FirstOrDefault();
  634. }
  635. }
  636. if (!string.IsNullOrWhiteSpace(request.AudioCodec))
  637. {
  638. state.SupportedAudioCodecs = request.AudioCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
  639. state.Request.AudioCodec = state.SupportedAudioCodecs.FirstOrDefault(i => MediaEncoder.CanEncodeToAudioCodec(i))
  640. ?? state.SupportedAudioCodecs.FirstOrDefault();
  641. }
  642. if (!string.IsNullOrWhiteSpace(request.SubtitleCodec))
  643. {
  644. state.SupportedSubtitleCodecs = request.SubtitleCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
  645. state.Request.SubtitleCodec = state.SupportedSubtitleCodecs.FirstOrDefault(i => MediaEncoder.CanEncodeToSubtitleCodec(i))
  646. ?? state.SupportedSubtitleCodecs.FirstOrDefault();
  647. }
  648. var item = LibraryManager.GetItemById(request.Id);
  649. state.IsInputVideo = string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  650. //var primaryImage = item.GetImageInfo(ImageType.Primary, 0) ??
  651. // item.Parents.Select(i => i.GetImageInfo(ImageType.Primary, 0)).FirstOrDefault(i => i != null);
  652. //if (primaryImage != null)
  653. //{
  654. // state.AlbumCoverPath = primaryImage.Path;
  655. //}
  656. MediaSourceInfo mediaSource = null;
  657. if (string.IsNullOrWhiteSpace(request.LiveStreamId))
  658. {
  659. var currentJob = !string.IsNullOrWhiteSpace(request.PlaySessionId) ?
  660. ApiEntryPoint.Instance.GetTranscodingJob(request.PlaySessionId)
  661. : null;
  662. if (currentJob != null)
  663. {
  664. mediaSource = currentJob.MediaSource;
  665. }
  666. if (mediaSource == null)
  667. {
  668. var mediaSources = (await MediaSourceManager.GetPlayackMediaSources(LibraryManager.GetItemById(request.Id), null, false, false, cancellationToken).ConfigureAwait(false)).ToList();
  669. mediaSource = string.IsNullOrEmpty(request.MediaSourceId)
  670. ? mediaSources.First()
  671. : mediaSources.FirstOrDefault(i => string.Equals(i.Id, request.MediaSourceId));
  672. if (mediaSource == null && request.MediaSourceId.Equals(request.Id))
  673. {
  674. mediaSource = mediaSources.First();
  675. }
  676. }
  677. }
  678. else
  679. {
  680. var liveStreamInfo = await MediaSourceManager.GetLiveStreamWithDirectStreamProvider(request.LiveStreamId, cancellationToken).ConfigureAwait(false);
  681. mediaSource = liveStreamInfo.Item1;
  682. state.DirectStreamProvider = liveStreamInfo.Item2;
  683. }
  684. var videoRequest = request as VideoStreamRequest;
  685. EncodingHelper.AttachMediaSourceInfo(state, mediaSource, url);
  686. var container = Path.GetExtension(state.RequestedUrl);
  687. if (string.IsNullOrEmpty(container))
  688. {
  689. container = request.Container;
  690. }
  691. if (string.IsNullOrEmpty(container))
  692. {
  693. container = request.Static ?
  694. StreamBuilder.NormalizeMediaSourceFormatIntoSingleContainer(state.InputContainer, state.MediaPath, null, DlnaProfileType.Audio) :
  695. GetOutputFileExtension(state);
  696. }
  697. state.OutputContainer = (container ?? string.Empty).TrimStart('.');
  698. state.OutputAudioBitrate = EncodingHelper.GetAudioBitrateParam(state.Request, state.AudioStream);
  699. state.OutputAudioCodec = state.Request.AudioCodec;
  700. state.OutputAudioChannels = EncodingHelper.GetNumAudioChannelsParam(state, state.AudioStream, state.OutputAudioCodec);
  701. if (videoRequest != null)
  702. {
  703. state.OutputVideoCodec = state.VideoRequest.VideoCodec;
  704. state.OutputVideoBitrate = EncodingHelper.GetVideoBitrateParamValue(state.VideoRequest, state.VideoStream, state.OutputVideoCodec);
  705. if (videoRequest != null)
  706. {
  707. EncodingHelper.TryStreamCopy(state);
  708. }
  709. if (state.OutputVideoBitrate.HasValue && !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  710. {
  711. var resolution = ResolutionNormalizer.Normalize(
  712. state.VideoStream == null ? (int?)null : state.VideoStream.BitRate,
  713. state.VideoStream == null ? (int?)null : state.VideoStream.Width,
  714. state.VideoStream == null ? (int?)null : state.VideoStream.Height,
  715. state.OutputVideoBitrate.Value,
  716. state.VideoStream == null ? null : state.VideoStream.Codec,
  717. state.OutputVideoCodec,
  718. videoRequest.MaxWidth,
  719. videoRequest.MaxHeight);
  720. videoRequest.MaxWidth = resolution.MaxWidth;
  721. videoRequest.MaxHeight = resolution.MaxHeight;
  722. }
  723. ApplyDeviceProfileSettings(state);
  724. }
  725. else
  726. {
  727. ApplyDeviceProfileSettings(state);
  728. }
  729. var ext = string.IsNullOrWhiteSpace(state.OutputContainer)
  730. ? GetOutputFileExtension(state)
  731. : ("." + state.OutputContainer);
  732. var encodingOptions = ApiEntryPoint.Instance.GetEncodingOptions();
  733. state.OutputFilePath = GetOutputFilePath(state, encodingOptions, ext);
  734. return state;
  735. }
  736. private void ApplyDeviceProfileSettings(StreamState state)
  737. {
  738. var headers = Request.Headers.ToDictionary();
  739. if (!string.IsNullOrWhiteSpace(state.Request.DeviceProfileId))
  740. {
  741. state.DeviceProfile = DlnaManager.GetProfile(state.Request.DeviceProfileId);
  742. }
  743. else
  744. {
  745. if (!string.IsNullOrWhiteSpace(state.Request.DeviceId))
  746. {
  747. var caps = DeviceManager.GetCapabilities(state.Request.DeviceId);
  748. if (caps != null)
  749. {
  750. state.DeviceProfile = caps.DeviceProfile;
  751. }
  752. else
  753. {
  754. state.DeviceProfile = DlnaManager.GetProfile(headers);
  755. }
  756. }
  757. }
  758. var profile = state.DeviceProfile;
  759. if (profile == null)
  760. {
  761. // Don't use settings from the default profile.
  762. // Only use a specific profile if it was requested.
  763. return;
  764. }
  765. var audioCodec = state.ActualOutputAudioCodec;
  766. var videoCodec = state.ActualOutputVideoCodec;
  767. var mediaProfile = state.VideoRequest == null ?
  768. profile.GetAudioMediaProfile(state.OutputContainer, audioCodec, state.OutputAudioChannels, state.OutputAudioBitrate, state.OutputAudioSampleRate, state.OutputAudioBitDepth) :
  769. profile.GetVideoMediaProfile(state.OutputContainer,
  770. audioCodec,
  771. videoCodec,
  772. state.OutputWidth,
  773. state.OutputHeight,
  774. state.TargetVideoBitDepth,
  775. state.OutputVideoBitrate,
  776. state.TargetVideoProfile,
  777. state.TargetVideoLevel,
  778. state.TargetFramerate,
  779. state.TargetPacketLength,
  780. state.TargetTimestamp,
  781. state.IsTargetAnamorphic,
  782. state.IsTargetInterlaced,
  783. state.TargetRefFrames,
  784. state.TargetVideoStreamCount,
  785. state.TargetAudioStreamCount,
  786. state.TargetVideoCodecTag,
  787. state.IsTargetAVC);
  788. if (mediaProfile != null)
  789. {
  790. state.MimeType = mediaProfile.MimeType;
  791. }
  792. if (!state.Request.Static)
  793. {
  794. var transcodingProfile = state.VideoRequest == null ?
  795. profile.GetAudioTranscodingProfile(state.OutputContainer, audioCodec) :
  796. profile.GetVideoTranscodingProfile(state.OutputContainer, audioCodec, videoCodec);
  797. if (transcodingProfile != null)
  798. {
  799. state.EstimateContentLength = transcodingProfile.EstimateContentLength;
  800. //state.EnableMpegtsM2TsMode = transcodingProfile.EnableMpegtsM2TsMode;
  801. state.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
  802. if (state.VideoRequest != null)
  803. {
  804. state.VideoRequest.CopyTimestamps = transcodingProfile.CopyTimestamps;
  805. state.VideoRequest.EnableSubtitlesInManifest = transcodingProfile.EnableSubtitlesInManifest;
  806. }
  807. }
  808. }
  809. }
  810. /// <summary>
  811. /// Adds the dlna headers.
  812. /// </summary>
  813. /// <param name="state">The state.</param>
  814. /// <param name="responseHeaders">The response headers.</param>
  815. /// <param name="isStaticallyStreamed">if set to <c>true</c> [is statically streamed].</param>
  816. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  817. protected void AddDlnaHeaders(StreamState state, IDictionary<string, string> responseHeaders, bool isStaticallyStreamed)
  818. {
  819. if (!state.EnableDlnaHeaders)
  820. {
  821. return;
  822. }
  823. var profile = state.DeviceProfile;
  824. var transferMode = GetHeader("transferMode.dlna.org");
  825. responseHeaders["transferMode.dlna.org"] = string.IsNullOrEmpty(transferMode) ? "Streaming" : transferMode;
  826. responseHeaders["realTimeInfo.dlna.org"] = "DLNA.ORG_TLAG=*";
  827. if (string.Equals(GetHeader("getMediaInfo.sec"), "1", StringComparison.OrdinalIgnoreCase))
  828. {
  829. if (state.RunTimeTicks.HasValue)
  830. {
  831. var ms = TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalMilliseconds;
  832. responseHeaders["MediaInfo.sec"] = string.Format("SEC_Duration={0};", Convert.ToInt32(ms).ToString(CultureInfo.InvariantCulture));
  833. }
  834. }
  835. if (state.RunTimeTicks.HasValue && !isStaticallyStreamed && profile != null)
  836. {
  837. AddTimeSeekResponseHeaders(state, responseHeaders);
  838. }
  839. if (profile == null)
  840. {
  841. profile = DlnaManager.GetDefaultProfile();
  842. }
  843. var audioCodec = state.ActualOutputAudioCodec;
  844. if (state.VideoRequest == null)
  845. {
  846. responseHeaders["contentFeatures.dlna.org"] = new ContentFeatureBuilder(profile)
  847. .BuildAudioHeader(
  848. state.OutputContainer,
  849. audioCodec,
  850. state.OutputAudioBitrate,
  851. state.OutputAudioSampleRate,
  852. state.OutputAudioChannels,
  853. state.OutputAudioBitDepth,
  854. isStaticallyStreamed,
  855. state.RunTimeTicks,
  856. state.TranscodeSeekInfo
  857. );
  858. }
  859. else
  860. {
  861. var videoCodec = state.ActualOutputVideoCodec;
  862. responseHeaders["contentFeatures.dlna.org"] = new ContentFeatureBuilder(profile)
  863. .BuildVideoHeader(
  864. state.OutputContainer,
  865. videoCodec,
  866. audioCodec,
  867. state.OutputWidth,
  868. state.OutputHeight,
  869. state.TargetVideoBitDepth,
  870. state.OutputVideoBitrate,
  871. state.TargetTimestamp,
  872. isStaticallyStreamed,
  873. state.RunTimeTicks,
  874. state.TargetVideoProfile,
  875. state.TargetVideoLevel,
  876. state.TargetFramerate,
  877. state.TargetPacketLength,
  878. state.TranscodeSeekInfo,
  879. state.IsTargetAnamorphic,
  880. state.IsTargetInterlaced,
  881. state.TargetRefFrames,
  882. state.TargetVideoStreamCount,
  883. state.TargetAudioStreamCount,
  884. state.TargetVideoCodecTag,
  885. state.IsTargetAVC
  886. ).FirstOrDefault() ?? string.Empty;
  887. }
  888. foreach (var item in responseHeaders)
  889. {
  890. Request.Response.AddHeader(item.Key, item.Value);
  891. }
  892. }
  893. private void AddTimeSeekResponseHeaders(StreamState state, IDictionary<string, string> responseHeaders)
  894. {
  895. var runtimeSeconds = TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds.ToString(UsCulture);
  896. var startSeconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds.ToString(UsCulture);
  897. responseHeaders["TimeSeekRange.dlna.org"] = string.Format("npt={0}-{1}/{1}", startSeconds, runtimeSeconds);
  898. responseHeaders["X-AvailableSeekRange"] = string.Format("1 npt={0}-{1}", startSeconds, runtimeSeconds);
  899. }
  900. }
  901. }