ApiEntryPoint.cs 18 KB

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