BaseStreamingService.cs 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  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.MediaEncoding.Encoder;
  26. using MediaBrowser.Model.Diagnostics;
  27. namespace MediaBrowser.Api.Playback
  28. {
  29. /// <summary>
  30. /// Class BaseStreamingService
  31. /// </summary>
  32. public abstract class BaseStreamingService : BaseApiService
  33. {
  34. /// <summary>
  35. /// Gets or sets the application paths.
  36. /// </summary>
  37. /// <value>The application paths.</value>
  38. protected IServerConfigurationManager ServerConfigurationManager { get; private set; }
  39. /// <summary>
  40. /// Gets or sets the user manager.
  41. /// </summary>
  42. /// <value>The user manager.</value>
  43. protected IUserManager UserManager { get; private set; }
  44. /// <summary>
  45. /// Gets or sets the library manager.
  46. /// </summary>
  47. /// <value>The library manager.</value>
  48. protected ILibraryManager LibraryManager { get; private set; }
  49. /// <summary>
  50. /// Gets or sets the iso manager.
  51. /// </summary>
  52. /// <value>The iso manager.</value>
  53. protected IIsoManager IsoManager { get; private set; }
  54. /// <summary>
  55. /// Gets or sets the media encoder.
  56. /// </summary>
  57. /// <value>The media encoder.</value>
  58. protected IMediaEncoder MediaEncoder { get; private set; }
  59. protected IFileSystem FileSystem { get; private set; }
  60. protected IDlnaManager DlnaManager { get; private set; }
  61. protected IDeviceManager DeviceManager { get; private set; }
  62. protected ISubtitleEncoder SubtitleEncoder { get; private set; }
  63. protected IMediaSourceManager MediaSourceManager { get; private set; }
  64. protected IZipClient ZipClient { get; private set; }
  65. protected IJsonSerializer JsonSerializer { get; private set; }
  66. public static IServerApplicationHost AppHost;
  67. public static IHttpClient HttpClient;
  68. protected IAuthorizationContext AuthorizationContext { get; private set; }
  69. protected EncodingHelper EncodingHelper { get; set; }
  70. /// <summary>
  71. /// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
  72. /// </summary>
  73. 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)
  74. {
  75. JsonSerializer = jsonSerializer;
  76. AuthorizationContext = authorizationContext;
  77. ZipClient = zipClient;
  78. MediaSourceManager = mediaSourceManager;
  79. DeviceManager = deviceManager;
  80. SubtitleEncoder = subtitleEncoder;
  81. DlnaManager = dlnaManager;
  82. FileSystem = fileSystem;
  83. ServerConfigurationManager = serverConfig;
  84. UserManager = userManager;
  85. LibraryManager = libraryManager;
  86. IsoManager = isoManager;
  87. MediaEncoder = mediaEncoder;
  88. EncodingHelper = new EncodingHelper(MediaEncoder, serverConfig, FileSystem, SubtitleEncoder);
  89. }
  90. /// <summary>
  91. /// Gets the command line arguments.
  92. /// </summary>
  93. /// <param name="outputPath">The output path.</param>
  94. /// <param name="state">The state.</param>
  95. /// <param name="isEncoding">if set to <c>true</c> [is encoding].</param>
  96. /// <returns>System.String.</returns>
  97. protected abstract string GetCommandLineArguments(string outputPath, StreamState state, bool isEncoding);
  98. /// <summary>
  99. /// Gets the type of the transcoding job.
  100. /// </summary>
  101. /// <value>The type of the transcoding job.</value>
  102. protected abstract TranscodingJobType TranscodingJobType { get; }
  103. /// <summary>
  104. /// Gets the output file extension.
  105. /// </summary>
  106. /// <param name="state">The state.</param>
  107. /// <returns>System.String.</returns>
  108. protected virtual string GetOutputFileExtension(StreamState state)
  109. {
  110. return Path.GetExtension(state.RequestedUrl);
  111. }
  112. /// <summary>
  113. /// Gets the output file path.
  114. /// </summary>
  115. /// <param name="state">The state.</param>
  116. /// <returns>System.String.</returns>
  117. private string GetOutputFilePath(StreamState state)
  118. {
  119. var folder = ServerConfigurationManager.ApplicationPaths.TranscodingTempPath;
  120. var outputFileExtension = GetOutputFileExtension(state);
  121. var data = GetCommandLineArguments("dummy\\dummy", state, false);
  122. data += "-" + (state.Request.DeviceId ?? string.Empty);
  123. data += "-" + (state.Request.PlaySessionId ?? string.Empty);
  124. var dataHash = data.GetMD5().ToString("N");
  125. if (EnableOutputInSubFolder)
  126. {
  127. return Path.Combine(folder, dataHash, dataHash + (outputFileExtension ?? string.Empty).ToLower());
  128. }
  129. return Path.Combine(folder, dataHash + (outputFileExtension ?? string.Empty).ToLower());
  130. }
  131. protected virtual bool EnableOutputInSubFolder
  132. {
  133. get { return false; }
  134. }
  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. }, false, 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(StreamState state,
  172. string outputPath,
  173. CancellationTokenSource cancellationTokenSource,
  174. string workingDirectory = null)
  175. {
  176. FileSystem.CreateDirectory(Path.GetDirectoryName(outputPath));
  177. await AcquireResources(state, cancellationTokenSource).ConfigureAwait(false);
  178. if (state.VideoRequest != null && !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  179. {
  180. var auth = AuthorizationContext.GetAuthorizationInfo(Request);
  181. if (!string.IsNullOrWhiteSpace(auth.UserId))
  182. {
  183. var user = UserManager.GetUserById(auth.UserId);
  184. if (!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 transcodingId = Guid.NewGuid().ToString("N");
  192. var commandLineArgs = GetCommandLineArguments(outputPath, state, true);
  193. var process = ApiEntryPoint.Instance.ProcessFactory.Create(new ProcessOptions
  194. {
  195. CreateNoWindow = true,
  196. UseShellExecute = false,
  197. // Must consume both stdout and stderr or deadlocks may occur
  198. //RedirectStandardOutput = true,
  199. RedirectStandardError = true,
  200. RedirectStandardInput = true,
  201. FileName = MediaEncoder.EncoderPath,
  202. Arguments = commandLineArgs,
  203. IsHidden = true,
  204. ErrorDialog = false,
  205. EnableRaisingEvents = true,
  206. WorkingDirectory = !string.IsNullOrWhiteSpace(workingDirectory) ? workingDirectory : null
  207. });
  208. var transcodingJob = ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath,
  209. state.Request.PlaySessionId,
  210. state.MediaSource.LiveStreamId,
  211. transcodingId,
  212. TranscodingJobType,
  213. process,
  214. state.Request.DeviceId,
  215. state,
  216. cancellationTokenSource);
  217. var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  218. Logger.Info(commandLineLogMessage);
  219. var logFilePrefix = "ffmpeg-transcode";
  220. if (state.VideoRequest != null && string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase) && string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
  221. {
  222. logFilePrefix = "ffmpeg-directstream";
  223. }
  224. else if (state.VideoRequest != null && string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  225. {
  226. logFilePrefix = "ffmpeg-remux";
  227. }
  228. var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + "-" + Guid.NewGuid() + ".txt");
  229. FileSystem.CreateDirectory(Path.GetDirectoryName(logFilePath));
  230. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  231. state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true);
  232. var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(Request.AbsoluteUri + Environment.NewLine + Environment.NewLine + JsonSerializer.SerializeToString(state.MediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine);
  233. await state.LogFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationTokenSource.Token).ConfigureAwait(false);
  234. process.Exited += (sender, args) => OnFfMpegProcessExited(process, transcodingJob, state);
  235. try
  236. {
  237. process.Start();
  238. }
  239. catch (Exception ex)
  240. {
  241. Logger.ErrorException("Error starting ffmpeg", ex);
  242. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType, state);
  243. throw;
  244. }
  245. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  246. //process.BeginOutputReadLine();
  247. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  248. var task = Task.Run(() => StartStreamingLog(transcodingJob, state, process.StandardError.BaseStream, state.LogFileStream));
  249. // Wait for the file to exist before proceeeding
  250. while (!FileSystem.FileExists(state.WaitForPath ?? outputPath) && !transcodingJob.HasExited)
  251. {
  252. await Task.Delay(100, cancellationTokenSource.Token).ConfigureAwait(false);
  253. }
  254. if (state.IsInputVideo && transcodingJob.Type == TranscodingJobType.Progressive && !transcodingJob.HasExited)
  255. {
  256. await Task.Delay(1000, cancellationTokenSource.Token).ConfigureAwait(false);
  257. if (state.ReadInputAtNativeFramerate && !transcodingJob.HasExited)
  258. {
  259. await Task.Delay(1500, cancellationTokenSource.Token).ConfigureAwait(false);
  260. }
  261. }
  262. if (!transcodingJob.HasExited)
  263. {
  264. StartThrottler(state, transcodingJob);
  265. }
  266. ReportUsage(state);
  267. return transcodingJob;
  268. }
  269. private void StartThrottler(StreamState state, TranscodingJob transcodingJob)
  270. {
  271. if (EnableThrottling(state))
  272. {
  273. transcodingJob.TranscodingThrottler = state.TranscodingThrottler = new TranscodingThrottler(transcodingJob, Logger, ServerConfigurationManager, ApiEntryPoint.Instance.TimerFactory, FileSystem);
  274. state.TranscodingThrottler.Start();
  275. }
  276. }
  277. private bool EnableThrottling(StreamState state)
  278. {
  279. return false;
  280. //// do not use throttling with hardware encoders
  281. //return state.InputProtocol == MediaProtocol.File &&
  282. // state.RunTimeTicks.HasValue &&
  283. // state.RunTimeTicks.Value >= TimeSpan.FromMinutes(5).Ticks &&
  284. // state.IsInputVideo &&
  285. // state.VideoType == VideoType.VideoFile &&
  286. // !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase) &&
  287. // string.Equals(GetVideoEncoder(state), "libx264", StringComparison.OrdinalIgnoreCase);
  288. }
  289. private async Task StartStreamingLog(TranscodingJob transcodingJob, StreamState state, Stream source, Stream target)
  290. {
  291. try
  292. {
  293. using (var reader = new StreamReader(source))
  294. {
  295. while (!reader.EndOfStream)
  296. {
  297. var line = await reader.ReadLineAsync().ConfigureAwait(false);
  298. ParseLogLine(line, transcodingJob, state);
  299. var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
  300. await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  301. await target.FlushAsync().ConfigureAwait(false);
  302. }
  303. }
  304. }
  305. catch (ObjectDisposedException)
  306. {
  307. // Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux
  308. }
  309. catch (Exception ex)
  310. {
  311. Logger.ErrorException("Error reading ffmpeg log", ex);
  312. }
  313. }
  314. private void ParseLogLine(string line, TranscodingJob transcodingJob, StreamState state)
  315. {
  316. float? framerate = null;
  317. double? percent = null;
  318. TimeSpan? transcodingPosition = null;
  319. long? bytesTranscoded = null;
  320. int? bitRate = null;
  321. var parts = line.Split(' ');
  322. var totalMs = state.RunTimeTicks.HasValue
  323. ? TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalMilliseconds
  324. : 0;
  325. var startMs = state.Request.StartTimeTicks.HasValue
  326. ? TimeSpan.FromTicks(state.Request.StartTimeTicks.Value).TotalMilliseconds
  327. : 0;
  328. for (var i = 0; i < parts.Length; i++)
  329. {
  330. var part = parts[i];
  331. if (string.Equals(part, "fps=", StringComparison.OrdinalIgnoreCase) &&
  332. (i + 1 < parts.Length))
  333. {
  334. var rate = parts[i + 1];
  335. float val;
  336. if (float.TryParse(rate, NumberStyles.Any, UsCulture, out val))
  337. {
  338. framerate = val;
  339. }
  340. }
  341. else if (state.RunTimeTicks.HasValue &&
  342. part.StartsWith("time=", StringComparison.OrdinalIgnoreCase))
  343. {
  344. var time = part.Split(new[] { '=' }, 2).Last();
  345. TimeSpan val;
  346. if (TimeSpan.TryParse(time, UsCulture, out val))
  347. {
  348. var currentMs = startMs + val.TotalMilliseconds;
  349. var percentVal = currentMs / totalMs;
  350. percent = 100 * percentVal;
  351. transcodingPosition = val;
  352. }
  353. }
  354. else if (part.StartsWith("size=", StringComparison.OrdinalIgnoreCase))
  355. {
  356. var size = part.Split(new[] { '=' }, 2).Last();
  357. int? scale = null;
  358. if (size.IndexOf("kb", StringComparison.OrdinalIgnoreCase) != -1)
  359. {
  360. scale = 1024;
  361. size = size.Replace("kb", string.Empty, StringComparison.OrdinalIgnoreCase);
  362. }
  363. if (scale.HasValue)
  364. {
  365. long val;
  366. if (long.TryParse(size, NumberStyles.Any, UsCulture, out val))
  367. {
  368. bytesTranscoded = val * scale.Value;
  369. }
  370. }
  371. }
  372. else if (part.StartsWith("bitrate=", StringComparison.OrdinalIgnoreCase))
  373. {
  374. var rate = part.Split(new[] { '=' }, 2).Last();
  375. int? scale = null;
  376. if (rate.IndexOf("kbits/s", StringComparison.OrdinalIgnoreCase) != -1)
  377. {
  378. scale = 1024;
  379. rate = rate.Replace("kbits/s", string.Empty, StringComparison.OrdinalIgnoreCase);
  380. }
  381. if (scale.HasValue)
  382. {
  383. float val;
  384. if (float.TryParse(rate, NumberStyles.Any, UsCulture, out val))
  385. {
  386. bitRate = (int)Math.Ceiling(val * scale.Value);
  387. }
  388. }
  389. }
  390. }
  391. if (framerate.HasValue || percent.HasValue)
  392. {
  393. ApiEntryPoint.Instance.ReportTranscodingProgress(transcodingJob, state, transcodingPosition, framerate, percent, bytesTranscoded, bitRate);
  394. }
  395. }
  396. /// <summary>
  397. /// Processes the exited.
  398. /// </summary>
  399. /// <param name="process">The process.</param>
  400. /// <param name="job">The job.</param>
  401. /// <param name="state">The state.</param>
  402. private void OnFfMpegProcessExited(IProcess process, TranscodingJob job, StreamState state)
  403. {
  404. if (job != null)
  405. {
  406. job.HasExited = true;
  407. }
  408. Logger.Debug("Disposing stream resources");
  409. state.Dispose();
  410. try
  411. {
  412. Logger.Info("FFMpeg exited with code {0}", process.ExitCode);
  413. }
  414. catch
  415. {
  416. Logger.Error("FFMpeg exited with an error.");
  417. }
  418. // This causes on exited to be called twice:
  419. //try
  420. //{
  421. // // Dispose the process
  422. // process.Dispose();
  423. //}
  424. //catch (Exception ex)
  425. //{
  426. // Logger.ErrorException("Error disposing ffmpeg.", ex);
  427. //}
  428. }
  429. /// <summary>
  430. /// Parses the parameters.
  431. /// </summary>
  432. /// <param name="request">The request.</param>
  433. private void ParseParams(StreamRequest request)
  434. {
  435. var vals = request.Params.Split(';');
  436. var videoRequest = request as VideoStreamRequest;
  437. for (var i = 0; i < vals.Length; i++)
  438. {
  439. var val = vals[i];
  440. if (string.IsNullOrWhiteSpace(val))
  441. {
  442. continue;
  443. }
  444. if (i == 0)
  445. {
  446. request.DeviceProfileId = val;
  447. }
  448. else if (i == 1)
  449. {
  450. request.DeviceId = val;
  451. }
  452. else if (i == 2)
  453. {
  454. request.MediaSourceId = val;
  455. }
  456. else if (i == 3)
  457. {
  458. request.Static = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  459. }
  460. else if (i == 4)
  461. {
  462. if (videoRequest != null)
  463. {
  464. videoRequest.VideoCodec = val;
  465. }
  466. }
  467. else if (i == 5)
  468. {
  469. request.AudioCodec = val;
  470. }
  471. else if (i == 6)
  472. {
  473. if (videoRequest != null)
  474. {
  475. videoRequest.AudioStreamIndex = int.Parse(val, UsCulture);
  476. }
  477. }
  478. else if (i == 7)
  479. {
  480. if (videoRequest != null)
  481. {
  482. videoRequest.SubtitleStreamIndex = int.Parse(val, UsCulture);
  483. }
  484. }
  485. else if (i == 8)
  486. {
  487. if (videoRequest != null)
  488. {
  489. videoRequest.VideoBitRate = int.Parse(val, UsCulture);
  490. }
  491. }
  492. else if (i == 9)
  493. {
  494. request.AudioBitRate = int.Parse(val, UsCulture);
  495. }
  496. else if (i == 10)
  497. {
  498. request.MaxAudioChannels = int.Parse(val, UsCulture);
  499. }
  500. else if (i == 11)
  501. {
  502. if (videoRequest != null)
  503. {
  504. videoRequest.MaxFramerate = float.Parse(val, UsCulture);
  505. }
  506. }
  507. else if (i == 12)
  508. {
  509. if (videoRequest != null)
  510. {
  511. videoRequest.MaxWidth = int.Parse(val, UsCulture);
  512. }
  513. }
  514. else if (i == 13)
  515. {
  516. if (videoRequest != null)
  517. {
  518. videoRequest.MaxHeight = int.Parse(val, UsCulture);
  519. }
  520. }
  521. else if (i == 14)
  522. {
  523. request.StartTimeTicks = long.Parse(val, UsCulture);
  524. }
  525. else if (i == 15)
  526. {
  527. if (videoRequest != null)
  528. {
  529. videoRequest.Level = val;
  530. }
  531. }
  532. else if (i == 16)
  533. {
  534. if (videoRequest != null)
  535. {
  536. videoRequest.MaxRefFrames = int.Parse(val, UsCulture);
  537. }
  538. }
  539. else if (i == 17)
  540. {
  541. if (videoRequest != null)
  542. {
  543. videoRequest.MaxVideoBitDepth = int.Parse(val, UsCulture);
  544. }
  545. }
  546. else if (i == 18)
  547. {
  548. if (videoRequest != null)
  549. {
  550. videoRequest.Profile = val;
  551. }
  552. }
  553. else if (i == 19)
  554. {
  555. // cabac no longer used
  556. }
  557. else if (i == 20)
  558. {
  559. request.PlaySessionId = val;
  560. }
  561. else if (i == 21)
  562. {
  563. // api_key
  564. }
  565. else if (i == 22)
  566. {
  567. request.LiveStreamId = val;
  568. }
  569. else if (i == 23)
  570. {
  571. // Duplicating ItemId because of MediaMonkey
  572. }
  573. else if (i == 24)
  574. {
  575. if (videoRequest != null)
  576. {
  577. videoRequest.CopyTimestamps = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  578. }
  579. }
  580. else if (i == 25)
  581. {
  582. if (!string.IsNullOrWhiteSpace(val) && videoRequest != null)
  583. {
  584. SubtitleDeliveryMethod method;
  585. if (Enum.TryParse(val, out method))
  586. {
  587. videoRequest.SubtitleMethod = method;
  588. }
  589. }
  590. }
  591. else if (i == 26)
  592. {
  593. request.TranscodingMaxAudioChannels = int.Parse(val, UsCulture);
  594. }
  595. else if (i == 27)
  596. {
  597. if (videoRequest != null)
  598. {
  599. videoRequest.EnableSubtitlesInManifest = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  600. }
  601. }
  602. else if (i == 28)
  603. {
  604. request.Tag = val;
  605. }
  606. else if (i == 29)
  607. {
  608. if (videoRequest != null)
  609. {
  610. videoRequest.RequireAvc = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  611. }
  612. }
  613. else if (i == 30)
  614. {
  615. request.SubtitleCodec = val;
  616. }
  617. }
  618. }
  619. /// <summary>
  620. /// Parses the dlna headers.
  621. /// </summary>
  622. /// <param name="request">The request.</param>
  623. private void ParseDlnaHeaders(StreamRequest request)
  624. {
  625. if (!request.StartTimeTicks.HasValue)
  626. {
  627. var timeSeek = GetHeader("TimeSeekRange.dlna.org");
  628. request.StartTimeTicks = ParseTimeSeekHeader(timeSeek);
  629. }
  630. }
  631. /// <summary>
  632. /// Parses the time seek header.
  633. /// </summary>
  634. private long? ParseTimeSeekHeader(string value)
  635. {
  636. if (string.IsNullOrWhiteSpace(value))
  637. {
  638. return null;
  639. }
  640. if (value.IndexOf("npt=", StringComparison.OrdinalIgnoreCase) != 0)
  641. {
  642. throw new ArgumentException("Invalid timeseek header");
  643. }
  644. value = value.Substring(4).Split(new[] { '-' }, 2)[0];
  645. if (value.IndexOf(':') == -1)
  646. {
  647. // Parses npt times in the format of '417.33'
  648. double seconds;
  649. if (double.TryParse(value, NumberStyles.Any, UsCulture, out seconds))
  650. {
  651. return TimeSpan.FromSeconds(seconds).Ticks;
  652. }
  653. throw new ArgumentException("Invalid timeseek header");
  654. }
  655. // Parses npt times in the format of '10:19:25.7'
  656. var tokens = value.Split(new[] { ':' }, 3);
  657. double secondsSum = 0;
  658. var timeFactor = 3600;
  659. foreach (var time in tokens)
  660. {
  661. double digit;
  662. if (double.TryParse(time, NumberStyles.Any, UsCulture, out digit))
  663. {
  664. secondsSum += digit * timeFactor;
  665. }
  666. else
  667. {
  668. throw new ArgumentException("Invalid timeseek header");
  669. }
  670. timeFactor /= 60;
  671. }
  672. return TimeSpan.FromSeconds(secondsSum).Ticks;
  673. }
  674. /// <summary>
  675. /// Gets the state.
  676. /// </summary>
  677. /// <param name="request">The request.</param>
  678. /// <param name="cancellationToken">The cancellation token.</param>
  679. /// <returns>StreamState.</returns>
  680. protected async Task<StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
  681. {
  682. ParseDlnaHeaders(request);
  683. if (!string.IsNullOrWhiteSpace(request.Params))
  684. {
  685. ParseParams(request);
  686. }
  687. var url = Request.PathInfo;
  688. if (string.IsNullOrEmpty(request.AudioCodec))
  689. {
  690. request.AudioCodec = EncodingHelper.InferAudioCodec(url);
  691. }
  692. var state = new StreamState(MediaSourceManager, Logger, TranscodingJobType)
  693. {
  694. Request = request,
  695. RequestedUrl = url,
  696. UserAgent = Request.UserAgent
  697. };
  698. var auth = AuthorizationContext.GetAuthorizationInfo(Request);
  699. if (!string.IsNullOrWhiteSpace(auth.UserId))
  700. {
  701. state.User = UserManager.GetUserById(auth.UserId);
  702. }
  703. //if ((Request.UserAgent ?? string.Empty).IndexOf("iphone", StringComparison.OrdinalIgnoreCase) != -1 ||
  704. // (Request.UserAgent ?? string.Empty).IndexOf("ipad", StringComparison.OrdinalIgnoreCase) != -1 ||
  705. // (Request.UserAgent ?? string.Empty).IndexOf("ipod", StringComparison.OrdinalIgnoreCase) != -1)
  706. //{
  707. // state.SegmentLength = 6;
  708. //}
  709. if (state.VideoRequest != null)
  710. {
  711. if (!string.IsNullOrWhiteSpace(state.VideoRequest.VideoCodec))
  712. {
  713. state.SupportedVideoCodecs = state.VideoRequest.VideoCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
  714. state.VideoRequest.VideoCodec = state.SupportedVideoCodecs.FirstOrDefault();
  715. }
  716. }
  717. if (!string.IsNullOrWhiteSpace(request.AudioCodec))
  718. {
  719. state.SupportedAudioCodecs = request.AudioCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
  720. state.Request.AudioCodec = state.SupportedAudioCodecs.FirstOrDefault(i => MediaEncoder.CanEncodeToAudioCodec(i))
  721. ?? state.SupportedAudioCodecs.FirstOrDefault();
  722. }
  723. if (!string.IsNullOrWhiteSpace(request.SubtitleCodec))
  724. {
  725. state.SupportedSubtitleCodecs = request.SubtitleCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
  726. state.Request.SubtitleCodec = state.SupportedSubtitleCodecs.FirstOrDefault(i => MediaEncoder.CanEncodeToSubtitleCodec(i))
  727. ?? state.SupportedSubtitleCodecs.FirstOrDefault();
  728. }
  729. var item = LibraryManager.GetItemById(request.Id);
  730. state.IsInputVideo = string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  731. MediaSourceInfo mediaSource = null;
  732. if (string.IsNullOrWhiteSpace(request.LiveStreamId))
  733. {
  734. TranscodingJob currentJob = !string.IsNullOrWhiteSpace(request.PlaySessionId) ?
  735. ApiEntryPoint.Instance.GetTranscodingJob(request.PlaySessionId)
  736. : null;
  737. if (currentJob != null)
  738. {
  739. mediaSource = currentJob.MediaSource;
  740. }
  741. if (mediaSource == null)
  742. {
  743. var mediaSources = (await MediaSourceManager.GetPlayackMediaSources(request.Id, null, false, new[] { MediaType.Audio, MediaType.Video }, cancellationToken).ConfigureAwait(false)).ToList();
  744. mediaSource = string.IsNullOrEmpty(request.MediaSourceId)
  745. ? mediaSources.First()
  746. : mediaSources.FirstOrDefault(i => string.Equals(i.Id, request.MediaSourceId));
  747. if (mediaSource == null && string.Equals(request.Id, request.MediaSourceId, StringComparison.OrdinalIgnoreCase))
  748. {
  749. mediaSource = mediaSources.First();
  750. }
  751. }
  752. }
  753. else
  754. {
  755. var liveStreamInfo = await MediaSourceManager.GetLiveStreamWithDirectStreamProvider(request.LiveStreamId, cancellationToken).ConfigureAwait(false);
  756. mediaSource = liveStreamInfo.Item1;
  757. state.DirectStreamProvider = liveStreamInfo.Item2;
  758. }
  759. var videoRequest = request as VideoStreamRequest;
  760. EncodingHelper.AttachMediaSourceInfo(state, mediaSource, url);
  761. var container = Path.GetExtension(state.RequestedUrl);
  762. if (string.IsNullOrEmpty(container))
  763. {
  764. container = request.Static ?
  765. state.InputContainer :
  766. (Path.GetExtension(GetOutputFilePath(state)) ?? string.Empty).TrimStart('.');
  767. }
  768. state.OutputContainer = (container ?? string.Empty).TrimStart('.');
  769. state.OutputAudioBitrate = EncodingHelper.GetAudioBitrateParam(state.Request, state.AudioStream);
  770. state.OutputAudioSampleRate = request.AudioSampleRate;
  771. state.OutputAudioCodec = state.Request.AudioCodec;
  772. state.OutputAudioChannels = EncodingHelper.GetNumAudioChannelsParam(state.Request, state.AudioStream, state.OutputAudioCodec);
  773. if (videoRequest != null)
  774. {
  775. state.OutputVideoCodec = state.VideoRequest.VideoCodec;
  776. state.OutputVideoBitrate = EncodingHelper.GetVideoBitrateParamValue(state.VideoRequest, state.VideoStream, state.OutputVideoCodec);
  777. if (videoRequest != null)
  778. {
  779. EncodingHelper.TryStreamCopy(state);
  780. }
  781. if (state.OutputVideoBitrate.HasValue && !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  782. {
  783. var resolution = ResolutionNormalizer.Normalize(
  784. state.VideoStream == null ? (int?)null : state.VideoStream.BitRate,
  785. state.OutputVideoBitrate.Value,
  786. state.VideoStream == null ? null : state.VideoStream.Codec,
  787. state.OutputVideoCodec,
  788. videoRequest.MaxWidth,
  789. videoRequest.MaxHeight);
  790. videoRequest.MaxWidth = resolution.MaxWidth;
  791. videoRequest.MaxHeight = resolution.MaxHeight;
  792. }
  793. ApplyDeviceProfileSettings(state);
  794. }
  795. else
  796. {
  797. ApplyDeviceProfileSettings(state);
  798. }
  799. state.OutputFilePath = GetOutputFilePath(state);
  800. return state;
  801. }
  802. private void ApplyDeviceProfileSettings(StreamState state)
  803. {
  804. var headers = Request.Headers.ToDictionary();
  805. if (!string.IsNullOrWhiteSpace(state.Request.DeviceProfileId))
  806. {
  807. state.DeviceProfile = DlnaManager.GetProfile(state.Request.DeviceProfileId);
  808. }
  809. else
  810. {
  811. if (!string.IsNullOrWhiteSpace(state.Request.DeviceId))
  812. {
  813. var caps = DeviceManager.GetCapabilities(state.Request.DeviceId);
  814. if (caps != null)
  815. {
  816. state.DeviceProfile = caps.DeviceProfile;
  817. }
  818. else
  819. {
  820. state.DeviceProfile = DlnaManager.GetProfile(headers);
  821. }
  822. }
  823. }
  824. var profile = state.DeviceProfile;
  825. if (profile == null)
  826. {
  827. // Don't use settings from the default profile.
  828. // Only use a specific profile if it was requested.
  829. return;
  830. }
  831. var audioCodec = state.ActualOutputAudioCodec;
  832. var videoCodec = state.ActualOutputVideoCodec;
  833. var mediaProfile = state.VideoRequest == null ?
  834. profile.GetAudioMediaProfile(state.OutputContainer, audioCodec, state.OutputAudioChannels, state.OutputAudioBitrate) :
  835. profile.GetVideoMediaProfile(state.OutputContainer,
  836. audioCodec,
  837. videoCodec,
  838. state.OutputWidth,
  839. state.OutputHeight,
  840. state.TargetVideoBitDepth,
  841. state.OutputVideoBitrate,
  842. state.TargetVideoProfile,
  843. state.TargetVideoLevel,
  844. state.TargetFramerate,
  845. state.TargetPacketLength,
  846. state.TargetTimestamp,
  847. state.IsTargetAnamorphic,
  848. state.TargetRefFrames,
  849. state.TargetVideoStreamCount,
  850. state.TargetAudioStreamCount,
  851. state.TargetVideoCodecTag,
  852. state.IsTargetAVC);
  853. if (mediaProfile != null)
  854. {
  855. state.MimeType = mediaProfile.MimeType;
  856. }
  857. if (!state.Request.Static)
  858. {
  859. var transcodingProfile = state.VideoRequest == null ?
  860. profile.GetAudioTranscodingProfile(state.OutputContainer, audioCodec) :
  861. profile.GetVideoTranscodingProfile(state.OutputContainer, audioCodec, videoCodec);
  862. if (transcodingProfile != null)
  863. {
  864. state.EstimateContentLength = transcodingProfile.EstimateContentLength;
  865. state.EnableMpegtsM2TsMode = transcodingProfile.EnableMpegtsM2TsMode;
  866. state.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
  867. if (state.VideoRequest != null)
  868. {
  869. state.VideoRequest.CopyTimestamps = transcodingProfile.CopyTimestamps;
  870. state.VideoRequest.EnableSubtitlesInManifest = transcodingProfile.EnableSubtitlesInManifest;
  871. }
  872. }
  873. }
  874. }
  875. private async void ReportUsage(StreamState state)
  876. {
  877. try
  878. {
  879. await ReportUsageInternal(state).ConfigureAwait(false);
  880. }
  881. catch
  882. {
  883. }
  884. }
  885. private Task ReportUsageInternal(StreamState state)
  886. {
  887. if (!ServerConfigurationManager.Configuration.EnableAnonymousUsageReporting)
  888. {
  889. return Task.FromResult(true);
  890. }
  891. if (!MediaEncoder.IsDefaultEncoderPath)
  892. {
  893. return Task.FromResult(true);
  894. }
  895. return Task.FromResult(true);
  896. //var dict = new Dictionary<string, string>();
  897. //var outputAudio = GetAudioEncoder(state);
  898. //if (!string.IsNullOrWhiteSpace(outputAudio))
  899. //{
  900. // dict["outputAudio"] = outputAudio;
  901. //}
  902. //var outputVideo = GetVideoEncoder(state);
  903. //if (!string.IsNullOrWhiteSpace(outputVideo))
  904. //{
  905. // dict["outputVideo"] = outputVideo;
  906. //}
  907. //if (ServerConfigurationManager.Configuration.CodecsUsed.Contains(outputAudio ?? string.Empty, StringComparer.OrdinalIgnoreCase) &&
  908. // ServerConfigurationManager.Configuration.CodecsUsed.Contains(outputVideo ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  909. //{
  910. // return Task.FromResult(true);
  911. //}
  912. //dict["id"] = AppHost.SystemId;
  913. //dict["type"] = state.VideoRequest == null ? "Audio" : "Video";
  914. //var audioStream = state.AudioStream;
  915. //if (audioStream != null && !string.IsNullOrWhiteSpace(audioStream.Codec))
  916. //{
  917. // dict["inputAudio"] = audioStream.Codec;
  918. //}
  919. //var videoStream = state.VideoStream;
  920. //if (videoStream != null && !string.IsNullOrWhiteSpace(videoStream.Codec))
  921. //{
  922. // dict["inputVideo"] = videoStream.Codec;
  923. //}
  924. //var cert = GetType().Assembly.GetModules().First().GetSignerCertificate();
  925. //if (cert != null)
  926. //{
  927. // dict["assemblySig"] = cert.GetCertHashString();
  928. // dict["certSubject"] = cert.Subject ?? string.Empty;
  929. // dict["certIssuer"] = cert.Issuer ?? string.Empty;
  930. //}
  931. //else
  932. //{
  933. // return Task.FromResult(true);
  934. //}
  935. //if (state.SupportedAudioCodecs.Count > 0)
  936. //{
  937. // dict["supportedAudioCodecs"] = string.Join(",", state.SupportedAudioCodecs.ToArray());
  938. //}
  939. //var auth = AuthorizationContext.GetAuthorizationInfo(Request);
  940. //dict["appName"] = auth.Client ?? string.Empty;
  941. //dict["appVersion"] = auth.Version ?? string.Empty;
  942. //dict["device"] = auth.Device ?? string.Empty;
  943. //dict["deviceId"] = auth.DeviceId ?? string.Empty;
  944. //dict["context"] = "streaming";
  945. ////Logger.Info(JsonSerializer.SerializeToString(dict));
  946. //if (!ServerConfigurationManager.Configuration.CodecsUsed.Contains(outputAudio ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  947. //{
  948. // var list = ServerConfigurationManager.Configuration.CodecsUsed.ToList();
  949. // list.Add(outputAudio);
  950. // ServerConfigurationManager.Configuration.CodecsUsed = list.ToArray();
  951. //}
  952. //if (!ServerConfigurationManager.Configuration.CodecsUsed.Contains(outputVideo ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  953. //{
  954. // var list = ServerConfigurationManager.Configuration.CodecsUsed.ToList();
  955. // list.Add(outputVideo);
  956. // ServerConfigurationManager.Configuration.CodecsUsed = list.ToArray();
  957. //}
  958. //ServerConfigurationManager.SaveConfiguration();
  959. ////Logger.Info(JsonSerializer.SerializeToString(dict));
  960. //var options = new HttpRequestOptions()
  961. //{
  962. // Url = "https://mb3admin.com/admin/service/transcoding/report",
  963. // CancellationToken = CancellationToken.None,
  964. // LogRequest = false,
  965. // LogErrors = false,
  966. // BufferContent = false
  967. //};
  968. //options.RequestContent = JsonSerializer.SerializeToString(dict);
  969. //options.RequestContentType = "application/json";
  970. //return HttpClient.Post(options);
  971. }
  972. /// <summary>
  973. /// Adds the dlna headers.
  974. /// </summary>
  975. /// <param name="state">The state.</param>
  976. /// <param name="responseHeaders">The response headers.</param>
  977. /// <param name="isStaticallyStreamed">if set to <c>true</c> [is statically streamed].</param>
  978. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  979. protected void AddDlnaHeaders(StreamState state, IDictionary<string, string> responseHeaders, bool isStaticallyStreamed)
  980. {
  981. var profile = state.DeviceProfile;
  982. var transferMode = GetHeader("transferMode.dlna.org");
  983. responseHeaders["transferMode.dlna.org"] = string.IsNullOrEmpty(transferMode) ? "Streaming" : transferMode;
  984. responseHeaders["realTimeInfo.dlna.org"] = "DLNA.ORG_TLAG=*";
  985. if (string.Equals(GetHeader("getMediaInfo.sec"), "1", StringComparison.OrdinalIgnoreCase))
  986. {
  987. if (state.RunTimeTicks.HasValue)
  988. {
  989. var ms = TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalMilliseconds;
  990. responseHeaders["MediaInfo.sec"] = string.Format("SEC_Duration={0};", Convert.ToInt32(ms).ToString(CultureInfo.InvariantCulture));
  991. }
  992. }
  993. if (state.RunTimeTicks.HasValue && !isStaticallyStreamed && profile != null)
  994. {
  995. AddTimeSeekResponseHeaders(state, responseHeaders);
  996. }
  997. if (profile == null)
  998. {
  999. profile = DlnaManager.GetDefaultProfile();
  1000. }
  1001. var audioCodec = state.ActualOutputAudioCodec;
  1002. if (state.VideoRequest == null)
  1003. {
  1004. responseHeaders["contentFeatures.dlna.org"] = new ContentFeatureBuilder(profile)
  1005. .BuildAudioHeader(
  1006. state.OutputContainer,
  1007. audioCodec,
  1008. state.OutputAudioBitrate,
  1009. state.OutputAudioSampleRate,
  1010. state.OutputAudioChannels,
  1011. isStaticallyStreamed,
  1012. state.RunTimeTicks,
  1013. state.TranscodeSeekInfo
  1014. );
  1015. }
  1016. else
  1017. {
  1018. var videoCodec = state.ActualOutputVideoCodec;
  1019. responseHeaders["contentFeatures.dlna.org"] = new ContentFeatureBuilder(profile)
  1020. .BuildVideoHeader(
  1021. state.OutputContainer,
  1022. videoCodec,
  1023. audioCodec,
  1024. state.OutputWidth,
  1025. state.OutputHeight,
  1026. state.TargetVideoBitDepth,
  1027. state.OutputVideoBitrate,
  1028. state.TargetTimestamp,
  1029. isStaticallyStreamed,
  1030. state.RunTimeTicks,
  1031. state.TargetVideoProfile,
  1032. state.TargetVideoLevel,
  1033. state.TargetFramerate,
  1034. state.TargetPacketLength,
  1035. state.TranscodeSeekInfo,
  1036. state.IsTargetAnamorphic,
  1037. state.TargetRefFrames,
  1038. state.TargetVideoStreamCount,
  1039. state.TargetAudioStreamCount,
  1040. state.TargetVideoCodecTag,
  1041. state.IsTargetAVC
  1042. ).FirstOrDefault() ?? string.Empty;
  1043. }
  1044. foreach (var item in responseHeaders)
  1045. {
  1046. Request.Response.AddHeader(item.Key, item.Value);
  1047. }
  1048. }
  1049. private void AddTimeSeekResponseHeaders(StreamState state, IDictionary<string, string> responseHeaders)
  1050. {
  1051. var runtimeSeconds = TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds.ToString(UsCulture);
  1052. var startSeconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds.ToString(UsCulture);
  1053. responseHeaders["TimeSeekRange.dlna.org"] = string.Format("npt={0}-{1}/{1}", startSeconds, runtimeSeconds);
  1054. responseHeaders["X-AvailableSeekRange"] = string.Format("1 npt={0}-{1}", startSeconds, runtimeSeconds);
  1055. }
  1056. }
  1057. }