ApiEntryPoint.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. using System.IO;
  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.Linq;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. namespace MediaBrowser.Api
  12. {
  13. /// <summary>
  14. /// Class ServerEntryPoint
  15. /// </summary>
  16. public class ApiEntryPoint : IServerEntryPoint
  17. {
  18. /// <summary>
  19. /// The instance
  20. /// </summary>
  21. public static ApiEntryPoint Instance;
  22. /// <summary>
  23. /// Gets or sets the logger.
  24. /// </summary>
  25. /// <value>The logger.</value>
  26. private ILogger Logger { get; set; }
  27. /// <summary>
  28. /// Initializes a new instance of the <see cref="ApiEntryPoint" /> class.
  29. /// </summary>
  30. /// <param name="logger">The logger.</param>
  31. public ApiEntryPoint(ILogger logger)
  32. {
  33. Logger = logger;
  34. Instance = this;
  35. }
  36. /// <summary>
  37. /// Runs this instance.
  38. /// </summary>
  39. public void Run()
  40. {
  41. }
  42. /// <summary>
  43. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  44. /// </summary>
  45. public void Dispose()
  46. {
  47. Dispose(true);
  48. GC.SuppressFinalize(this);
  49. }
  50. /// <summary>
  51. /// Releases unmanaged and - optionally - managed resources.
  52. /// </summary>
  53. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  54. protected virtual void Dispose(bool dispose)
  55. {
  56. var jobCount = _activeTranscodingJobs.Count;
  57. Parallel.ForEach(_activeTranscodingJobs, OnTranscodeKillTimerStopped);
  58. // Try to allow for some time to kill the ffmpeg processes and delete the partial stream files
  59. if (jobCount > 0)
  60. {
  61. Thread.Sleep(1000);
  62. }
  63. }
  64. /// <summary>
  65. /// The active transcoding jobs
  66. /// </summary>
  67. private readonly List<TranscodingJob> _activeTranscodingJobs = new List<TranscodingJob>();
  68. /// <summary>
  69. /// Called when [transcode beginning].
  70. /// </summary>
  71. /// <param name="path">The path.</param>
  72. /// <param name="type">The type.</param>
  73. /// <param name="process">The process.</param>
  74. public void OnTranscodeBeginning(string path, TranscodingJobType type, Process process)
  75. {
  76. lock (_activeTranscodingJobs)
  77. {
  78. _activeTranscodingJobs.Add(new TranscodingJob
  79. {
  80. Type = type,
  81. Path = path,
  82. Process = process,
  83. ActiveRequestCount = 1
  84. });
  85. }
  86. }
  87. /// <summary>
  88. /// <summary>
  89. /// The progressive
  90. /// </summary>
  91. /// Called when [transcode failed to start].
  92. /// </summary>
  93. /// <param name="path">The path.</param>
  94. /// <param name="type">The type.</param>
  95. public void OnTranscodeFailedToStart(string path, TranscodingJobType type)
  96. {
  97. lock (_activeTranscodingJobs)
  98. {
  99. var job = _activeTranscodingJobs.First(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  100. _activeTranscodingJobs.Remove(job);
  101. }
  102. }
  103. /// <summary>
  104. /// Determines whether [has active transcoding job] [the specified path].
  105. /// </summary>
  106. /// <param name="path">The path.</param>
  107. /// <param name="type">The type.</param>
  108. /// <returns><c>true</c> if [has active transcoding job] [the specified path]; otherwise, <c>false</c>.</returns>
  109. public bool HasActiveTranscodingJob(string path, TranscodingJobType type)
  110. {
  111. lock (_activeTranscodingJobs)
  112. {
  113. return _activeTranscodingJobs.Any(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  114. }
  115. }
  116. /// <summary>
  117. /// Called when [transcode begin request].
  118. /// </summary>
  119. /// <param name="path">The path.</param>
  120. /// <param name="type">The type.</param>
  121. public void OnTranscodeBeginRequest(string path, TranscodingJobType type)
  122. {
  123. lock (_activeTranscodingJobs)
  124. {
  125. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  126. if (job == null)
  127. {
  128. return;
  129. }
  130. job.ActiveRequestCount++;
  131. if (job.KillTimer != null)
  132. {
  133. job.KillTimer.Dispose();
  134. job.KillTimer = null;
  135. }
  136. }
  137. }
  138. /// <summary>
  139. /// Called when [transcode end request].
  140. /// </summary>
  141. /// <param name="path">The path.</param>
  142. /// <param name="type">The type.</param>
  143. public void OnTranscodeEndRequest(string path, TranscodingJobType type)
  144. {
  145. lock (_activeTranscodingJobs)
  146. {
  147. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  148. if (job == null)
  149. {
  150. return;
  151. }
  152. job.ActiveRequestCount--;
  153. if (job.ActiveRequestCount == 0)
  154. {
  155. var timerDuration = type == TranscodingJobType.Progressive ? 1000 : 30000;
  156. if (job.KillTimer == null)
  157. {
  158. job.KillTimer = new Timer(OnTranscodeKillTimerStopped, job, timerDuration, Timeout.Infinite);
  159. }
  160. else
  161. {
  162. job.KillTimer.Change(timerDuration, Timeout.Infinite);
  163. }
  164. }
  165. }
  166. }
  167. /// <summary>
  168. /// Called when [transcode kill timer stopped].
  169. /// </summary>
  170. /// <param name="state">The state.</param>
  171. private async void OnTranscodeKillTimerStopped(object state)
  172. {
  173. var job = (TranscodingJob)state;
  174. lock (_activeTranscodingJobs)
  175. {
  176. _activeTranscodingJobs.Remove(job);
  177. if (job.KillTimer != null)
  178. {
  179. job.KillTimer.Dispose();
  180. job.KillTimer = null;
  181. }
  182. }
  183. var process = job.Process;
  184. var hasExited = true;
  185. try
  186. {
  187. hasExited = process.HasExited;
  188. }
  189. catch (Win32Exception ex)
  190. {
  191. Logger.ErrorException("Error determining if ffmpeg process has exited for {0}", ex, job.Path);
  192. }
  193. catch (InvalidOperationException ex)
  194. {
  195. Logger.ErrorException("Error determining if ffmpeg process has exited for {0}", ex, job.Path);
  196. }
  197. catch (NotSupportedException ex)
  198. {
  199. Logger.ErrorException("Error determining if ffmpeg process has exited for {0}", ex, job.Path);
  200. }
  201. if (!hasExited)
  202. {
  203. try
  204. {
  205. Logger.Info("Killing ffmpeg process for {0}", job.Path);
  206. process.Kill();
  207. // Need to wait because killing is asynchronous
  208. process.WaitForExit(5000);
  209. }
  210. catch (Win32Exception ex)
  211. {
  212. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  213. }
  214. catch (InvalidOperationException ex)
  215. {
  216. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  217. }
  218. catch (NotSupportedException ex)
  219. {
  220. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  221. }
  222. }
  223. // Determine if it exited successfully
  224. var hasExitedSuccessfully = false;
  225. try
  226. {
  227. hasExitedSuccessfully = process.ExitCode == 0;
  228. }
  229. catch (InvalidOperationException)
  230. {
  231. }
  232. catch (NotSupportedException)
  233. {
  234. }
  235. // Dispose the process
  236. process.Dispose();
  237. // If it didn't complete successfully cleanup the partial files
  238. if (!hasExitedSuccessfully)
  239. {
  240. Logger.Info("Deleting partial stream file(s) {0}", job.Path);
  241. await Task.Delay(1000).ConfigureAwait(false);
  242. try
  243. {
  244. if (job.Type == TranscodingJobType.Progressive)
  245. {
  246. DeleteProgressivePartialStreamFiles(job.Path);
  247. }
  248. else
  249. {
  250. DeleteHlsPartialStreamFiles(job.Path);
  251. }
  252. }
  253. catch (IOException ex)
  254. {
  255. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, job.Path);
  256. }
  257. }
  258. }
  259. /// <summary>
  260. /// Deletes the progressive partial stream files.
  261. /// </summary>
  262. /// <param name="outputFilePath">The output file path.</param>
  263. private void DeleteProgressivePartialStreamFiles(string outputFilePath)
  264. {
  265. File.Delete(outputFilePath);
  266. }
  267. /// <summary>
  268. /// Deletes the HLS partial stream files.
  269. /// </summary>
  270. /// <param name="outputFilePath">The output file path.</param>
  271. private void DeleteHlsPartialStreamFiles(string outputFilePath)
  272. {
  273. var directory = Path.GetDirectoryName(outputFilePath);
  274. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  275. var filesToDelete = Directory.EnumerateFiles(directory)
  276. .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1)
  277. .ToList();
  278. foreach (var file in filesToDelete)
  279. {
  280. try
  281. {
  282. Logger.Info("Deleting HLS file {0}", file);
  283. File.Delete(file);
  284. }
  285. catch (IOException ex)
  286. {
  287. Logger.ErrorException("Error deleting HLS file {0}", ex, file);
  288. }
  289. }
  290. }
  291. }
  292. /// <summary>
  293. /// Class TranscodingJob
  294. /// </summary>
  295. public class TranscodingJob
  296. {
  297. /// <summary>
  298. /// Gets or sets the path.
  299. /// </summary>
  300. /// <value>The path.</value>
  301. public string Path { get; set; }
  302. /// <summary>
  303. /// Gets or sets the type.
  304. /// </summary>
  305. /// <value>The type.</value>
  306. public TranscodingJobType Type { get; set; }
  307. /// <summary>
  308. /// Gets or sets the process.
  309. /// </summary>
  310. /// <value>The process.</value>
  311. public Process Process { get; set; }
  312. /// <summary>
  313. /// Gets or sets the active request count.
  314. /// </summary>
  315. /// <value>The active request count.</value>
  316. public int ActiveRequestCount { get; set; }
  317. /// <summary>
  318. /// Gets or sets the kill timer.
  319. /// </summary>
  320. /// <value>The kill timer.</value>
  321. public Timer KillTimer { get; set; }
  322. }
  323. /// <summary>
  324. /// Enum TranscodingJobType
  325. /// </summary>
  326. public enum TranscodingJobType
  327. {
  328. /// <summary>
  329. /// The progressive
  330. /// </summary>
  331. Progressive,
  332. /// <summary>
  333. /// The HLS
  334. /// </summary>
  335. Hls
  336. }
  337. }