ApiEntryPoint.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Api.Playback;
  8. using MediaBrowser.Common.Configuration;
  9. using MediaBrowser.Controller.Configuration;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.MediaEncoding;
  12. using MediaBrowser.Controller.Net;
  13. using MediaBrowser.Controller.Plugins;
  14. using MediaBrowser.Controller.Session;
  15. using MediaBrowser.Model.Configuration;
  16. using MediaBrowser.Model.Diagnostics;
  17. using MediaBrowser.Model.Dto;
  18. using MediaBrowser.Model.IO;
  19. using MediaBrowser.Model.Session;
  20. using MediaBrowser.Model.Threading;
  21. using Microsoft.Extensions.Logging;
  22. namespace MediaBrowser.Api
  23. {
  24. /// <summary>
  25. /// Class ServerEntryPoint
  26. /// </summary>
  27. public class ApiEntryPoint : IServerEntryPoint
  28. {
  29. /// <summary>
  30. /// The instance
  31. /// </summary>
  32. public static ApiEntryPoint Instance;
  33. /// <summary>
  34. /// Gets or sets the logger.
  35. /// </summary>
  36. /// <value>The logger.</value>
  37. internal ILogger Logger { get; private set; }
  38. internal IHttpResultFactory ResultFactory { get; private set; }
  39. /// <summary>
  40. /// The application paths
  41. /// </summary>
  42. private readonly IServerConfigurationManager _config;
  43. private readonly ISessionManager _sessionManager;
  44. private readonly IFileSystem _fileSystem;
  45. private readonly IMediaSourceManager _mediaSourceManager;
  46. public readonly ITimerFactory TimerFactory;
  47. public readonly IProcessFactory ProcessFactory;
  48. /// <summary>
  49. /// The active transcoding jobs
  50. /// </summary>
  51. private readonly List<TranscodingJob> _activeTranscodingJobs = new List<TranscodingJob>();
  52. private readonly Dictionary<string, SemaphoreSlim> _transcodingLocks =
  53. new Dictionary<string, SemaphoreSlim>();
  54. /// <summary>
  55. /// Initializes a new instance of the <see cref="ApiEntryPoint" /> class.
  56. /// </summary>
  57. /// <param name="logger">The logger.</param>
  58. /// <param name="sessionManager">The session manager.</param>
  59. /// <param name="config">The configuration.</param>
  60. /// <param name="fileSystem">The file system.</param>
  61. /// <param name="mediaSourceManager">The media source manager.</param>
  62. public ApiEntryPoint(ILogger logger, ISessionManager sessionManager, IServerConfigurationManager config, IFileSystem fileSystem, IMediaSourceManager mediaSourceManager, ITimerFactory timerFactory, IProcessFactory processFactory, IHttpResultFactory resultFactory)
  63. {
  64. Logger = logger;
  65. _sessionManager = sessionManager;
  66. _config = config;
  67. _fileSystem = fileSystem;
  68. _mediaSourceManager = mediaSourceManager;
  69. TimerFactory = timerFactory;
  70. ProcessFactory = processFactory;
  71. ResultFactory = resultFactory;
  72. Instance = this;
  73. _sessionManager.PlaybackProgress += _sessionManager_PlaybackProgress;
  74. _sessionManager.PlaybackStart += _sessionManager_PlaybackStart;
  75. }
  76. public static string[] Split(string value, char separator, bool removeEmpty)
  77. {
  78. if (string.IsNullOrWhiteSpace(value))
  79. {
  80. return Array.Empty<string>();
  81. }
  82. if (removeEmpty)
  83. {
  84. return value.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries);
  85. }
  86. return value.Split(separator);
  87. }
  88. public SemaphoreSlim GetTranscodingLock(string outputPath)
  89. {
  90. lock (_transcodingLocks)
  91. {
  92. if (!_transcodingLocks.TryGetValue(outputPath, out SemaphoreSlim result))
  93. {
  94. result = new SemaphoreSlim(1, 1);
  95. _transcodingLocks[outputPath] = result;
  96. }
  97. return result;
  98. }
  99. }
  100. private void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e)
  101. {
  102. if (!string.IsNullOrWhiteSpace(e.PlaySessionId))
  103. {
  104. PingTranscodingJob(e.PlaySessionId, e.IsPaused);
  105. }
  106. }
  107. void _sessionManager_PlaybackProgress(object sender, PlaybackProgressEventArgs e)
  108. {
  109. if (!string.IsNullOrWhiteSpace(e.PlaySessionId))
  110. {
  111. PingTranscodingJob(e.PlaySessionId, e.IsPaused);
  112. }
  113. }
  114. /// <summary>
  115. /// Runs this instance.
  116. /// </summary>
  117. public Task RunAsync()
  118. {
  119. try
  120. {
  121. DeleteEncodedMediaCache();
  122. }
  123. catch (FileNotFoundException)
  124. {
  125. // Don't clutter the log
  126. }
  127. catch (IOException)
  128. {
  129. // Don't clutter the log
  130. }
  131. catch (Exception ex)
  132. {
  133. Logger.LogError(ex, "Error deleting encoded media cache");
  134. }
  135. return Task.CompletedTask;
  136. }
  137. public EncodingOptions GetEncodingOptions()
  138. {
  139. return ConfigurationManagerExtensions.GetConfiguration<EncodingOptions>(_config, "encoding");
  140. }
  141. /// <summary>
  142. /// Deletes the encoded media cache.
  143. /// </summary>
  144. private void DeleteEncodedMediaCache()
  145. {
  146. var path = _config.ApplicationPaths.TranscodingTempPath;
  147. foreach (var file in _fileSystem.GetFilePaths(path, true))
  148. {
  149. _fileSystem.DeleteFile(file);
  150. }
  151. }
  152. /// <summary>
  153. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  154. /// </summary>
  155. public void Dispose()
  156. {
  157. Dispose(true);
  158. GC.SuppressFinalize(this);
  159. }
  160. /// <summary>
  161. /// Releases unmanaged and - optionally - managed resources.
  162. /// </summary>
  163. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  164. protected virtual void Dispose(bool dispose)
  165. {
  166. var list = _activeTranscodingJobs.ToList();
  167. var jobCount = list.Count;
  168. Parallel.ForEach(list, j => KillTranscodingJob(j, false, path => true));
  169. // Try to allow for some time to kill the ffmpeg processes and delete the partial stream files
  170. if (jobCount > 0)
  171. {
  172. var task = Task.Delay(1000);
  173. Task.WaitAll(task);
  174. }
  175. }
  176. /// <summary>
  177. /// Called when [transcode beginning].
  178. /// </summary>
  179. /// <param name="path">The path.</param>
  180. /// <param name="playSessionId">The play session identifier.</param>
  181. /// <param name="liveStreamId">The live stream identifier.</param>
  182. /// <param name="transcodingJobId">The transcoding job identifier.</param>
  183. /// <param name="type">The type.</param>
  184. /// <param name="process">The process.</param>
  185. /// <param name="deviceId">The device id.</param>
  186. /// <param name="state">The state.</param>
  187. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  188. /// <returns>TranscodingJob.</returns>
  189. public TranscodingJob OnTranscodeBeginning(string path,
  190. string playSessionId,
  191. string liveStreamId,
  192. string transcodingJobId,
  193. TranscodingJobType type,
  194. IProcess process,
  195. string deviceId,
  196. StreamState state,
  197. CancellationTokenSource cancellationTokenSource)
  198. {
  199. lock (_activeTranscodingJobs)
  200. {
  201. var job = new TranscodingJob(Logger, TimerFactory)
  202. {
  203. Type = type,
  204. Path = path,
  205. Process = process,
  206. ActiveRequestCount = 1,
  207. DeviceId = deviceId,
  208. CancellationTokenSource = cancellationTokenSource,
  209. Id = transcodingJobId,
  210. PlaySessionId = playSessionId,
  211. LiveStreamId = liveStreamId,
  212. MediaSource = state.MediaSource
  213. };
  214. _activeTranscodingJobs.Add(job);
  215. ReportTranscodingProgress(job, state, null, null, null, null, null);
  216. return job;
  217. }
  218. }
  219. public void ReportTranscodingProgress(TranscodingJob job, StreamState state, TimeSpan? transcodingPosition, float? framerate, double? percentComplete, long? bytesTranscoded, int? bitRate)
  220. {
  221. var ticks = transcodingPosition.HasValue ? transcodingPosition.Value.Ticks : (long?)null;
  222. if (job != null)
  223. {
  224. job.Framerate = framerate;
  225. job.CompletionPercentage = percentComplete;
  226. job.TranscodingPositionTicks = ticks;
  227. job.BytesTranscoded = bytesTranscoded;
  228. job.BitRate = bitRate;
  229. }
  230. var deviceId = state.Request.DeviceId;
  231. if (!string.IsNullOrWhiteSpace(deviceId))
  232. {
  233. var audioCodec = state.ActualOutputAudioCodec;
  234. var videoCodec = state.ActualOutputVideoCodec;
  235. _sessionManager.ReportTranscodingInfo(deviceId, new TranscodingInfo
  236. {
  237. Bitrate = bitRate ?? state.TotalOutputBitrate,
  238. AudioCodec = audioCodec,
  239. VideoCodec = videoCodec,
  240. Container = state.OutputContainer,
  241. Framerate = framerate,
  242. CompletionPercentage = percentComplete,
  243. Width = state.OutputWidth,
  244. Height = state.OutputHeight,
  245. AudioChannels = state.OutputAudioChannels,
  246. IsAudioDirect = string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase),
  247. IsVideoDirect = string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase),
  248. TranscodeReasons = state.TranscodeReasons
  249. });
  250. }
  251. }
  252. /// <summary>
  253. /// <summary>
  254. /// The progressive
  255. /// </summary>
  256. /// Called when [transcode failed to start].
  257. /// </summary>
  258. /// <param name="path">The path.</param>
  259. /// <param name="type">The type.</param>
  260. /// <param name="state">The state.</param>
  261. public void OnTranscodeFailedToStart(string path, TranscodingJobType type, StreamState state)
  262. {
  263. lock (_activeTranscodingJobs)
  264. {
  265. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
  266. if (job != null)
  267. {
  268. _activeTranscodingJobs.Remove(job);
  269. }
  270. }
  271. lock (_transcodingLocks)
  272. {
  273. _transcodingLocks.Remove(path);
  274. }
  275. if (!string.IsNullOrWhiteSpace(state.Request.DeviceId))
  276. {
  277. _sessionManager.ClearTranscodingInfo(state.Request.DeviceId);
  278. }
  279. }
  280. /// <summary>
  281. /// Determines whether [has active transcoding job] [the specified path].
  282. /// </summary>
  283. /// <param name="path">The path.</param>
  284. /// <param name="type">The type.</param>
  285. /// <returns><c>true</c> if [has active transcoding job] [the specified path]; otherwise, <c>false</c>.</returns>
  286. public bool HasActiveTranscodingJob(string path, TranscodingJobType type)
  287. {
  288. return GetTranscodingJob(path, type) != null;
  289. }
  290. public TranscodingJob GetTranscodingJob(string path, TranscodingJobType type)
  291. {
  292. lock (_activeTranscodingJobs)
  293. {
  294. return _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
  295. }
  296. }
  297. public TranscodingJob GetTranscodingJob(string playSessionId)
  298. {
  299. lock (_activeTranscodingJobs)
  300. {
  301. return _activeTranscodingJobs.FirstOrDefault(j => string.Equals(j.PlaySessionId, playSessionId, StringComparison.OrdinalIgnoreCase));
  302. }
  303. }
  304. /// <summary>
  305. /// Called when [transcode begin request].
  306. /// </summary>
  307. /// <param name="path">The path.</param>
  308. /// <param name="type">The type.</param>
  309. public TranscodingJob OnTranscodeBeginRequest(string path, TranscodingJobType type)
  310. {
  311. lock (_activeTranscodingJobs)
  312. {
  313. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
  314. if (job == null)
  315. {
  316. return null;
  317. }
  318. OnTranscodeBeginRequest(job);
  319. return job;
  320. }
  321. }
  322. public void OnTranscodeBeginRequest(TranscodingJob job)
  323. {
  324. job.ActiveRequestCount++;
  325. if (string.IsNullOrWhiteSpace(job.PlaySessionId) || job.Type == TranscodingJobType.Progressive)
  326. {
  327. job.StopKillTimer();
  328. }
  329. }
  330. public void OnTranscodeEndRequest(TranscodingJob job)
  331. {
  332. job.ActiveRequestCount--;
  333. //Logger.LogDebug("OnTranscodeEndRequest job.ActiveRequestCount={0}", job.ActiveRequestCount);
  334. if (job.ActiveRequestCount <= 0)
  335. {
  336. PingTimer(job, false);
  337. }
  338. }
  339. internal void PingTranscodingJob(string playSessionId, bool? isUserPaused)
  340. {
  341. if (string.IsNullOrEmpty(playSessionId))
  342. {
  343. throw new ArgumentNullException(nameof(playSessionId));
  344. }
  345. //Logger.LogDebug("PingTranscodingJob PlaySessionId={0} isUsedPaused: {1}", playSessionId, isUserPaused);
  346. List<TranscodingJob> jobs;
  347. lock (_activeTranscodingJobs)
  348. {
  349. // This is really only needed for HLS.
  350. // Progressive streams can stop on their own reliably
  351. jobs = _activeTranscodingJobs.Where(j => string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase)).ToList();
  352. }
  353. foreach (var job in jobs)
  354. {
  355. if (isUserPaused.HasValue)
  356. {
  357. //Logger.LogDebug("Setting job.IsUserPaused to {0}. jobId: {1}", isUserPaused, job.Id);
  358. job.IsUserPaused = isUserPaused.Value;
  359. }
  360. PingTimer(job, true);
  361. }
  362. }
  363. private void PingTimer(TranscodingJob job, bool isProgressCheckIn)
  364. {
  365. if (job.HasExited)
  366. {
  367. job.StopKillTimer();
  368. return;
  369. }
  370. var timerDuration = 10000;
  371. if (job.Type != TranscodingJobType.Progressive)
  372. {
  373. timerDuration = 60000;
  374. }
  375. job.PingTimeout = timerDuration;
  376. job.LastPingDate = DateTime.UtcNow;
  377. // Don't start the timer for playback checkins with progressive streaming
  378. if (job.Type != TranscodingJobType.Progressive || !isProgressCheckIn)
  379. {
  380. job.StartKillTimer(OnTranscodeKillTimerStopped);
  381. }
  382. else
  383. {
  384. job.ChangeKillTimerIfStarted();
  385. }
  386. }
  387. /// <summary>
  388. /// Called when [transcode kill timer stopped].
  389. /// </summary>
  390. /// <param name="state">The state.</param>
  391. private void OnTranscodeKillTimerStopped(object state)
  392. {
  393. var job = (TranscodingJob)state;
  394. if (!job.HasExited && job.Type != TranscodingJobType.Progressive)
  395. {
  396. var timeSinceLastPing = (DateTime.UtcNow - job.LastPingDate).TotalMilliseconds;
  397. if (timeSinceLastPing < job.PingTimeout)
  398. {
  399. job.StartKillTimer(OnTranscodeKillTimerStopped, job.PingTimeout);
  400. return;
  401. }
  402. }
  403. Logger.LogInformation("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
  404. KillTranscodingJob(job, true, path => true).GetAwaiter().GetResult();
  405. }
  406. /// <summary>
  407. /// Kills the single transcoding job.
  408. /// </summary>
  409. /// <param name="deviceId">The device id.</param>
  410. /// <param name="playSessionId">The play session identifier.</param>
  411. /// <param name="deleteFiles">The delete files.</param>
  412. /// <returns>Task.</returns>
  413. internal Task KillTranscodingJobs(string deviceId, string playSessionId, Func<string, bool> deleteFiles)
  414. {
  415. return KillTranscodingJobs(j =>
  416. {
  417. if (!string.IsNullOrWhiteSpace(playSessionId))
  418. {
  419. return string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase);
  420. }
  421. return string.Equals(deviceId, j.DeviceId, StringComparison.OrdinalIgnoreCase);
  422. }, deleteFiles);
  423. }
  424. /// <summary>
  425. /// Kills the transcoding jobs.
  426. /// </summary>
  427. /// <param name="killJob">The kill job.</param>
  428. /// <param name="deleteFiles">The delete files.</param>
  429. /// <returns>Task.</returns>
  430. private Task KillTranscodingJobs(Func<TranscodingJob, bool> killJob, Func<string, bool> deleteFiles)
  431. {
  432. var jobs = new List<TranscodingJob>();
  433. lock (_activeTranscodingJobs)
  434. {
  435. // This is really only needed for HLS.
  436. // Progressive streams can stop on their own reliably
  437. jobs.AddRange(_activeTranscodingJobs.Where(killJob));
  438. }
  439. if (jobs.Count == 0)
  440. {
  441. return Task.CompletedTask;
  442. }
  443. IEnumerable<Task> GetKillJobs()
  444. {
  445. foreach (var job in jobs)
  446. {
  447. yield return KillTranscodingJob(job, false, deleteFiles);
  448. }
  449. }
  450. return Task.WhenAll(GetKillJobs());
  451. }
  452. /// <summary>
  453. /// Kills the transcoding job.
  454. /// </summary>
  455. /// <param name="job">The job.</param>
  456. /// <param name="closeLiveStream">if set to <c>true</c> [close live stream].</param>
  457. /// <param name="delete">The delete.</param>
  458. private async Task KillTranscodingJob(TranscodingJob job, bool closeLiveStream, Func<string, bool> delete)
  459. {
  460. job.DisposeKillTimer();
  461. Logger.LogDebug("KillTranscodingJob - JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
  462. lock (_activeTranscodingJobs)
  463. {
  464. _activeTranscodingJobs.Remove(job);
  465. if (!job.CancellationTokenSource.IsCancellationRequested)
  466. {
  467. job.CancellationTokenSource.Cancel();
  468. }
  469. }
  470. lock (_transcodingLocks)
  471. {
  472. _transcodingLocks.Remove(job.Path);
  473. }
  474. lock (job.ProcessLock)
  475. {
  476. if (job.TranscodingThrottler != null)
  477. {
  478. job.TranscodingThrottler.Stop();
  479. }
  480. var process = job.Process;
  481. var hasExited = job.HasExited;
  482. if (!hasExited)
  483. {
  484. try
  485. {
  486. Logger.LogInformation("Stopping ffmpeg process with q command for {path}", job.Path);
  487. //process.Kill();
  488. process.StandardInput.WriteLine("q");
  489. // Need to wait because killing is asynchronous
  490. if (!process.WaitForExit(5000))
  491. {
  492. Logger.LogInformation("Killing ffmpeg process for {path}", job.Path);
  493. process.Kill();
  494. }
  495. }
  496. catch (Exception ex)
  497. {
  498. Logger.LogError(ex, "Error killing transcoding job for {path}", job.Path);
  499. }
  500. }
  501. }
  502. if (delete(job.Path))
  503. {
  504. await DeletePartialStreamFiles(job.Path, job.Type, 0, 1500).ConfigureAwait(false);
  505. }
  506. if (closeLiveStream && !string.IsNullOrWhiteSpace(job.LiveStreamId))
  507. {
  508. try
  509. {
  510. await _mediaSourceManager.CloseLiveStream(job.LiveStreamId).ConfigureAwait(false);
  511. }
  512. catch (Exception ex)
  513. {
  514. Logger.LogError(ex, "Error closing live stream for {Path}", job.Path);
  515. }
  516. }
  517. }
  518. private async Task DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
  519. {
  520. if (retryCount >= 10)
  521. {
  522. return;
  523. }
  524. Logger.LogInformation("Deleting partial stream file(s) {0}", path);
  525. await Task.Delay(delayMs).ConfigureAwait(false);
  526. try
  527. {
  528. if (jobType == TranscodingJobType.Progressive)
  529. {
  530. DeleteProgressivePartialStreamFiles(path);
  531. }
  532. else
  533. {
  534. DeleteHlsPartialStreamFiles(path);
  535. }
  536. }
  537. catch (FileNotFoundException)
  538. {
  539. }
  540. catch (IOException ex)
  541. {
  542. Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path);
  543. await DeletePartialStreamFiles(path, jobType, retryCount + 1, 500).ConfigureAwait(false);
  544. }
  545. catch (Exception ex)
  546. {
  547. Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path);
  548. }
  549. }
  550. /// <summary>
  551. /// Deletes the progressive partial stream files.
  552. /// </summary>
  553. /// <param name="outputFilePath">The output file path.</param>
  554. private void DeleteProgressivePartialStreamFiles(string outputFilePath)
  555. {
  556. _fileSystem.DeleteFile(outputFilePath);
  557. }
  558. /// <summary>
  559. /// Deletes the HLS partial stream files.
  560. /// </summary>
  561. /// <param name="outputFilePath">The output file path.</param>
  562. private void DeleteHlsPartialStreamFiles(string outputFilePath)
  563. {
  564. var directory = Path.GetDirectoryName(outputFilePath);
  565. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  566. var filesToDelete = _fileSystem.GetFilePaths(directory)
  567. .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1);
  568. Exception e = null;
  569. foreach (var file in filesToDelete)
  570. {
  571. try
  572. {
  573. //Logger.LogDebug("Deleting HLS file {0}", file);
  574. _fileSystem.DeleteFile(file);
  575. }
  576. catch (FileNotFoundException)
  577. {
  578. }
  579. catch (IOException ex)
  580. {
  581. e = ex;
  582. Logger.LogError(ex, "Error deleting HLS file {path}", file);
  583. }
  584. }
  585. if (e != null)
  586. {
  587. throw e;
  588. }
  589. }
  590. }
  591. /// <summary>
  592. /// Class TranscodingJob
  593. /// </summary>
  594. public class TranscodingJob
  595. {
  596. /// <summary>
  597. /// Gets or sets the play session identifier.
  598. /// </summary>
  599. /// <value>The play session identifier.</value>
  600. public string PlaySessionId { get; set; }
  601. /// <summary>
  602. /// Gets or sets the live stream identifier.
  603. /// </summary>
  604. /// <value>The live stream identifier.</value>
  605. public string LiveStreamId { get; set; }
  606. public bool IsLiveOutput { get; set; }
  607. /// <summary>
  608. /// Gets or sets the path.
  609. /// </summary>
  610. /// <value>The path.</value>
  611. public MediaSourceInfo MediaSource { get; set; }
  612. public string Path { get; set; }
  613. /// <summary>
  614. /// Gets or sets the type.
  615. /// </summary>
  616. /// <value>The type.</value>
  617. public TranscodingJobType Type { get; set; }
  618. /// <summary>
  619. /// Gets or sets the process.
  620. /// </summary>
  621. /// <value>The process.</value>
  622. public IProcess Process { get; set; }
  623. public ILogger Logger { get; private set; }
  624. /// <summary>
  625. /// Gets or sets the active request count.
  626. /// </summary>
  627. /// <value>The active request count.</value>
  628. public int ActiveRequestCount { get; set; }
  629. /// <summary>
  630. /// Gets or sets the kill timer.
  631. /// </summary>
  632. /// <value>The kill timer.</value>
  633. private ITimer KillTimer { get; set; }
  634. private readonly ITimerFactory _timerFactory;
  635. public string DeviceId { get; set; }
  636. public CancellationTokenSource CancellationTokenSource { get; set; }
  637. public object ProcessLock = new object();
  638. public bool HasExited { get; set; }
  639. public bool IsUserPaused { get; set; }
  640. public string Id { get; set; }
  641. public float? Framerate { get; set; }
  642. public double? CompletionPercentage { get; set; }
  643. public long? BytesDownloaded { get; set; }
  644. public long? BytesTranscoded { get; set; }
  645. public int? BitRate { get; set; }
  646. public long? TranscodingPositionTicks { get; set; }
  647. public long? DownloadPositionTicks { get; set; }
  648. public TranscodingThrottler TranscodingThrottler { get; set; }
  649. private readonly object _timerLock = new object();
  650. public DateTime LastPingDate { get; set; }
  651. public int PingTimeout { get; set; }
  652. public TranscodingJob(ILogger logger, ITimerFactory timerFactory)
  653. {
  654. Logger = logger;
  655. _timerFactory = timerFactory;
  656. }
  657. public void StopKillTimer()
  658. {
  659. lock (_timerLock)
  660. {
  661. if (KillTimer != null)
  662. {
  663. KillTimer.Change(Timeout.Infinite, Timeout.Infinite);
  664. }
  665. }
  666. }
  667. public void DisposeKillTimer()
  668. {
  669. lock (_timerLock)
  670. {
  671. if (KillTimer != null)
  672. {
  673. KillTimer.Dispose();
  674. KillTimer = null;
  675. }
  676. }
  677. }
  678. public void StartKillTimer(Action<object> callback)
  679. {
  680. StartKillTimer(callback, PingTimeout);
  681. }
  682. public void StartKillTimer(Action<object> callback, int intervalMs)
  683. {
  684. if (HasExited)
  685. {
  686. return;
  687. }
  688. lock (_timerLock)
  689. {
  690. if (KillTimer == null)
  691. {
  692. //Logger.LogDebug("Starting kill timer at {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
  693. KillTimer = _timerFactory.Create(callback, this, intervalMs, Timeout.Infinite);
  694. }
  695. else
  696. {
  697. //Logger.LogDebug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
  698. KillTimer.Change(intervalMs, Timeout.Infinite);
  699. }
  700. }
  701. }
  702. public void ChangeKillTimerIfStarted()
  703. {
  704. if (HasExited)
  705. {
  706. return;
  707. }
  708. lock (_timerLock)
  709. {
  710. if (KillTimer != null)
  711. {
  712. var intervalMs = PingTimeout;
  713. //Logger.LogDebug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
  714. KillTimer.Change(intervalMs, Timeout.Infinite);
  715. }
  716. }
  717. }
  718. }
  719. }