MpegDashService.cs 21 KB

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