MpegDashService.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. using MediaBrowser.Api.Playback.Hls;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Devices;
  6. using MediaBrowser.Controller.Diagnostics;
  7. using MediaBrowser.Controller.Dlna;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.LiveTv;
  10. using MediaBrowser.Controller.MediaEncoding;
  11. using MediaBrowser.Controller.Net;
  12. using MediaBrowser.Model.IO;
  13. using ServiceStack;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Globalization;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Threading;
  20. using System.Threading.Tasks;
  21. using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
  22. namespace MediaBrowser.Api.Playback.Dash
  23. {
  24. /// <summary>
  25. /// Options is needed for chromecast. Threw Head in there since it's related
  26. /// </summary>
  27. [Route("/Videos/{Id}/master.mpd", "GET", Summary = "Gets a video stream using Mpeg dash.")]
  28. [Route("/Videos/{Id}/master.mpd", "HEAD", Summary = "Gets a video stream using Mpeg dash.")]
  29. public class GetMasterManifest : VideoStreamRequest
  30. {
  31. public bool EnableAdaptiveBitrateStreaming { get; set; }
  32. public GetMasterManifest()
  33. {
  34. EnableAdaptiveBitrateStreaming = true;
  35. }
  36. }
  37. [Route("/Videos/{Id}/dash/{RepresentationId}/{SegmentId}.m4s", "GET")]
  38. public class GetDashSegment : VideoStreamRequest
  39. {
  40. /// <summary>
  41. /// Gets or sets the segment id.
  42. /// </summary>
  43. /// <value>The segment id.</value>
  44. public string SegmentId { get; set; }
  45. /// <summary>
  46. /// Gets or sets the representation identifier.
  47. /// </summary>
  48. /// <value>The representation identifier.</value>
  49. public string RepresentationId { get; set; }
  50. }
  51. public class MpegDashService : BaseHlsService
  52. {
  53. public MpegDashService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, ILiveTvManager liveTvManager, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IProcessManager processManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, INetworkManager networkManager)
  54. : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, liveTvManager, dlnaManager, subtitleEncoder, deviceManager, processManager, mediaSourceManager, zipClient)
  55. {
  56. NetworkManager = networkManager;
  57. }
  58. protected INetworkManager NetworkManager { get; private set; }
  59. public object Get(GetMasterManifest request)
  60. {
  61. var result = GetAsync(request, "GET").Result;
  62. return result;
  63. }
  64. public object Head(GetMasterManifest request)
  65. {
  66. var result = GetAsync(request, "HEAD").Result;
  67. return result;
  68. }
  69. protected override bool EnableOutputInSubFolder
  70. {
  71. get
  72. {
  73. return true;
  74. }
  75. }
  76. private async Task<object> GetAsync(GetMasterManifest request, string method)
  77. {
  78. if (string.IsNullOrEmpty(request.MediaSourceId))
  79. {
  80. throw new ArgumentException("MediaSourceId is required");
  81. }
  82. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  83. var playlistText = string.Empty;
  84. if (string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
  85. {
  86. playlistText = new ManifestBuilder().GetManifestText(state, Request.RawUrl);
  87. }
  88. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.mpd"), new Dictionary<string, string>());
  89. }
  90. public object Get(GetDashSegment request)
  91. {
  92. return GetDynamicSegment(request, request.SegmentId, request.RepresentationId).Result;
  93. }
  94. private async Task<object> GetDynamicSegment(VideoStreamRequest request, string segmentId, string representationId)
  95. {
  96. if ((request.StartTimeTicks ?? 0) > 0)
  97. {
  98. throw new ArgumentException("StartTimeTicks is not allowed.");
  99. }
  100. var cancellationTokenSource = new CancellationTokenSource();
  101. var cancellationToken = cancellationTokenSource.Token;
  102. var requestedIndex = string.Equals(segmentId, "init", StringComparison.OrdinalIgnoreCase) ?
  103. -1 :
  104. int.Parse(segmentId, NumberStyles.Integer, UsCulture);
  105. var state = await GetState(request, cancellationToken).ConfigureAwait(false);
  106. var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".mpd");
  107. var segmentExtension = GetSegmentFileExtension(state);
  108. var segmentPath = FindSegment(playlistPath, representationId, segmentExtension, requestedIndex);
  109. var segmentLength = state.SegmentLength;
  110. TranscodingJob job = null;
  111. if (!string.IsNullOrWhiteSpace(segmentPath))
  112. {
  113. job = ApiEntryPoint.Instance.GetTranscodingJob(playlistPath, TranscodingJobType);
  114. return await GetSegmentResult(playlistPath, segmentPath, requestedIndex, segmentLength, job, cancellationToken).ConfigureAwait(false);
  115. }
  116. await ApiEntryPoint.Instance.TranscodingStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
  117. try
  118. {
  119. segmentPath = FindSegment(playlistPath, representationId, segmentExtension, requestedIndex);
  120. if (!string.IsNullOrWhiteSpace(segmentPath))
  121. {
  122. job = ApiEntryPoint.Instance.GetTranscodingJob(playlistPath, TranscodingJobType);
  123. return await GetSegmentResult(playlistPath, segmentPath, requestedIndex, segmentLength, job, cancellationToken).ConfigureAwait(false);
  124. }
  125. else
  126. {
  127. if (string.Equals(representationId, "0", StringComparison.OrdinalIgnoreCase))
  128. {
  129. job = ApiEntryPoint.Instance.GetTranscodingJob(playlistPath, TranscodingJobType);
  130. var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
  131. var segmentGapRequiringTranscodingChange = 24 / state.SegmentLength;
  132. Logger.Debug("Current transcoding index is {0}. requestedIndex={1}. segmentGapRequiringTranscodingChange={2}", currentTranscodingIndex ?? -2, requestedIndex, segmentGapRequiringTranscodingChange);
  133. if (currentTranscodingIndex == null || requestedIndex < currentTranscodingIndex.Value || (requestedIndex - currentTranscodingIndex.Value) > segmentGapRequiringTranscodingChange)
  134. {
  135. // If the playlist doesn't already exist, startup ffmpeg
  136. try
  137. {
  138. KillTranscodingJobs(request.DeviceId, playlistPath);
  139. if (currentTranscodingIndex.HasValue)
  140. {
  141. DeleteLastTranscodedFiles(playlistPath, 0);
  142. }
  143. var positionTicks = GetPositionTicks(state, requestedIndex);
  144. request.StartTimeTicks = positionTicks;
  145. var startNumber = GetStartNumber(state);
  146. var workingDirectory = Path.Combine(Path.GetDirectoryName(playlistPath), (startNumber == -1 ? 0 : startNumber).ToString(CultureInfo.InvariantCulture));
  147. state.WaitForPath = Path.Combine(workingDirectory, Path.GetFileName(playlistPath));
  148. Directory.CreateDirectory(workingDirectory);
  149. job = await StartFfMpeg(state, playlistPath, cancellationTokenSource, workingDirectory).ConfigureAwait(false);
  150. await WaitForMinimumDashSegmentCount(Path.Combine(workingDirectory, Path.GetFileName(playlistPath)), 1, cancellationTokenSource.Token).ConfigureAwait(false);
  151. }
  152. catch
  153. {
  154. state.Dispose();
  155. throw;
  156. }
  157. }
  158. }
  159. }
  160. }
  161. finally
  162. {
  163. ApiEntryPoint.Instance.TranscodingStartLock.Release();
  164. }
  165. while (string.IsNullOrWhiteSpace(segmentPath))
  166. {
  167. segmentPath = FindSegment(playlistPath, representationId, segmentExtension, requestedIndex);
  168. await Task.Delay(50, cancellationToken).ConfigureAwait(false);
  169. }
  170. Logger.Info("returning {0}", segmentPath);
  171. return await GetSegmentResult(playlistPath, segmentPath, requestedIndex, segmentLength, job ?? ApiEntryPoint.Instance.GetTranscodingJob(playlistPath, TranscodingJobType), cancellationToken).ConfigureAwait(false);
  172. }
  173. private void KillTranscodingJobs(string deviceId, string playlistPath)
  174. {
  175. ApiEntryPoint.Instance.KillTranscodingJobs(j => j.Type == TranscodingJobType && string.Equals(j.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase), p => !string.Equals(p, playlistPath, StringComparison.OrdinalIgnoreCase));
  176. }
  177. private long GetPositionTicks(StreamState state, int segmentIndex)
  178. {
  179. if (segmentIndex <= 1)
  180. {
  181. return 0;
  182. }
  183. var startSeconds = segmentIndex * state.SegmentLength;
  184. return TimeSpan.FromSeconds(startSeconds).Ticks;
  185. }
  186. protected Task WaitForMinimumDashSegmentCount(string playlist, int segmentCount, CancellationToken cancellationToken)
  187. {
  188. return WaitForSegment(playlist, "stream0-" + segmentCount.ToString("00000", CultureInfo.InvariantCulture) + ".m4s", cancellationToken);
  189. }
  190. private async Task<object> GetSegmentResult(string playlistPath,
  191. string segmentPath,
  192. int segmentIndex,
  193. int segmentLength,
  194. TranscodingJob transcodingJob,
  195. CancellationToken cancellationToken)
  196. {
  197. // If all transcoding has completed, just return immediately
  198. if (transcodingJob != null && transcodingJob.HasExited)
  199. {
  200. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  201. }
  202. // Wait for the file to stop being written to, then stream it
  203. var length = new FileInfo(segmentPath).Length;
  204. var eofCount = 0;
  205. while (eofCount < 10)
  206. {
  207. var info = new FileInfo(segmentPath);
  208. if (!info.Exists)
  209. {
  210. break;
  211. }
  212. var newLength = info.Length;
  213. if (newLength == length)
  214. {
  215. eofCount++;
  216. }
  217. else
  218. {
  219. eofCount = 0;
  220. }
  221. length = newLength;
  222. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  223. }
  224. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  225. }
  226. private object GetSegmentResult(string segmentPath, int index, int segmentLength, TranscodingJob transcodingJob)
  227. {
  228. var segmentEndingSeconds = (1 + index) * segmentLength;
  229. var segmentEndingPositionTicks = TimeSpan.FromSeconds(segmentEndingSeconds).Ticks;
  230. return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  231. {
  232. Path = segmentPath,
  233. FileShare = FileShare.ReadWrite,
  234. OnComplete = () =>
  235. {
  236. if (transcodingJob != null)
  237. {
  238. transcodingJob.DownloadPositionTicks = Math.Max(transcodingJob.DownloadPositionTicks ?? segmentEndingPositionTicks, segmentEndingPositionTicks);
  239. }
  240. }
  241. });
  242. }
  243. public int? GetCurrentTranscodingIndex(string playlist, string segmentExtension)
  244. {
  245. var file = GetLastTranscodingFiles(playlist, segmentExtension, FileSystem, 1).FirstOrDefault();
  246. if (file == null)
  247. {
  248. return null;
  249. }
  250. return GetIndex(file.FullName);
  251. }
  252. public int GetIndex(string segmentPath)
  253. {
  254. var indexString = Path.GetFileNameWithoutExtension(segmentPath).Split('-').LastOrDefault();
  255. if (string.Equals(indexString, "init", StringComparison.OrdinalIgnoreCase))
  256. {
  257. return -1;
  258. }
  259. var startNumber = int.Parse(Path.GetFileNameWithoutExtension(Path.GetDirectoryName(segmentPath)), NumberStyles.Integer, UsCulture);
  260. return startNumber + int.Parse(indexString, NumberStyles.Integer, UsCulture) - 1;
  261. }
  262. private void DeleteLastTranscodedFiles(string playlistPath, int retryCount)
  263. {
  264. if (retryCount >= 5)
  265. {
  266. return;
  267. }
  268. }
  269. private static List<FileInfo> GetLastTranscodingFiles(string playlist, string segmentExtension, IFileSystem fileSystem, int count)
  270. {
  271. var folder = Path.GetDirectoryName(playlist);
  272. try
  273. {
  274. return new DirectoryInfo(folder)
  275. .EnumerateFiles("*", SearchOption.AllDirectories)
  276. .Where(i => string.Equals(i.Extension, segmentExtension, StringComparison.OrdinalIgnoreCase))
  277. .OrderByDescending(fileSystem.GetLastWriteTimeUtc)
  278. .Take(count)
  279. .ToList();
  280. }
  281. catch (DirectoryNotFoundException)
  282. {
  283. return new List<FileInfo>();
  284. }
  285. }
  286. private string FindSegment(string playlist, string representationId, string segmentExtension, int index)
  287. {
  288. var folder = Path.GetDirectoryName(playlist);
  289. if (index == -1)
  290. {
  291. var path = Path.Combine(folder, "0", "stream" + representationId + "-" + "init" + segmentExtension);
  292. return File.Exists(path) ? path : null;
  293. }
  294. try
  295. {
  296. foreach (var subfolder in new DirectoryInfo(folder).EnumerateDirectories().ToList())
  297. {
  298. int startNumber;
  299. if (int.TryParse(Path.GetFileNameWithoutExtension(subfolder.FullName), NumberStyles.Any, UsCulture, out startNumber))
  300. {
  301. var segmentIndex = index - startNumber + 1;
  302. var path = Path.Combine(folder, "0", "stream" + representationId + "-" + segmentIndex.ToString("00000", CultureInfo.InvariantCulture) + segmentExtension);
  303. return File.Exists(path) ? path : null;
  304. }
  305. }
  306. }
  307. catch (DirectoryNotFoundException)
  308. {
  309. }
  310. return null;
  311. }
  312. protected override string GetAudioArguments(StreamState state)
  313. {
  314. var codec = state.OutputAudioCodec;
  315. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  316. {
  317. return "-codec:a:0 copy";
  318. }
  319. var args = "-codec:a:0 " + codec;
  320. var channels = state.OutputAudioChannels;
  321. if (channels.HasValue)
  322. {
  323. args += " -ac " + channels.Value;
  324. }
  325. var bitrate = state.OutputAudioBitrate;
  326. if (bitrate.HasValue)
  327. {
  328. args += " -ab " + bitrate.Value.ToString(UsCulture);
  329. }
  330. args += " " + GetAudioFilterParam(state, true);
  331. return args;
  332. }
  333. protected override string GetVideoArguments(StreamState state)
  334. {
  335. var codec = state.OutputVideoCodec;
  336. var args = "-codec:v:0 " + codec;
  337. if (state.EnableMpegtsM2TsMode)
  338. {
  339. args += " -mpegts_m2ts_mode 1";
  340. }
  341. // See if we can save come cpu cycles by avoiding encoding
  342. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  343. {
  344. return state.VideoStream != null && IsH264(state.VideoStream) ?
  345. args + " -bsf:v h264_mp4toannexb" :
  346. args;
  347. }
  348. var keyFrameArg = string.Format(" -force_key_frames expr:gte(t,n_forced*{0})",
  349. state.SegmentLength.ToString(UsCulture));
  350. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream;
  351. args += " " + GetVideoQualityParam(state, H264Encoder, true) + keyFrameArg;
  352. // Add resolution params, if specified
  353. if (!hasGraphicalSubs)
  354. {
  355. args += GetOutputSizeParam(state, codec, false);
  356. }
  357. // This is for internal graphical subs
  358. if (hasGraphicalSubs)
  359. {
  360. args += GetGraphicalSubtitleParam(state, codec);
  361. }
  362. return args;
  363. }
  364. protected override string GetCommandLineArguments(string outputPath, string transcodingJobId, StreamState state, bool isEncoding)
  365. {
  366. // test url http://192.168.1.2:8096/videos/233e8905d559a8f230db9bffd2ac9d6d/master.mpd?mediasourceid=233e8905d559a8f230db9bffd2ac9d6d&videocodec=h264&audiocodec=aac&maxwidth=1280&videobitrate=500000&audiobitrate=128000&profile=baseline&level=3
  367. // Good info on i-frames http://blog.streamroot.io/encode-multi-bitrate-videos-mpeg-dash-mse-based-media-players/
  368. var threads = GetNumberOfThreads(state, false);
  369. var inputModifier = GetInputModifier(state);
  370. var initSegmentName = "stream$RepresentationID$-init.m4s";
  371. var segmentName = "stream$RepresentationID$-$Number%05d$.m4s";
  372. var args = string.Format("{0} {1} -map_metadata -1 -threads {2} {3} {4} -copyts {5} -f dash -init_seg_name \"{6}\" -media_seg_name \"{7}\" -use_template 0 -use_timeline 1 -min_seg_duration {8} -y \"{9}\"",
  373. inputModifier,
  374. GetInputArgument(transcodingJobId, state),
  375. threads,
  376. GetMapArgs(state),
  377. GetVideoArguments(state),
  378. GetAudioArguments(state),
  379. initSegmentName,
  380. segmentName,
  381. (state.SegmentLength * 1000000).ToString(CultureInfo.InvariantCulture),
  382. state.WaitForPath
  383. ).Trim();
  384. return args;
  385. }
  386. protected override int GetStartNumber(StreamState state)
  387. {
  388. return GetStartNumber(state.VideoRequest);
  389. }
  390. private int GetStartNumber(VideoStreamRequest request)
  391. {
  392. var segmentId = "0";
  393. var segmentRequest = request as GetDashSegment;
  394. if (segmentRequest != null)
  395. {
  396. segmentId = segmentRequest.SegmentId;
  397. }
  398. if (string.Equals(segmentId, "init", StringComparison.OrdinalIgnoreCase))
  399. {
  400. return -1;
  401. }
  402. return int.Parse(segmentId, NumberStyles.Integer, UsCulture);
  403. }
  404. /// <summary>
  405. /// Gets the segment file extension.
  406. /// </summary>
  407. /// <param name="state">The state.</param>
  408. /// <returns>System.String.</returns>
  409. protected override string GetSegmentFileExtension(StreamState state)
  410. {
  411. return ".m4s";
  412. }
  413. protected override TranscodingJobType TranscodingJobType
  414. {
  415. get
  416. {
  417. return TranscodingJobType.Dash;
  418. }
  419. }
  420. private async Task WaitForSegment(string playlist, string segment, CancellationToken cancellationToken)
  421. {
  422. var tmpPath = playlist + ".tmp";
  423. var segmentFilename = Path.GetFileName(segment);
  424. Logger.Debug("Waiting for {0} in {1}", segmentFilename, playlist);
  425. while (true)
  426. {
  427. FileStream fileStream;
  428. try
  429. {
  430. fileStream = FileSystem.GetFileStream(tmpPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  431. }
  432. catch (IOException)
  433. {
  434. fileStream = FileSystem.GetFileStream(playlist, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  435. }
  436. // Need to use FileShare.ReadWrite because we're reading the file at the same time it's being written
  437. using (fileStream)
  438. {
  439. using (var reader = new StreamReader(fileStream))
  440. {
  441. while (!reader.EndOfStream)
  442. {
  443. var line = await reader.ReadLineAsync().ConfigureAwait(false);
  444. if (line.IndexOf(segmentFilename, StringComparison.OrdinalIgnoreCase) != -1)
  445. {
  446. Logger.Debug("Finished waiting for {0} in {1}", segmentFilename, playlist);
  447. return;
  448. }
  449. }
  450. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  451. }
  452. }
  453. }
  454. }
  455. }
  456. }