BaseStreamingService.cs 41 KB

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