ApiEntryPoint.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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="transcodingJobId">The transcoding job identifier.</param>
  109. /// <param name="type">The type.</param>
  110. /// <param name="process">The process.</param>
  111. /// <param name="deviceId">The device id.</param>
  112. /// <param name="state">The state.</param>
  113. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  114. /// <returns>TranscodingJob.</returns>
  115. public TranscodingJob OnTranscodeBeginning(string path,
  116. string transcodingJobId,
  117. TranscodingJobType type,
  118. Process process,
  119. string deviceId,
  120. StreamState state,
  121. CancellationTokenSource cancellationTokenSource)
  122. {
  123. lock (_activeTranscodingJobs)
  124. {
  125. var job = new TranscodingJob
  126. {
  127. Type = type,
  128. Path = path,
  129. Process = process,
  130. ActiveRequestCount = 1,
  131. DeviceId = deviceId,
  132. CancellationTokenSource = cancellationTokenSource,
  133. Id = transcodingJobId
  134. };
  135. _activeTranscodingJobs.Add(job);
  136. ReportTranscodingProgress(job, state, null, null, null, null);
  137. return job;
  138. }
  139. }
  140. public void ReportTranscodingProgress(TranscodingJob job, StreamState state, TimeSpan? transcodingPosition, float? framerate, double? percentComplete, long? bytesTranscoded)
  141. {
  142. var ticks = transcodingPosition.HasValue ? transcodingPosition.Value.Ticks : (long?)null;
  143. if (job != null)
  144. {
  145. job.Framerate = framerate;
  146. job.CompletionPercentage = percentComplete;
  147. job.TranscodingPositionTicks = ticks;
  148. job.BytesTranscoded = bytesTranscoded;
  149. }
  150. var deviceId = state.Request.DeviceId;
  151. if (!string.IsNullOrWhiteSpace(deviceId))
  152. {
  153. var audioCodec = state.Request.AudioCodec;
  154. var videoCodec = state.VideoRequest == null ? null : state.VideoRequest.VideoCodec;
  155. if (string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase) ||
  156. string.IsNullOrEmpty(audioCodec))
  157. {
  158. audioCodec = state.OutputAudioCodec;
  159. }
  160. if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase) ||
  161. string.IsNullOrEmpty(videoCodec))
  162. {
  163. videoCodec = state.OutputVideoCodec;
  164. }
  165. _sessionManager.ReportTranscodingInfo(deviceId, new TranscodingInfo
  166. {
  167. Bitrate = state.TotalOutputBitrate,
  168. AudioCodec = audioCodec,
  169. VideoCodec = videoCodec,
  170. Container = state.OutputContainer,
  171. Framerate = framerate,
  172. CompletionPercentage = percentComplete,
  173. Width = state.OutputWidth,
  174. Height = state.OutputHeight,
  175. AudioChannels = state.OutputAudioChannels
  176. });
  177. }
  178. }
  179. /// <summary>
  180. /// <summary>
  181. /// The progressive
  182. /// </summary>
  183. /// Called when [transcode failed to start].
  184. /// </summary>
  185. /// <param name="path">The path.</param>
  186. /// <param name="type">The type.</param>
  187. /// <param name="state">The state.</param>
  188. public void OnTranscodeFailedToStart(string path, TranscodingJobType type, StreamState state)
  189. {
  190. lock (_activeTranscodingJobs)
  191. {
  192. var job = _activeTranscodingJobs.First(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  193. _activeTranscodingJobs.Remove(job);
  194. }
  195. if (!string.IsNullOrWhiteSpace(state.Request.DeviceId))
  196. {
  197. _sessionManager.ClearTranscodingInfo(state.Request.DeviceId);
  198. }
  199. }
  200. /// <summary>
  201. /// Determines whether [has active transcoding job] [the specified path].
  202. /// </summary>
  203. /// <param name="path">The path.</param>
  204. /// <param name="type">The type.</param>
  205. /// <returns><c>true</c> if [has active transcoding job] [the specified path]; otherwise, <c>false</c>.</returns>
  206. public bool HasActiveTranscodingJob(string path, TranscodingJobType type)
  207. {
  208. return GetTranscodingJob(path, type) != null;
  209. }
  210. public TranscodingJob GetTranscodingJob(string path, TranscodingJobType type)
  211. {
  212. lock (_activeTranscodingJobs)
  213. {
  214. return _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  215. }
  216. }
  217. public TranscodingJob GetTranscodingJob(string id)
  218. {
  219. lock (_activeTranscodingJobs)
  220. {
  221. return _activeTranscodingJobs.FirstOrDefault(j => j.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
  222. }
  223. }
  224. /// <summary>
  225. /// Called when [transcode begin request].
  226. /// </summary>
  227. /// <param name="path">The path.</param>
  228. /// <param name="type">The type.</param>
  229. public TranscodingJob OnTranscodeBeginRequest(string path, TranscodingJobType type)
  230. {
  231. lock (_activeTranscodingJobs)
  232. {
  233. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  234. if (job == null)
  235. {
  236. return null;
  237. }
  238. job.ActiveRequestCount++;
  239. if (job.KillTimer != null)
  240. {
  241. job.KillTimer.Dispose();
  242. job.KillTimer = null;
  243. }
  244. return job;
  245. }
  246. }
  247. public void OnTranscodeEndRequest(TranscodingJob job)
  248. {
  249. job.ActiveRequestCount--;
  250. if (job.ActiveRequestCount == 0)
  251. {
  252. // The HLS kill timer is long - 1/2 hr. clients should use the manual kill command when stopping.
  253. var timerDuration = job.Type == TranscodingJobType.Progressive ? 1000 : 1800000;
  254. if (job.KillTimer == null)
  255. {
  256. job.KillTimer = new Timer(OnTranscodeKillTimerStopped, job, timerDuration, Timeout.Infinite);
  257. }
  258. else
  259. {
  260. job.KillTimer.Change(timerDuration, Timeout.Infinite);
  261. }
  262. }
  263. }
  264. /// <summary>
  265. /// Called when [transcode kill timer stopped].
  266. /// </summary>
  267. /// <param name="state">The state.</param>
  268. private void OnTranscodeKillTimerStopped(object state)
  269. {
  270. var job = (TranscodingJob)state;
  271. KillTranscodingJob(job, path => true);
  272. }
  273. /// <summary>
  274. /// Kills the single transcoding job.
  275. /// </summary>
  276. /// <param name="deviceId">The device id.</param>
  277. /// <param name="deleteFiles">The delete files.</param>
  278. /// <param name="acquireLock">if set to <c>true</c> [acquire lock].</param>
  279. /// <returns>Task.</returns>
  280. /// <exception cref="ArgumentNullException">deviceId</exception>
  281. internal Task KillTranscodingJobs(string deviceId, Func<string, bool> deleteFiles, bool acquireLock)
  282. {
  283. if (string.IsNullOrEmpty(deviceId))
  284. {
  285. throw new ArgumentNullException("deviceId");
  286. }
  287. return KillTranscodingJobs(j => string.Equals(deviceId, j.DeviceId, StringComparison.OrdinalIgnoreCase), deleteFiles, acquireLock);
  288. }
  289. /// <summary>
  290. /// Kills the transcoding jobs.
  291. /// </summary>
  292. /// <param name="killJob">The kill job.</param>
  293. /// <param name="deleteFiles">The delete files.</param>
  294. /// <param name="acquireLock">if set to <c>true</c> [acquire lock].</param>
  295. /// <returns>Task.</returns>
  296. internal async Task KillTranscodingJobs(Func<TranscodingJob, bool> killJob, Func<string, bool> deleteFiles, bool acquireLock)
  297. {
  298. var jobs = new List<TranscodingJob>();
  299. lock (_activeTranscodingJobs)
  300. {
  301. // This is really only needed for HLS.
  302. // Progressive streams can stop on their own reliably
  303. jobs.AddRange(_activeTranscodingJobs.Where(killJob));
  304. }
  305. if (jobs.Count == 0)
  306. {
  307. return;
  308. }
  309. if (acquireLock)
  310. {
  311. await TranscodingStartLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  312. }
  313. try
  314. {
  315. foreach (var job in jobs)
  316. {
  317. KillTranscodingJob(job, deleteFiles);
  318. }
  319. }
  320. finally
  321. {
  322. if (acquireLock)
  323. {
  324. TranscodingStartLock.Release();
  325. }
  326. }
  327. }
  328. /// <summary>
  329. /// Kills the transcoding job.
  330. /// </summary>
  331. /// <param name="job">The job.</param>
  332. /// <param name="delete">The delete.</param>
  333. private void KillTranscodingJob(TranscodingJob job, Func<string, bool> delete)
  334. {
  335. lock (_activeTranscodingJobs)
  336. {
  337. _activeTranscodingJobs.Remove(job);
  338. if (!job.CancellationTokenSource.IsCancellationRequested)
  339. {
  340. job.CancellationTokenSource.Cancel();
  341. }
  342. if (job.KillTimer != null)
  343. {
  344. job.KillTimer.Dispose();
  345. job.KillTimer = null;
  346. }
  347. }
  348. lock (job.ProcessLock)
  349. {
  350. var process = job.Process;
  351. var hasExited = true;
  352. try
  353. {
  354. hasExited = process.HasExited;
  355. }
  356. catch (Exception ex)
  357. {
  358. Logger.ErrorException("Error determining if ffmpeg process has exited for {0}", ex, job.Path);
  359. }
  360. if (!hasExited)
  361. {
  362. try
  363. {
  364. Logger.Info("Killing ffmpeg process for {0}", job.Path);
  365. //process.Kill();
  366. process.StandardInput.WriteLine("q");
  367. // Need to wait because killing is asynchronous
  368. process.WaitForExit(5000);
  369. }
  370. catch (Exception ex)
  371. {
  372. Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
  373. }
  374. }
  375. }
  376. if (delete(job.Path))
  377. {
  378. DeletePartialStreamFiles(job.Path, job.Type, 0, 1500);
  379. }
  380. }
  381. private async void DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
  382. {
  383. if (retryCount >= 10)
  384. {
  385. return;
  386. }
  387. Logger.Info("Deleting partial stream file(s) {0}", path);
  388. await Task.Delay(delayMs).ConfigureAwait(false);
  389. try
  390. {
  391. if (jobType == TranscodingJobType.Progressive)
  392. {
  393. DeleteProgressivePartialStreamFiles(path);
  394. }
  395. else
  396. {
  397. DeleteHlsPartialStreamFiles(path);
  398. }
  399. }
  400. catch (DirectoryNotFoundException)
  401. {
  402. }
  403. catch (FileNotFoundException)
  404. {
  405. }
  406. catch (IOException ex)
  407. {
  408. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
  409. DeletePartialStreamFiles(path, jobType, retryCount + 1, 500);
  410. }
  411. catch (Exception ex)
  412. {
  413. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
  414. }
  415. }
  416. /// <summary>
  417. /// Deletes the progressive partial stream files.
  418. /// </summary>
  419. /// <param name="outputFilePath">The output file path.</param>
  420. private void DeleteProgressivePartialStreamFiles(string outputFilePath)
  421. {
  422. File.Delete(outputFilePath);
  423. }
  424. /// <summary>
  425. /// Deletes the HLS partial stream files.
  426. /// </summary>
  427. /// <param name="outputFilePath">The output file path.</param>
  428. private void DeleteHlsPartialStreamFiles(string outputFilePath)
  429. {
  430. var directory = Path.GetDirectoryName(outputFilePath);
  431. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  432. var filesToDelete = Directory.EnumerateFiles(directory)
  433. .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1)
  434. .ToList();
  435. Exception e = null;
  436. foreach (var file in filesToDelete)
  437. {
  438. try
  439. {
  440. Logger.Info("Deleting HLS file {0}", file);
  441. File.Delete(file);
  442. }
  443. catch (DirectoryNotFoundException)
  444. {
  445. }
  446. catch (FileNotFoundException)
  447. {
  448. }
  449. catch (IOException ex)
  450. {
  451. e = ex;
  452. Logger.ErrorException("Error deleting HLS file {0}", ex, file);
  453. }
  454. }
  455. if (e != null)
  456. {
  457. throw e;
  458. }
  459. }
  460. }
  461. /// <summary>
  462. /// Class TranscodingJob
  463. /// </summary>
  464. public class TranscodingJob
  465. {
  466. /// <summary>
  467. /// Gets or sets the path.
  468. /// </summary>
  469. /// <value>The path.</value>
  470. public string Path { get; set; }
  471. /// <summary>
  472. /// Gets or sets the type.
  473. /// </summary>
  474. /// <value>The type.</value>
  475. public TranscodingJobType Type { get; set; }
  476. /// <summary>
  477. /// Gets or sets the process.
  478. /// </summary>
  479. /// <value>The process.</value>
  480. public Process Process { get; set; }
  481. /// <summary>
  482. /// Gets or sets the active request count.
  483. /// </summary>
  484. /// <value>The active request count.</value>
  485. public int ActiveRequestCount { get; set; }
  486. /// <summary>
  487. /// Gets or sets the kill timer.
  488. /// </summary>
  489. /// <value>The kill timer.</value>
  490. public Timer KillTimer { get; set; }
  491. public string DeviceId { get; set; }
  492. public CancellationTokenSource CancellationTokenSource { get; set; }
  493. public object ProcessLock = new object();
  494. public bool HasExited { get; set; }
  495. public string Id { get; set; }
  496. public float? Framerate { get; set; }
  497. public double? CompletionPercentage { get; set; }
  498. public long? BytesDownloaded { get; set; }
  499. public long? BytesTranscoded { get; set; }
  500. public long? TranscodingPositionTicks { get; set; }
  501. public long? DownloadPositionTicks { get; set; }
  502. }
  503. /// <summary>
  504. /// Enum TranscodingJobType
  505. /// </summary>
  506. public enum TranscodingJobType
  507. {
  508. /// <summary>
  509. /// The progressive
  510. /// </summary>
  511. Progressive,
  512. /// <summary>
  513. /// The HLS
  514. /// </summary>
  515. Hls
  516. }
  517. }