BaseStreamingService.cs 41 KB

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