ApiEntryPoint.cs 14 KB

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