ApiEntryPoint.cs 17 KB

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