MpegDashService.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. using MediaBrowser.Api.Playback.Hls;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Devices;
  5. using MediaBrowser.Controller.Dlna;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.MediaEncoding;
  8. using MediaBrowser.Controller.Net;
  9. using MediaBrowser.Model.IO;
  10. using MediaBrowser.Model.Serialization;
  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 CommonIO;
  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. FileSystem.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<FileSystemMetadata> GetLastTranscodingFiles(string playlist, string segmentExtension, IFileSystem fileSystem, int count)
  269. {
  270. var folder = Path.GetDirectoryName(playlist);
  271. try
  272. {
  273. return fileSystem.GetFiles(folder)
  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<FileSystemMetadata>();
  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 FileSystem.FileExists(path) ? path : null;
  291. }
  292. try
  293. {
  294. foreach (var subfolder in FileSystem.GetDirectoryPaths(folder).ToList())
  295. {
  296. var subfolderName = Path.GetFileNameWithoutExtension(subfolder);
  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 (FileSystem.FileExists(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 = GetAudioEncoder(state);
  317. if (string.Equals(codec, "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 = GetVideoEncoder(state);
  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, GetH264Encoder(state)) + 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. }