ApiEntryPoint.cs 15 KB

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