2
0

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