MpegDashService.cs 21 KB

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