ApiEntryPoint.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. using MediaBrowser.Controller.Plugins;
  2. using MediaBrowser.Model.Logging;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.Diagnostics;
  7. using System.IO;
  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, KillTranscodingJob);
  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. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  75. /// <param name="startTimeTicks">The start time ticks.</param>
  76. /// <param name="sourcePath">The source path.</param>
  77. /// <param name="deviceId">The device id.</param>
  78. public void OnTranscodeBeginning(string path, TranscodingJobType type, Process process, bool isVideo, long? startTimeTicks, string sourcePath, string deviceId)
  79. {
  80. lock (_activeTranscodingJobs)
  81. {
  82. _activeTranscodingJobs.Add(new TranscodingJob
  83. {
  84. Type = type,
  85. Path = path,
  86. Process = process,
  87. ActiveRequestCount = 1,
  88. IsVideo = isVideo,
  89. StartTimeTicks = startTimeTicks,
  90. SourcePath = sourcePath,
  91. DeviceId = deviceId
  92. });
  93. }
  94. }
  95. /// <summary>
  96. /// <summary>
  97. /// The progressive
  98. /// </summary>
  99. /// Called when [transcode failed to start].
  100. /// </summary>
  101. /// <param name="path">The path.</param>
  102. /// <param name="type">The type.</param>
  103. public void OnTranscodeFailedToStart(string path, TranscodingJobType type)
  104. {
  105. lock (_activeTranscodingJobs)
  106. {
  107. var job = _activeTranscodingJobs.First(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  108. _activeTranscodingJobs.Remove(job);
  109. }
  110. }
  111. /// <summary>
  112. /// Determines whether [has active transcoding job] [the specified path].
  113. /// </summary>
  114. /// <param name="path">The path.</param>
  115. /// <param name="type">The type.</param>
  116. /// <returns><c>true</c> if [has active transcoding job] [the specified path]; otherwise, <c>false</c>.</returns>
  117. public bool HasActiveTranscodingJob(string path, TranscodingJobType type)
  118. {
  119. lock (_activeTranscodingJobs)
  120. {
  121. return _activeTranscodingJobs.Any(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  122. }
  123. }
  124. /// <summary>
  125. /// Called when [transcode begin request].
  126. /// </summary>
  127. /// <param name="path">The path.</param>
  128. /// <param name="type">The type.</param>
  129. public void OnTranscodeBeginRequest(string path, TranscodingJobType type)
  130. {
  131. lock (_activeTranscodingJobs)
  132. {
  133. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  134. if (job == null)
  135. {
  136. return;
  137. }
  138. job.ActiveRequestCount++;
  139. if (job.KillTimer != null)
  140. {
  141. job.KillTimer.Dispose();
  142. job.KillTimer = null;
  143. }
  144. }
  145. }
  146. /// <summary>
  147. /// Called when [transcode end request].
  148. /// </summary>
  149. /// <param name="path">The path.</param>
  150. /// <param name="type">The type.</param>
  151. public void OnTranscodeEndRequest(string path, TranscodingJobType type)
  152. {
  153. lock (_activeTranscodingJobs)
  154. {
  155. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  156. if (job == null)
  157. {
  158. return;
  159. }
  160. job.ActiveRequestCount--;
  161. if (job.ActiveRequestCount == 0)
  162. {
  163. var timerDuration = type == TranscodingJobType.Progressive ? 1000 : 180000;
  164. if (job.KillTimer == null)
  165. {
  166. job.KillTimer = new Timer(OnTranscodeKillTimerStopped, job, timerDuration, Timeout.Infinite);
  167. }
  168. else
  169. {
  170. job.KillTimer.Change(timerDuration, Timeout.Infinite);
  171. }
  172. }
  173. }
  174. }
  175. /// <summary>
  176. /// Called when [transcode kill timer stopped].
  177. /// </summary>
  178. /// <param name="state">The state.</param>
  179. private void OnTranscodeKillTimerStopped(object state)
  180. {
  181. var job = (TranscodingJob)state;
  182. KillTranscodingJob(job);
  183. }
  184. /// <summary>
  185. /// Kills the single transcoding job.
  186. /// </summary>
  187. /// <param name="deviceId">The device id.</param>
  188. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  189. /// <exception cref="System.ArgumentNullException">sourcePath</exception>
  190. internal void KillTranscodingJobs(string deviceId, bool isVideo)
  191. {
  192. if (string.IsNullOrEmpty(deviceId))
  193. {
  194. throw new ArgumentNullException("deviceId");
  195. }
  196. var jobs = new List<TranscodingJob>();
  197. lock (_activeTranscodingJobs)
  198. {
  199. // This is really only needed for HLS.
  200. // Progressive streams can stop on their own reliably
  201. jobs.AddRange(_activeTranscodingJobs.Where(i => isVideo == i.IsVideo && string.Equals(deviceId, i.DeviceId, StringComparison.OrdinalIgnoreCase)));
  202. }
  203. foreach (var job in jobs)
  204. {
  205. KillTranscodingJob(job);
  206. }
  207. }
  208. /// <summary>
  209. /// Kills the transcoding job.
  210. /// </summary>
  211. /// <param name="job">The job.</param>
  212. private async void KillTranscodingJob(TranscodingJob job)
  213. {
  214. lock (_activeTranscodingJobs)
  215. {
  216. _activeTranscodingJobs.Remove(job);
  217. if (job.KillTimer != null)
  218. {
  219. job.KillTimer.Dispose();
  220. job.KillTimer = null;
  221. }
  222. }
  223. var process = job.Process;
  224. var hasExited = true;
  225. try
  226. {
  227. hasExited = process.HasExited;
  228. }
  229. catch (Exception ex)
  230. {
  231. Logger.ErrorException("Error determining if ffmpeg process has exited for {0}", ex, job.Path);
  232. }
  233. if (!hasExited)
  234. {
  235. try
  236. {
  237. Logger.Info("Killing ffmpeg process for {0}", job.Path);
  238. process.Kill();
  239. // Need to wait because killing is asynchronous
  240. process.WaitForExit(5000);
  241. }
  242. catch (Win32Exception ex)
  243. {
  244. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  245. }
  246. catch (InvalidOperationException ex)
  247. {
  248. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  249. }
  250. catch (NotSupportedException ex)
  251. {
  252. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  253. }
  254. }
  255. // Determine if it exited successfully
  256. var hasExitedSuccessfully = false;
  257. try
  258. {
  259. hasExitedSuccessfully = process.ExitCode == 0;
  260. }
  261. catch (InvalidOperationException)
  262. {
  263. }
  264. catch (NotSupportedException)
  265. {
  266. }
  267. // Dispose the process
  268. process.Dispose();
  269. // If it didn't complete successfully cleanup the partial files
  270. // Also don't cache output from resume points
  271. // Also don't cache video
  272. if (!hasExitedSuccessfully || job.StartTimeTicks.HasValue || job.IsVideo)
  273. {
  274. Logger.Info("Deleting partial stream file(s) {0}", job.Path);
  275. await Task.Delay(1000).ConfigureAwait(false);
  276. try
  277. {
  278. if (job.Type == TranscodingJobType.Progressive)
  279. {
  280. DeleteProgressivePartialStreamFiles(job.Path);
  281. }
  282. else
  283. {
  284. DeleteHlsPartialStreamFiles(job.Path);
  285. }
  286. }
  287. catch (IOException ex)
  288. {
  289. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, job.Path);
  290. }
  291. }
  292. }
  293. /// <summary>
  294. /// Deletes the progressive partial stream files.
  295. /// </summary>
  296. /// <param name="outputFilePath">The output file path.</param>
  297. private void DeleteProgressivePartialStreamFiles(string outputFilePath)
  298. {
  299. File.Delete(outputFilePath);
  300. }
  301. /// <summary>
  302. /// Deletes the HLS partial stream files.
  303. /// </summary>
  304. /// <param name="outputFilePath">The output file path.</param>
  305. private void DeleteHlsPartialStreamFiles(string outputFilePath)
  306. {
  307. var directory = Path.GetDirectoryName(outputFilePath);
  308. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  309. var filesToDelete = Directory.EnumerateFiles(directory)
  310. .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1)
  311. .ToList();
  312. foreach (var file in filesToDelete)
  313. {
  314. try
  315. {
  316. Logger.Info("Deleting HLS file {0}", file);
  317. File.Delete(file);
  318. }
  319. catch (IOException ex)
  320. {
  321. Logger.ErrorException("Error deleting HLS file {0}", ex, file);
  322. }
  323. }
  324. }
  325. }
  326. /// <summary>
  327. /// Class TranscodingJob
  328. /// </summary>
  329. public class TranscodingJob
  330. {
  331. /// <summary>
  332. /// Gets or sets the path.
  333. /// </summary>
  334. /// <value>The path.</value>
  335. public string Path { get; set; }
  336. /// <summary>
  337. /// Gets or sets the type.
  338. /// </summary>
  339. /// <value>The type.</value>
  340. public TranscodingJobType Type { get; set; }
  341. /// <summary>
  342. /// Gets or sets the process.
  343. /// </summary>
  344. /// <value>The process.</value>
  345. public Process Process { get; set; }
  346. /// <summary>
  347. /// Gets or sets the active request count.
  348. /// </summary>
  349. /// <value>The active request count.</value>
  350. public int ActiveRequestCount { get; set; }
  351. /// <summary>
  352. /// Gets or sets the kill timer.
  353. /// </summary>
  354. /// <value>The kill timer.</value>
  355. public Timer KillTimer { get; set; }
  356. public bool IsVideo { get; set; }
  357. public long? StartTimeTicks { get; set; }
  358. public string SourcePath { get; set; }
  359. public string DeviceId { get; set; }
  360. }
  361. /// <summary>
  362. /// Enum TranscodingJobType
  363. /// </summary>
  364. public enum TranscodingJobType
  365. {
  366. /// <summary>
  367. /// The progressive
  368. /// </summary>
  369. Progressive,
  370. /// <summary>
  371. /// The HLS
  372. /// </summary>
  373. Hls
  374. }
  375. }