BaseStreamingService.cs 41 KB

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