MpegDashService.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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. ApiEntryPoint.Instance.KillTranscodingJobs(request.DeviceId, request.StreamId, p => false);
  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 long GetPositionTicks(StreamState state, int requestedIndex)
  174. {
  175. if (requestedIndex <= 0)
  176. {
  177. return 0;
  178. }
  179. var startSeconds = requestedIndex * state.SegmentLength;
  180. return TimeSpan.FromSeconds(startSeconds).Ticks;
  181. }
  182. protected Task WaitForMinimumDashSegmentCount(string playlist, int segmentCount, CancellationToken cancellationToken)
  183. {
  184. return WaitForSegment(playlist, "stream0-" + segmentCount.ToString("00000", CultureInfo.InvariantCulture) + ".m4s", cancellationToken);
  185. }
  186. private async Task<object> GetSegmentResult(string playlistPath,
  187. string segmentPath,
  188. int segmentIndex,
  189. int segmentLength,
  190. TranscodingJob transcodingJob,
  191. CancellationToken cancellationToken)
  192. {
  193. // If all transcoding has completed, just return immediately
  194. if (transcodingJob != null && transcodingJob.HasExited)
  195. {
  196. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  197. }
  198. // Wait for the file to stop being written to, then stream it
  199. var length = new FileInfo(segmentPath).Length;
  200. var eofCount = 0;
  201. while (eofCount < 10)
  202. {
  203. var info = new FileInfo(segmentPath);
  204. if (!info.Exists)
  205. {
  206. break;
  207. }
  208. var newLength = info.Length;
  209. if (newLength == length)
  210. {
  211. eofCount++;
  212. }
  213. else
  214. {
  215. eofCount = 0;
  216. }
  217. length = newLength;
  218. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  219. }
  220. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  221. }
  222. private object GetSegmentResult(string segmentPath, int index, int segmentLength, TranscodingJob transcodingJob)
  223. {
  224. var segmentEndingSeconds = (1 + index) * segmentLength;
  225. var segmentEndingPositionTicks = TimeSpan.FromSeconds(segmentEndingSeconds).Ticks;
  226. return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  227. {
  228. Path = segmentPath,
  229. FileShare = FileShare.ReadWrite,
  230. OnComplete = () =>
  231. {
  232. if (transcodingJob != null)
  233. {
  234. transcodingJob.DownloadPositionTicks = Math.Max(transcodingJob.DownloadPositionTicks ?? segmentEndingPositionTicks, segmentEndingPositionTicks);
  235. }
  236. }
  237. });
  238. }
  239. public int? GetCurrentTranscodingIndex(string playlist, string segmentExtension)
  240. {
  241. var job = ApiEntryPoint.Instance.GetTranscodingJob(playlist, TranscodingJobType);
  242. if (job == null || job.HasExited)
  243. {
  244. return null;
  245. }
  246. var file = GetLastTranscodingFiles(playlist, segmentExtension, FileSystem, 1).FirstOrDefault();
  247. if (file == null)
  248. {
  249. return null;
  250. }
  251. return GetIndex(file.FullName);
  252. }
  253. public int GetIndex(string segmentPath)
  254. {
  255. var indexString = Path.GetFileNameWithoutExtension(segmentPath).Split('-').LastOrDefault();
  256. if (string.Equals(indexString, "init", StringComparison.OrdinalIgnoreCase))
  257. {
  258. return -1;
  259. }
  260. var startNumber = int.Parse(Path.GetFileNameWithoutExtension(Path.GetDirectoryName(segmentPath)), NumberStyles.Integer, UsCulture);
  261. return startNumber + int.Parse(indexString, NumberStyles.Integer, UsCulture) - 1;
  262. }
  263. private void DeleteLastTranscodedFiles(string playlistPath, int retryCount)
  264. {
  265. if (retryCount >= 5)
  266. {
  267. return;
  268. }
  269. }
  270. private static List<FileInfo> GetLastTranscodingFiles(string playlist, string segmentExtension, IFileSystem fileSystem, int count)
  271. {
  272. var folder = Path.GetDirectoryName(playlist);
  273. try
  274. {
  275. return new DirectoryInfo(folder)
  276. .EnumerateFiles("*", SearchOption.AllDirectories)
  277. .Where(i => string.Equals(i.Extension, segmentExtension, StringComparison.OrdinalIgnoreCase))
  278. .OrderByDescending(fileSystem.GetLastWriteTimeUtc)
  279. .Take(count)
  280. .ToList();
  281. }
  282. catch (DirectoryNotFoundException)
  283. {
  284. return new List<FileInfo>();
  285. }
  286. }
  287. private string FindSegment(string playlist, string representationId, string segmentExtension, int requestedIndex)
  288. {
  289. var folder = Path.GetDirectoryName(playlist);
  290. if (requestedIndex == -1)
  291. {
  292. var path = Path.Combine(folder, "0", "stream" + representationId + "-" + "init" + segmentExtension);
  293. return File.Exists(path) ? path : null;
  294. }
  295. try
  296. {
  297. foreach (var subfolder in new DirectoryInfo(folder).EnumerateDirectories().ToList())
  298. {
  299. var subfolderName = Path.GetFileNameWithoutExtension(subfolder.FullName);
  300. int startNumber;
  301. if (int.TryParse(subfolderName, NumberStyles.Any, UsCulture, out startNumber))
  302. {
  303. var segmentIndex = requestedIndex - startNumber + 1;
  304. var path = Path.Combine(folder, subfolderName, "stream" + representationId + "-" + segmentIndex.ToString("00000", CultureInfo.InvariantCulture) + segmentExtension);
  305. if (File.Exists(path))
  306. {
  307. return path;
  308. }
  309. }
  310. }
  311. }
  312. catch (DirectoryNotFoundException)
  313. {
  314. }
  315. return null;
  316. }
  317. protected override string GetAudioArguments(StreamState state)
  318. {
  319. var codec = state.OutputAudioCodec;
  320. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  321. {
  322. return "-codec:a:0 copy";
  323. }
  324. var args = "-codec:a:0 " + codec;
  325. var channels = state.OutputAudioChannels;
  326. if (channels.HasValue)
  327. {
  328. args += " -ac " + channels.Value;
  329. }
  330. var bitrate = state.OutputAudioBitrate;
  331. if (bitrate.HasValue)
  332. {
  333. args += " -ab " + bitrate.Value.ToString(UsCulture);
  334. }
  335. args += " " + GetAudioFilterParam(state, true);
  336. return args;
  337. }
  338. protected override string GetVideoArguments(StreamState state)
  339. {
  340. var codec = state.OutputVideoCodec;
  341. var args = "-codec:v:0 " + codec;
  342. if (state.EnableMpegtsM2TsMode)
  343. {
  344. args += " -mpegts_m2ts_mode 1";
  345. }
  346. // See if we can save come cpu cycles by avoiding encoding
  347. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  348. {
  349. return state.VideoStream != null && IsH264(state.VideoStream) ?
  350. args + " -bsf:v h264_mp4toannexb" :
  351. args;
  352. }
  353. var keyFrameArg = string.Format(" -force_key_frames expr:gte(t,n_forced*{0})",
  354. state.SegmentLength.ToString(UsCulture));
  355. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream;
  356. args += " " + GetVideoQualityParam(state, H264Encoder, true) + keyFrameArg;
  357. // Add resolution params, if specified
  358. if (!hasGraphicalSubs)
  359. {
  360. args += GetOutputSizeParam(state, codec, false);
  361. }
  362. // This is for internal graphical subs
  363. if (hasGraphicalSubs)
  364. {
  365. args += GetGraphicalSubtitleParam(state, codec);
  366. }
  367. return args;
  368. }
  369. protected override string GetCommandLineArguments(string outputPath, string transcodingJobId, StreamState state, bool isEncoding)
  370. {
  371. // 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
  372. // Good info on i-frames http://blog.streamroot.io/encode-multi-bitrate-videos-mpeg-dash-mse-based-media-players/
  373. var threads = GetNumberOfThreads(state, false);
  374. var inputModifier = GetInputModifier(state);
  375. var initSegmentName = "stream$RepresentationID$-init.m4s";
  376. var segmentName = "stream$RepresentationID$-$Number%05d$.m4s";
  377. 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}\"",
  378. inputModifier,
  379. GetInputArgument(transcodingJobId, state),
  380. threads,
  381. GetMapArgs(state),
  382. GetVideoArguments(state),
  383. GetAudioArguments(state),
  384. initSegmentName,
  385. segmentName,
  386. (state.SegmentLength * 1000000).ToString(CultureInfo.InvariantCulture),
  387. state.WaitForPath
  388. ).Trim();
  389. return args;
  390. }
  391. protected override int GetStartNumber(StreamState state)
  392. {
  393. return GetStartNumber(state.VideoRequest);
  394. }
  395. private int GetStartNumber(VideoStreamRequest request)
  396. {
  397. var segmentId = "0";
  398. var segmentRequest = request as GetDashSegment;
  399. if (segmentRequest != null)
  400. {
  401. segmentId = segmentRequest.SegmentId;
  402. }
  403. if (string.Equals(segmentId, "init", StringComparison.OrdinalIgnoreCase))
  404. {
  405. return -1;
  406. }
  407. return int.Parse(segmentId, NumberStyles.Integer, UsCulture);
  408. }
  409. /// <summary>
  410. /// Gets the segment file extension.
  411. /// </summary>
  412. /// <param name="state">The state.</param>
  413. /// <returns>System.String.</returns>
  414. protected override string GetSegmentFileExtension(StreamState state)
  415. {
  416. return ".m4s";
  417. }
  418. protected override TranscodingJobType TranscodingJobType
  419. {
  420. get
  421. {
  422. return TranscodingJobType.Dash;
  423. }
  424. }
  425. private async Task WaitForSegment(string playlist, string segment, CancellationToken cancellationToken)
  426. {
  427. var tmpPath = playlist + ".tmp";
  428. var segmentFilename = Path.GetFileName(segment);
  429. Logger.Debug("Waiting for {0} in {1}", segmentFilename, playlist);
  430. while (true)
  431. {
  432. FileStream fileStream;
  433. try
  434. {
  435. fileStream = FileSystem.GetFileStream(tmpPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  436. }
  437. catch (IOException)
  438. {
  439. fileStream = FileSystem.GetFileStream(playlist, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  440. }
  441. // Need to use FileShare.ReadWrite because we're reading the file at the same time it's being written
  442. using (fileStream)
  443. {
  444. using (var reader = new StreamReader(fileStream))
  445. {
  446. while (!reader.EndOfStream)
  447. {
  448. var line = await reader.ReadLineAsync().ConfigureAwait(false);
  449. if (line.IndexOf(segmentFilename, StringComparison.OrdinalIgnoreCase) != -1)
  450. {
  451. Logger.Debug("Finished waiting for {0} in {1}", segmentFilename, playlist);
  452. return;
  453. }
  454. }
  455. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  456. }
  457. }
  458. }
  459. }
  460. }
  461. }