BaseStreamingService.cs 40 KB

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