ApiEntryPoint.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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, FileDeleteMode.All));
  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, FileDeleteMode.All);
  263. }
  264. /// <summary>
  265. /// Kills the single transcoding job.
  266. /// </summary>
  267. /// <param name="deviceId">The device id.</param>
  268. /// <param name="deleteMode">The delete mode.</param>
  269. /// <param name="acquireLock">if set to <c>true</c> [acquire lock].</param>
  270. /// <exception cref="System.ArgumentNullException">sourcePath</exception>
  271. internal async Task KillTranscodingJobs(string deviceId, FileDeleteMode deleteMode, bool acquireLock)
  272. {
  273. if (string.IsNullOrEmpty(deviceId))
  274. {
  275. throw new ArgumentNullException("deviceId");
  276. }
  277. var jobs = new List<TranscodingJob>();
  278. lock (_activeTranscodingJobs)
  279. {
  280. // This is really only needed for HLS.
  281. // Progressive streams can stop on their own reliably
  282. jobs.AddRange(_activeTranscodingJobs.Where(i => string.Equals(deviceId, i.DeviceId, StringComparison.OrdinalIgnoreCase)));
  283. }
  284. if (jobs.Count == 0)
  285. {
  286. return;
  287. }
  288. if (acquireLock)
  289. {
  290. await TranscodingStartLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  291. }
  292. try
  293. {
  294. foreach (var job in jobs)
  295. {
  296. KillTranscodingJob(job, deleteMode);
  297. }
  298. }
  299. finally
  300. {
  301. if (acquireLock)
  302. {
  303. TranscodingStartLock.Release();
  304. }
  305. }
  306. }
  307. /// <summary>
  308. /// Kills the transcoding jobs.
  309. /// </summary>
  310. /// <param name="deviceId">The device identifier.</param>
  311. /// <param name="type">The type.</param>
  312. /// <param name="deleteMode">The delete mode.</param>
  313. /// <param name="acquireLock">if set to <c>true</c> [acquire lock].</param>
  314. /// <exception cref="System.ArgumentNullException">deviceId</exception>
  315. internal async Task KillTranscodingJobs(string deviceId, TranscodingJobType type, FileDeleteMode deleteMode, bool acquireLock)
  316. {
  317. if (string.IsNullOrEmpty(deviceId))
  318. {
  319. throw new ArgumentNullException("deviceId");
  320. }
  321. var jobs = new List<TranscodingJob>();
  322. lock (_activeTranscodingJobs)
  323. {
  324. // This is really only needed for HLS.
  325. // Progressive streams can stop on their own reliably
  326. jobs.AddRange(_activeTranscodingJobs.Where(i => string.Equals(deviceId, i.DeviceId, StringComparison.OrdinalIgnoreCase) && i.Type == type));
  327. }
  328. if (jobs.Count == 0)
  329. {
  330. return;
  331. }
  332. if (acquireLock)
  333. {
  334. await TranscodingStartLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  335. }
  336. try
  337. {
  338. foreach (var job in jobs)
  339. {
  340. KillTranscodingJob(job, deleteMode);
  341. }
  342. }
  343. finally
  344. {
  345. if (acquireLock)
  346. {
  347. TranscodingStartLock.Release();
  348. }
  349. }
  350. }
  351. /// <summary>
  352. /// Kills the transcoding job.
  353. /// </summary>
  354. /// <param name="job">The job.</param>
  355. /// <param name="deleteMode">The delete mode.</param>
  356. private void KillTranscodingJob(TranscodingJob job, FileDeleteMode deleteMode)
  357. {
  358. lock (_activeTranscodingJobs)
  359. {
  360. _activeTranscodingJobs.Remove(job);
  361. if (!job.CancellationTokenSource.IsCancellationRequested)
  362. {
  363. job.CancellationTokenSource.Cancel();
  364. }
  365. if (job.KillTimer != null)
  366. {
  367. job.KillTimer.Dispose();
  368. job.KillTimer = null;
  369. }
  370. }
  371. lock (job.ProcessLock)
  372. {
  373. var process = job.Process;
  374. var hasExited = true;
  375. try
  376. {
  377. hasExited = process.HasExited;
  378. }
  379. catch (Exception ex)
  380. {
  381. Logger.ErrorException("Error determining if ffmpeg process has exited for {0}", ex, job.Path);
  382. }
  383. if (!hasExited)
  384. {
  385. try
  386. {
  387. Logger.Info("Killing ffmpeg process for {0}", job.Path);
  388. //process.Kill();
  389. process.StandardInput.WriteLine("q");
  390. // Need to wait because killing is asynchronous
  391. process.WaitForExit(5000);
  392. }
  393. catch (Exception ex)
  394. {
  395. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  396. }
  397. }
  398. }
  399. if (deleteMode == FileDeleteMode.All)
  400. {
  401. DeletePartialStreamFiles(job.Path, job.Type, 0, 1500);
  402. }
  403. }
  404. private async void DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
  405. {
  406. if (retryCount >= 10)
  407. {
  408. return;
  409. }
  410. Logger.Info("Deleting partial stream file(s) {0}", path);
  411. await Task.Delay(delayMs).ConfigureAwait(false);
  412. try
  413. {
  414. if (jobType == TranscodingJobType.Progressive)
  415. {
  416. DeleteProgressivePartialStreamFiles(path);
  417. }
  418. else
  419. {
  420. DeleteHlsPartialStreamFiles(path);
  421. }
  422. }
  423. catch (IOException ex)
  424. {
  425. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
  426. DeletePartialStreamFiles(path, jobType, retryCount + 1, 500);
  427. }
  428. catch (Exception ex)
  429. {
  430. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
  431. }
  432. }
  433. /// <summary>
  434. /// Deletes the progressive partial stream files.
  435. /// </summary>
  436. /// <param name="outputFilePath">The output file path.</param>
  437. private void DeleteProgressivePartialStreamFiles(string outputFilePath)
  438. {
  439. File.Delete(outputFilePath);
  440. }
  441. /// <summary>
  442. /// Deletes the HLS partial stream files.
  443. /// </summary>
  444. /// <param name="outputFilePath">The output file path.</param>
  445. private void DeleteHlsPartialStreamFiles(string outputFilePath)
  446. {
  447. var directory = Path.GetDirectoryName(outputFilePath);
  448. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  449. var filesToDelete = Directory.EnumerateFiles(directory)
  450. .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1)
  451. .ToList();
  452. Exception e = null;
  453. foreach (var file in filesToDelete)
  454. {
  455. try
  456. {
  457. Logger.Info("Deleting HLS file {0}", file);
  458. File.Delete(file);
  459. }
  460. catch (IOException ex)
  461. {
  462. e = ex;
  463. Logger.ErrorException("Error deleting HLS file {0}", ex, file);
  464. }
  465. }
  466. if (e != null)
  467. {
  468. throw e;
  469. }
  470. }
  471. }
  472. /// <summary>
  473. /// Class TranscodingJob
  474. /// </summary>
  475. public class TranscodingJob
  476. {
  477. /// <summary>
  478. /// Gets or sets the path.
  479. /// </summary>
  480. /// <value>The path.</value>
  481. public string Path { get; set; }
  482. /// <summary>
  483. /// Gets or sets the type.
  484. /// </summary>
  485. /// <value>The type.</value>
  486. public TranscodingJobType Type { get; set; }
  487. /// <summary>
  488. /// Gets or sets the process.
  489. /// </summary>
  490. /// <value>The process.</value>
  491. public Process Process { get; set; }
  492. /// <summary>
  493. /// Gets or sets the active request count.
  494. /// </summary>
  495. /// <value>The active request count.</value>
  496. public int ActiveRequestCount { get; set; }
  497. /// <summary>
  498. /// Gets or sets the kill timer.
  499. /// </summary>
  500. /// <value>The kill timer.</value>
  501. public Timer KillTimer { get; set; }
  502. public string DeviceId { get; set; }
  503. public CancellationTokenSource CancellationTokenSource { get; set; }
  504. public object ProcessLock = new object();
  505. public bool HasExited { get; set; }
  506. }
  507. /// <summary>
  508. /// Enum TranscodingJobType
  509. /// </summary>
  510. public enum TranscodingJobType
  511. {
  512. /// <summary>
  513. /// The progressive
  514. /// </summary>
  515. Progressive,
  516. /// <summary>
  517. /// The HLS
  518. /// </summary>
  519. Hls
  520. }
  521. public enum FileDeleteMode
  522. {
  523. None,
  524. All
  525. }
  526. }