ApiEntryPoint.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. using MediaBrowser.Controller;
  2. using MediaBrowser.Controller.Plugins;
  3. using MediaBrowser.Controller.Resolvers;
  4. using MediaBrowser.Model.Logging;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.ComponentModel;
  8. using System.Diagnostics;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. namespace MediaBrowser.Api
  14. {
  15. /// <summary>
  16. /// Class ServerEntryPoint
  17. /// </summary>
  18. public class ApiEntryPoint : IServerEntryPoint
  19. {
  20. /// <summary>
  21. /// The instance
  22. /// </summary>
  23. public static ApiEntryPoint Instance;
  24. /// <summary>
  25. /// Gets or sets the logger.
  26. /// </summary>
  27. /// <value>The logger.</value>
  28. private ILogger Logger { get; set; }
  29. /// <summary>
  30. /// The application paths
  31. /// </summary>
  32. private readonly IServerApplicationPaths AppPaths;
  33. /// <summary>
  34. /// Initializes a new instance of the <see cref="ApiEntryPoint" /> class.
  35. /// </summary>
  36. /// <param name="logger">The logger.</param>
  37. /// <param name="appPaths">The application paths.</param>
  38. public ApiEntryPoint(ILogger logger, IServerApplicationPaths appPaths)
  39. {
  40. Logger = logger;
  41. AppPaths = appPaths;
  42. Instance = this;
  43. }
  44. /// <summary>
  45. /// Runs this instance.
  46. /// </summary>
  47. public void Run()
  48. {
  49. try
  50. {
  51. DeleteEncodedMediaCache();
  52. }
  53. catch (DirectoryNotFoundException)
  54. {
  55. // Don't clutter the log
  56. }
  57. catch (IOException ex)
  58. {
  59. Logger.ErrorException("Error deleting encoded media cache", ex);
  60. }
  61. }
  62. /// <summary>
  63. /// Deletes the encoded media cache.
  64. /// </summary>
  65. private void DeleteEncodedMediaCache()
  66. {
  67. foreach (var file in Directory.EnumerateFiles(AppPaths.EncodedMediaCachePath)
  68. .Where(i => EntityResolutionHelper.VideoFileExtensions.Contains(Path.GetExtension(i)))
  69. .ToList())
  70. {
  71. File.Delete(file);
  72. }
  73. }
  74. /// <summary>
  75. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  76. /// </summary>
  77. public void Dispose()
  78. {
  79. Dispose(true);
  80. GC.SuppressFinalize(this);
  81. }
  82. /// <summary>
  83. /// Releases unmanaged and - optionally - managed resources.
  84. /// </summary>
  85. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  86. protected virtual void Dispose(bool dispose)
  87. {
  88. var jobCount = _activeTranscodingJobs.Count;
  89. Parallel.ForEach(_activeTranscodingJobs.ToList(), KillTranscodingJob);
  90. // Try to allow for some time to kill the ffmpeg processes and delete the partial stream files
  91. if (jobCount > 0)
  92. {
  93. Thread.Sleep(1000);
  94. }
  95. }
  96. /// <summary>
  97. /// The active transcoding jobs
  98. /// </summary>
  99. private readonly List<TranscodingJob> _activeTranscodingJobs = new List<TranscodingJob>();
  100. /// <summary>
  101. /// Called when [transcode beginning].
  102. /// </summary>
  103. /// <param name="path">The path.</param>
  104. /// <param name="type">The type.</param>
  105. /// <param name="process">The process.</param>
  106. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  107. /// <param name="startTimeTicks">The start time ticks.</param>
  108. /// <param name="sourcePath">The source path.</param>
  109. /// <param name="deviceId">The device id.</param>
  110. public void OnTranscodeBeginning(string path, TranscodingJobType type, Process process, bool isVideo, long? startTimeTicks, string sourcePath, string deviceId)
  111. {
  112. lock (_activeTranscodingJobs)
  113. {
  114. _activeTranscodingJobs.Add(new TranscodingJob
  115. {
  116. Type = type,
  117. Path = path,
  118. Process = process,
  119. ActiveRequestCount = 1,
  120. IsVideo = isVideo,
  121. StartTimeTicks = startTimeTicks,
  122. SourcePath = sourcePath,
  123. DeviceId = deviceId
  124. });
  125. }
  126. }
  127. /// <summary>
  128. /// <summary>
  129. /// The progressive
  130. /// </summary>
  131. /// Called when [transcode failed to start].
  132. /// </summary>
  133. /// <param name="path">The path.</param>
  134. /// <param name="type">The type.</param>
  135. public void OnTranscodeFailedToStart(string path, TranscodingJobType type)
  136. {
  137. lock (_activeTranscodingJobs)
  138. {
  139. var job = _activeTranscodingJobs.First(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  140. _activeTranscodingJobs.Remove(job);
  141. }
  142. }
  143. /// <summary>
  144. /// Determines whether [has active transcoding job] [the specified path].
  145. /// </summary>
  146. /// <param name="path">The path.</param>
  147. /// <param name="type">The type.</param>
  148. /// <returns><c>true</c> if [has active transcoding job] [the specified path]; otherwise, <c>false</c>.</returns>
  149. public bool HasActiveTranscodingJob(string path, TranscodingJobType type)
  150. {
  151. lock (_activeTranscodingJobs)
  152. {
  153. return _activeTranscodingJobs.Any(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  154. }
  155. }
  156. /// <summary>
  157. /// Called when [transcode begin request].
  158. /// </summary>
  159. /// <param name="path">The path.</param>
  160. /// <param name="type">The type.</param>
  161. public void OnTranscodeBeginRequest(string path, TranscodingJobType type)
  162. {
  163. lock (_activeTranscodingJobs)
  164. {
  165. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  166. if (job == null)
  167. {
  168. return;
  169. }
  170. job.ActiveRequestCount++;
  171. if (job.KillTimer != null)
  172. {
  173. job.KillTimer.Dispose();
  174. job.KillTimer = null;
  175. }
  176. }
  177. }
  178. /// <summary>
  179. /// Called when [transcode end request].
  180. /// </summary>
  181. /// <param name="path">The path.</param>
  182. /// <param name="type">The type.</param>
  183. public void OnTranscodeEndRequest(string path, TranscodingJobType type)
  184. {
  185. lock (_activeTranscodingJobs)
  186. {
  187. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  188. if (job == null)
  189. {
  190. return;
  191. }
  192. job.ActiveRequestCount--;
  193. if (job.ActiveRequestCount == 0)
  194. {
  195. // The HLS kill timer is long - 1/2 hr. clients should use the manual kill command when stopping.
  196. var timerDuration = type == TranscodingJobType.Progressive ? 1000 : 1800000;
  197. if (job.KillTimer == null)
  198. {
  199. job.KillTimer = new Timer(OnTranscodeKillTimerStopped, job, timerDuration, Timeout.Infinite);
  200. }
  201. else
  202. {
  203. job.KillTimer.Change(timerDuration, Timeout.Infinite);
  204. }
  205. }
  206. }
  207. }
  208. /// <summary>
  209. /// Called when [transcode kill timer stopped].
  210. /// </summary>
  211. /// <param name="state">The state.</param>
  212. private void OnTranscodeKillTimerStopped(object state)
  213. {
  214. var job = (TranscodingJob)state;
  215. KillTranscodingJob(job);
  216. }
  217. /// <summary>
  218. /// Kills the single transcoding job.
  219. /// </summary>
  220. /// <param name="deviceId">The device id.</param>
  221. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  222. /// <exception cref="System.ArgumentNullException">sourcePath</exception>
  223. internal void KillTranscodingJobs(string deviceId, bool isVideo)
  224. {
  225. if (string.IsNullOrEmpty(deviceId))
  226. {
  227. throw new ArgumentNullException("deviceId");
  228. }
  229. var jobs = new List<TranscodingJob>();
  230. lock (_activeTranscodingJobs)
  231. {
  232. // This is really only needed for HLS.
  233. // Progressive streams can stop on their own reliably
  234. jobs.AddRange(_activeTranscodingJobs.Where(i => isVideo == i.IsVideo && string.Equals(deviceId, i.DeviceId, StringComparison.OrdinalIgnoreCase)));
  235. }
  236. foreach (var job in jobs)
  237. {
  238. KillTranscodingJob(job);
  239. }
  240. }
  241. /// <summary>
  242. /// Kills the transcoding job.
  243. /// </summary>
  244. /// <param name="job">The job.</param>
  245. private async void KillTranscodingJob(TranscodingJob job)
  246. {
  247. lock (_activeTranscodingJobs)
  248. {
  249. _activeTranscodingJobs.Remove(job);
  250. if (job.KillTimer != null)
  251. {
  252. job.KillTimer.Dispose();
  253. job.KillTimer = null;
  254. }
  255. }
  256. var process = job.Process;
  257. var hasExited = true;
  258. try
  259. {
  260. hasExited = process.HasExited;
  261. }
  262. catch (Exception ex)
  263. {
  264. Logger.ErrorException("Error determining if ffmpeg process has exited for {0}", ex, job.Path);
  265. }
  266. if (!hasExited)
  267. {
  268. try
  269. {
  270. Logger.Info("Killing ffmpeg process for {0}", job.Path);
  271. process.Kill();
  272. // Need to wait because killing is asynchronous
  273. process.WaitForExit(5000);
  274. }
  275. catch (Win32Exception ex)
  276. {
  277. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  278. }
  279. catch (InvalidOperationException ex)
  280. {
  281. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  282. }
  283. catch (NotSupportedException ex)
  284. {
  285. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  286. }
  287. }
  288. // Determine if it exited successfully
  289. var hasExitedSuccessfully = false;
  290. try
  291. {
  292. hasExitedSuccessfully = process.ExitCode == 0;
  293. }
  294. catch (InvalidOperationException)
  295. {
  296. }
  297. catch (NotSupportedException)
  298. {
  299. }
  300. // Dispose the process
  301. process.Dispose();
  302. // If it didn't complete successfully cleanup the partial files
  303. // Also don't cache output from resume points
  304. // Also don't cache video
  305. if (!hasExitedSuccessfully || job.StartTimeTicks.HasValue || job.IsVideo)
  306. {
  307. Logger.Info("Deleting partial stream file(s) {0}", job.Path);
  308. await Task.Delay(1500).ConfigureAwait(false);
  309. try
  310. {
  311. if (job.Type == TranscodingJobType.Progressive)
  312. {
  313. DeleteProgressivePartialStreamFiles(job.Path);
  314. }
  315. else
  316. {
  317. DeleteHlsPartialStreamFiles(job.Path);
  318. }
  319. }
  320. catch (IOException ex)
  321. {
  322. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, job.Path);
  323. }
  324. }
  325. }
  326. /// <summary>
  327. /// Deletes the progressive partial stream files.
  328. /// </summary>
  329. /// <param name="outputFilePath">The output file path.</param>
  330. private void DeleteProgressivePartialStreamFiles(string outputFilePath)
  331. {
  332. File.Delete(outputFilePath);
  333. }
  334. /// <summary>
  335. /// Deletes the HLS partial stream files.
  336. /// </summary>
  337. /// <param name="outputFilePath">The output file path.</param>
  338. private void DeleteHlsPartialStreamFiles(string outputFilePath)
  339. {
  340. var directory = Path.GetDirectoryName(outputFilePath);
  341. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  342. var filesToDelete = Directory.EnumerateFiles(directory)
  343. .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1)
  344. .ToList();
  345. foreach (var file in filesToDelete)
  346. {
  347. try
  348. {
  349. Logger.Info("Deleting HLS file {0}", file);
  350. File.Delete(file);
  351. }
  352. catch (IOException ex)
  353. {
  354. Logger.ErrorException("Error deleting HLS file {0}", ex, file);
  355. }
  356. }
  357. }
  358. }
  359. /// <summary>
  360. /// Class TranscodingJob
  361. /// </summary>
  362. public class TranscodingJob
  363. {
  364. /// <summary>
  365. /// Gets or sets the path.
  366. /// </summary>
  367. /// <value>The path.</value>
  368. public string Path { get; set; }
  369. /// <summary>
  370. /// Gets or sets the type.
  371. /// </summary>
  372. /// <value>The type.</value>
  373. public TranscodingJobType Type { get; set; }
  374. /// <summary>
  375. /// Gets or sets the process.
  376. /// </summary>
  377. /// <value>The process.</value>
  378. public Process Process { get; set; }
  379. /// <summary>
  380. /// Gets or sets the active request count.
  381. /// </summary>
  382. /// <value>The active request count.</value>
  383. public int ActiveRequestCount { get; set; }
  384. /// <summary>
  385. /// Gets or sets the kill timer.
  386. /// </summary>
  387. /// <value>The kill timer.</value>
  388. public Timer KillTimer { get; set; }
  389. public bool IsVideo { get; set; }
  390. public long? StartTimeTicks { get; set; }
  391. public string SourcePath { get; set; }
  392. public string DeviceId { get; set; }
  393. }
  394. /// <summary>
  395. /// Enum TranscodingJobType
  396. /// </summary>
  397. public enum TranscodingJobType
  398. {
  399. /// <summary>
  400. /// The progressive
  401. /// </summary>
  402. Progressive,
  403. /// <summary>
  404. /// The HLS
  405. /// </summary>
  406. Hls
  407. }
  408. }