ApiEntryPoint.cs 17 KB

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