BaseStreamingService.cs 40 KB

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