MpegDashService.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Devices;
  5. using MediaBrowser.Controller.Diagnostics;
  6. using MediaBrowser.Controller.Dlna;
  7. using MediaBrowser.Controller.Library;
  8. using MediaBrowser.Controller.LiveTv;
  9. using MediaBrowser.Controller.MediaEncoding;
  10. using MediaBrowser.Controller.Net;
  11. using MediaBrowser.Model.IO;
  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.Security;
  19. using System.Text;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
  23. namespace MediaBrowser.Api.Playback.Hls
  24. {
  25. /// <summary>
  26. /// Options is needed for chromecast. Threw Head in there since it's related
  27. /// </summary>
  28. [Route("/Videos/{Id}/master.mpd", "GET", Summary = "Gets a video stream using Mpeg dash.")]
  29. [Route("/Videos/{Id}/master.mpd", "HEAD", Summary = "Gets a video stream using Mpeg dash.")]
  30. public class GetMasterManifest : VideoStreamRequest
  31. {
  32. public bool EnableAdaptiveBitrateStreaming { get; set; }
  33. public GetMasterManifest()
  34. {
  35. EnableAdaptiveBitrateStreaming = true;
  36. }
  37. }
  38. [Route("/Videos/{Id}/dash/audio/{SegmentId}.m4s", "GET")]
  39. [Route("/Videos/{Id}/dash/video/{SegmentId}.m4s", "GET")]
  40. public class GetDashSegment : VideoStreamRequest
  41. {
  42. /// <summary>
  43. /// Gets or sets the segment id.
  44. /// </summary>
  45. /// <value>The segment id.</value>
  46. public string SegmentId { get; set; }
  47. }
  48. public class MpegDashService : BaseHlsService
  49. {
  50. 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, INetworkManager networkManager) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, liveTvManager, dlnaManager, subtitleEncoder, deviceManager, processManager, mediaSourceManager)
  51. {
  52. NetworkManager = networkManager;
  53. }
  54. protected INetworkManager NetworkManager { get; private set; }
  55. public object Get(GetMasterManifest request)
  56. {
  57. var result = GetAsync(request, "GET").Result;
  58. return result;
  59. }
  60. public object Head(GetMasterManifest request)
  61. {
  62. var result = GetAsync(request, "HEAD").Result;
  63. return result;
  64. }
  65. private async Task<object> GetAsync(GetMasterManifest request, string method)
  66. {
  67. if (string.Equals(request.AudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
  68. {
  69. throw new ArgumentException("Audio codec copy is not allowed here.");
  70. }
  71. if (string.Equals(request.VideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  72. {
  73. throw new ArgumentException("Video codec copy is not allowed here.");
  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 = GetManifestText(state);
  84. }
  85. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.mpd"), new Dictionary<string, string>());
  86. }
  87. private string GetManifestText(StreamState state)
  88. {
  89. var builder = new StringBuilder();
  90. var time = TimeSpan.FromTicks(state.RunTimeTicks.Value);
  91. var duration = "PT" + time.Hours.ToString("00", UsCulture) + "H" + time.Minutes.ToString("00", UsCulture) + "M" + time.Seconds.ToString("00", UsCulture) + ".00S";
  92. builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  93. builder.AppendFormat(
  94. "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"urn:mpeg:dash:schema:mpd:2011\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\" profiles=\"urn:mpeg:dash:profile:isoff-live:2011\" type=\"static\" mediaPresentationDuration=\"{0}\" minBufferTime=\"PT5.0S\">",
  95. duration);
  96. builder.Append("<ProgramInformation>");
  97. builder.Append("</ProgramInformation>");
  98. builder.Append("<Period start=\"PT0S\">");
  99. builder.Append(GetVideoAdaptationSet(state));
  100. builder.Append(GetAudioAdaptationSet(state));
  101. builder.Append("</Period>");
  102. builder.Append("</MPD>");
  103. return builder.ToString();
  104. }
  105. private string GetVideoAdaptationSet(StreamState state)
  106. {
  107. var builder = new StringBuilder();
  108. builder.Append("<AdaptationSet id=\"video\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">");
  109. builder.Append(GetVideoRepresentationOpenElement(state));
  110. AppendSegmentList(state, builder, "video");
  111. builder.Append("</Representation>");
  112. builder.Append("</AdaptationSet>");
  113. return builder.ToString();
  114. }
  115. private string GetAudioAdaptationSet(StreamState state)
  116. {
  117. var builder = new StringBuilder();
  118. builder.Append("<AdaptationSet id=\"audio\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">");
  119. builder.Append(GetAudioRepresentationOpenElement(state));
  120. builder.Append("<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"6\" />");
  121. AppendSegmentList(state, builder, "audio");
  122. builder.Append("</Representation>");
  123. builder.Append("</AdaptationSet>");
  124. return builder.ToString();
  125. }
  126. private string GetVideoRepresentationOpenElement(StreamState state)
  127. {
  128. var codecs = GetVideoCodecDescriptor(state);
  129. var mime = "video/mp4";
  130. var xml = "<Representation id=\"0\" mimeType=\"" + mime + "\" codecs=\"" + codecs + "\"";
  131. if (state.OutputWidth.HasValue)
  132. {
  133. xml += " width=\"" + state.OutputWidth.Value.ToString(UsCulture) + "\"";
  134. }
  135. if (state.OutputHeight.HasValue)
  136. {
  137. xml += " height=\"" + state.OutputHeight.Value.ToString(UsCulture) + "\"";
  138. }
  139. if (state.OutputVideoBitrate.HasValue)
  140. {
  141. xml += " bandwidth=\"" + state.OutputVideoBitrate.Value.ToString(UsCulture) + "\"";
  142. }
  143. xml += ">";
  144. return xml;
  145. }
  146. private string GetAudioRepresentationOpenElement(StreamState state)
  147. {
  148. var codecs = GetAudioCodecDescriptor(state);
  149. var mime = "audio/mp4";
  150. var xml = "<Representation id=\"1\" mimeType=\"" + mime + "\" codecs=\"" + codecs + "\"";
  151. if (state.OutputAudioSampleRate.HasValue)
  152. {
  153. xml += " audioSamplingRate=\"" + state.OutputAudioSampleRate.Value.ToString(UsCulture) + "\"";
  154. }
  155. if (state.OutputAudioBitrate.HasValue)
  156. {
  157. xml += " bandwidth=\"" + state.OutputAudioBitrate.Value.ToString(UsCulture) + "\"";
  158. }
  159. xml += ">";
  160. return xml;
  161. }
  162. private string GetVideoCodecDescriptor(StreamState state)
  163. {
  164. // https://developer.apple.com/library/ios/documentation/networkinginternet/conceptual/streamingmediaguide/FrequentlyAskedQuestions/FrequentlyAskedQuestions.html
  165. // http://www.chipwreck.de/blog/2010/02/25/html-5-video-tag-and-attributes/
  166. var level = state.TargetVideoLevel ?? 0;
  167. var profile = state.TargetVideoProfile ?? string.Empty;
  168. if (profile.IndexOf("high", StringComparison.OrdinalIgnoreCase) != -1)
  169. {
  170. if (level >= 4.1)
  171. {
  172. return "avc1.640028";
  173. }
  174. if (level >= 4)
  175. {
  176. return "avc1.640028";
  177. }
  178. return "avc1.64001f";
  179. }
  180. if (profile.IndexOf("main", StringComparison.OrdinalIgnoreCase) != -1)
  181. {
  182. if (level >= 4)
  183. {
  184. return "avc1.4d0028";
  185. }
  186. if (level >= 3.1)
  187. {
  188. return "avc1.4d001f";
  189. }
  190. return "avc1.4d001e";
  191. }
  192. if (level >= 3.1)
  193. {
  194. return "avc1.42001f";
  195. }
  196. return "avc1.42E01E";
  197. }
  198. private string GetAudioCodecDescriptor(StreamState state)
  199. {
  200. // https://developer.apple.com/library/ios/documentation/networkinginternet/conceptual/streamingmediaguide/FrequentlyAskedQuestions/FrequentlyAskedQuestions.html
  201. if (string.Equals(state.OutputAudioCodec, "mp3", StringComparison.OrdinalIgnoreCase))
  202. {
  203. return "mp4a.40.34";
  204. }
  205. // AAC 5ch
  206. if (state.OutputAudioChannels.HasValue && state.OutputAudioChannels.Value >= 5)
  207. {
  208. return "mp4a.40.5";
  209. }
  210. // AAC 2ch
  211. return "mp4a.40.2";
  212. }
  213. public object Get(GetDashSegment request)
  214. {
  215. return GetDynamicSegment(request, request.SegmentId).Result;
  216. }
  217. private void AppendSegmentList(StreamState state, StringBuilder builder, string type)
  218. {
  219. var extension = GetSegmentFileExtension(state);
  220. var seconds = TimeSpan.FromTicks(state.RunTimeTicks ?? 0).TotalSeconds;
  221. var queryStringIndex = Request.RawUrl.IndexOf('?');
  222. var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
  223. var index = 0;
  224. builder.Append("<SegmentList timescale=\"1000000\" duration=\"5000000\" startNumber=\"1\">");
  225. while (seconds > 0)
  226. {
  227. var segmentUrl = string.Format("dash/{3}/{0}{1}{2}",
  228. index.ToString(UsCulture),
  229. extension,
  230. SecurityElement.Escape(queryString),
  231. type);
  232. if (index == 0)
  233. {
  234. builder.AppendFormat("<Initialization sourceURL=\"{0}\"/>", segmentUrl);
  235. }
  236. else
  237. {
  238. builder.AppendFormat("<SegmentURL media=\"{0}\"/>", segmentUrl);
  239. }
  240. seconds -= state.SegmentLength;
  241. index++;
  242. }
  243. builder.Append("</SegmentList>");
  244. }
  245. private async Task<object> GetDynamicSegment(VideoStreamRequest request, string segmentId)
  246. {
  247. if ((request.StartTimeTicks ?? 0) > 0)
  248. {
  249. throw new ArgumentException("StartTimeTicks is not allowed.");
  250. }
  251. var cancellationTokenSource = new CancellationTokenSource();
  252. var cancellationToken = cancellationTokenSource.Token;
  253. var index = int.Parse(segmentId, NumberStyles.Integer, UsCulture);
  254. var state = await GetState(request, cancellationToken).ConfigureAwait(false);
  255. var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".mpd");
  256. var segmentExtension = GetSegmentFileExtension(state);
  257. var segmentPath = GetSegmentPath(playlistPath, segmentExtension, index);
  258. var segmentLength = state.SegmentLength;
  259. TranscodingJob job = null;
  260. if (File.Exists(segmentPath))
  261. {
  262. job = ApiEntryPoint.Instance.GetTranscodingJob(playlistPath, TranscodingJobType);
  263. return await GetSegmentResult(playlistPath, segmentPath, index, segmentLength, job, cancellationToken).ConfigureAwait(false);
  264. }
  265. await ApiEntryPoint.Instance.TranscodingStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
  266. try
  267. {
  268. if (File.Exists(segmentPath))
  269. {
  270. job = ApiEntryPoint.Instance.GetTranscodingJob(playlistPath, TranscodingJobType);
  271. return await GetSegmentResult(playlistPath, segmentPath, index, segmentLength, job, cancellationToken).ConfigureAwait(false);
  272. }
  273. else
  274. {
  275. var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
  276. if (currentTranscodingIndex == null || index < currentTranscodingIndex.Value || (index - currentTranscodingIndex.Value) > 4)
  277. {
  278. // If the playlist doesn't already exist, startup ffmpeg
  279. try
  280. {
  281. ApiEntryPoint.Instance.KillTranscodingJobs(j => j.Type == TranscodingJobType && string.Equals(j.DeviceId, request.DeviceId, StringComparison.OrdinalIgnoreCase), p => !string.Equals(p, playlistPath, StringComparison.OrdinalIgnoreCase));
  282. if (currentTranscodingIndex.HasValue)
  283. {
  284. DeleteLastFile(playlistPath, segmentExtension, 0);
  285. }
  286. var startSeconds = index * state.SegmentLength;
  287. request.StartTimeTicks = TimeSpan.FromSeconds(startSeconds).Ticks;
  288. job = await StartFfMpeg(state, playlistPath, cancellationTokenSource, Path.GetDirectoryName(playlistPath)).ConfigureAwait(false);
  289. }
  290. catch
  291. {
  292. state.Dispose();
  293. throw;
  294. }
  295. await WaitForMinimumSegmentCount(playlistPath, 2, cancellationTokenSource.Token).ConfigureAwait(false);
  296. }
  297. }
  298. }
  299. finally
  300. {
  301. ApiEntryPoint.Instance.TranscodingStartLock.Release();
  302. }
  303. Logger.Info("waiting for {0}", segmentPath);
  304. while (!File.Exists(segmentPath))
  305. {
  306. await Task.Delay(50, cancellationToken).ConfigureAwait(false);
  307. }
  308. Logger.Info("returning {0}", segmentPath);
  309. job = job ?? ApiEntryPoint.Instance.GetTranscodingJob(playlistPath, TranscodingJobType);
  310. return await GetSegmentResult(playlistPath, segmentPath, index, segmentLength, job, cancellationToken).ConfigureAwait(false);
  311. }
  312. private async Task<object> GetSegmentResult(string playlistPath,
  313. string segmentPath,
  314. int segmentIndex,
  315. int segmentLength,
  316. TranscodingJob transcodingJob,
  317. CancellationToken cancellationToken)
  318. {
  319. // If all transcoding has completed, just return immediately
  320. if (!IsTranscoding(playlistPath))
  321. {
  322. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  323. }
  324. var segmentFilename = Path.GetFileName(segmentPath);
  325. using (var fileStream = FileSystem.GetFileStream(playlistPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  326. {
  327. using (var reader = new StreamReader(fileStream))
  328. {
  329. var text = await reader.ReadToEndAsync().ConfigureAwait(false);
  330. // If it appears in the playlist, it's done
  331. if (text.IndexOf(segmentFilename, StringComparison.OrdinalIgnoreCase) != -1)
  332. {
  333. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  334. }
  335. }
  336. }
  337. // if a different file is encoding, it's done
  338. //var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath);
  339. //if (currentTranscodingIndex > segmentIndex)
  340. //{
  341. //return GetSegmentResult(segmentPath, segmentIndex);
  342. //}
  343. // Wait for the file to stop being written to, then stream it
  344. var length = new FileInfo(segmentPath).Length;
  345. var eofCount = 0;
  346. while (eofCount < 10)
  347. {
  348. var info = new FileInfo(segmentPath);
  349. if (!info.Exists)
  350. {
  351. break;
  352. }
  353. var newLength = info.Length;
  354. if (newLength == length)
  355. {
  356. eofCount++;
  357. }
  358. else
  359. {
  360. eofCount = 0;
  361. }
  362. length = newLength;
  363. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  364. }
  365. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  366. }
  367. private object GetSegmentResult(string segmentPath, int index, int segmentLength, TranscodingJob transcodingJob)
  368. {
  369. var segmentEndingSeconds = (1 + index) * segmentLength;
  370. var segmentEndingPositionTicks = TimeSpan.FromSeconds(segmentEndingSeconds).Ticks;
  371. return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  372. {
  373. Path = segmentPath,
  374. FileShare = FileShare.ReadWrite,
  375. OnComplete = () =>
  376. {
  377. if (transcodingJob != null)
  378. {
  379. transcodingJob.DownloadPositionTicks = Math.Max(transcodingJob.DownloadPositionTicks ?? segmentEndingPositionTicks, segmentEndingPositionTicks);
  380. }
  381. }
  382. });
  383. }
  384. private bool IsTranscoding(string playlistPath)
  385. {
  386. var job = ApiEntryPoint.Instance.GetTranscodingJob(playlistPath, TranscodingJobType);
  387. return job != null && !job.HasExited;
  388. }
  389. public int? GetCurrentTranscodingIndex(string playlist, string segmentExtension)
  390. {
  391. var file = GetLastTranscodingFile(playlist, segmentExtension, FileSystem);
  392. if (file == null)
  393. {
  394. return null;
  395. }
  396. var playlistFilename = Path.GetFileNameWithoutExtension(playlist);
  397. var indexString = Path.GetFileNameWithoutExtension(file.Name).Substring(playlistFilename.Length);
  398. return int.Parse(indexString, NumberStyles.Integer, UsCulture);
  399. }
  400. private void DeleteLastFile(string path, string segmentExtension, int retryCount)
  401. {
  402. if (retryCount >= 5)
  403. {
  404. return;
  405. }
  406. var file = GetLastTranscodingFile(path, segmentExtension, FileSystem);
  407. if (file != null)
  408. {
  409. try
  410. {
  411. FileSystem.DeleteFile(file.FullName);
  412. }
  413. catch (IOException ex)
  414. {
  415. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, file.FullName);
  416. Thread.Sleep(100);
  417. DeleteLastFile(path, segmentExtension, retryCount + 1);
  418. }
  419. catch (Exception ex)
  420. {
  421. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, file.FullName);
  422. }
  423. }
  424. }
  425. private static FileInfo GetLastTranscodingFile(string playlist, string segmentExtension, IFileSystem fileSystem)
  426. {
  427. var folder = Path.GetDirectoryName(playlist);
  428. try
  429. {
  430. return new DirectoryInfo(folder)
  431. .EnumerateFiles("*", SearchOption.TopDirectoryOnly)
  432. .Where(i => string.Equals(i.Extension, segmentExtension, StringComparison.OrdinalIgnoreCase))
  433. .OrderByDescending(fileSystem.GetLastWriteTimeUtc)
  434. .FirstOrDefault();
  435. }
  436. catch (DirectoryNotFoundException)
  437. {
  438. return null;
  439. }
  440. }
  441. protected override int GetStartNumber(StreamState state)
  442. {
  443. return GetStartNumber(state.VideoRequest);
  444. }
  445. private int GetStartNumber(VideoStreamRequest request)
  446. {
  447. var segmentId = "0";
  448. var segmentRequest = request as GetDynamicHlsVideoSegment;
  449. if (segmentRequest != null)
  450. {
  451. segmentId = segmentRequest.SegmentId;
  452. }
  453. return int.Parse(segmentId, NumberStyles.Integer, UsCulture);
  454. }
  455. private string GetSegmentPath(string playlist, string segmentExtension, int index)
  456. {
  457. var folder = Path.GetDirectoryName(playlist);
  458. var filename = Path.GetFileNameWithoutExtension(playlist);
  459. return Path.Combine(folder, filename + index.ToString("000", UsCulture) + segmentExtension);
  460. }
  461. protected override string GetAudioArguments(StreamState state)
  462. {
  463. var codec = state.OutputAudioCodec;
  464. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  465. {
  466. return "-codec:a:0 copy";
  467. }
  468. var args = "-codec:a:0 " + codec;
  469. var channels = state.OutputAudioChannels;
  470. if (channels.HasValue)
  471. {
  472. args += " -ac " + channels.Value;
  473. }
  474. var bitrate = state.OutputAudioBitrate;
  475. if (bitrate.HasValue)
  476. {
  477. args += " -ab " + bitrate.Value.ToString(UsCulture);
  478. }
  479. args += " " + GetAudioFilterParam(state, true);
  480. return args;
  481. }
  482. protected override string GetVideoArguments(StreamState state)
  483. {
  484. var codec = state.OutputVideoCodec;
  485. var args = "-codec:v:0 " + codec;
  486. if (state.EnableMpegtsM2TsMode)
  487. {
  488. args += " -mpegts_m2ts_mode 1";
  489. }
  490. // See if we can save come cpu cycles by avoiding encoding
  491. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  492. {
  493. return state.VideoStream != null && IsH264(state.VideoStream) ?
  494. args + " -bsf:v h264_mp4toannexb" :
  495. args;
  496. }
  497. var keyFrameArg = string.Format(" -force_key_frames expr:gte(t,n_forced*{0})",
  498. state.SegmentLength.ToString(UsCulture));
  499. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream;
  500. args+= " " + GetVideoQualityParam(state, H264Encoder, true) + keyFrameArg;
  501. args += " -r 24 -g 24";
  502. // Add resolution params, if specified
  503. if (!hasGraphicalSubs)
  504. {
  505. args += GetOutputSizeParam(state, codec, false);
  506. }
  507. // This is for internal graphical subs
  508. if (hasGraphicalSubs)
  509. {
  510. args += GetGraphicalSubtitleParam(state, codec);
  511. }
  512. return args;
  513. }
  514. protected override string GetCommandLineArguments(string outputPath, string transcodingJobId, StreamState state, bool isEncoding)
  515. {
  516. // 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
  517. // Good info on i-frames http://blog.streamroot.io/encode-multi-bitrate-videos-mpeg-dash-mse-based-media-players/
  518. var threads = GetNumberOfThreads(state, false);
  519. var inputModifier = GetInputModifier(state);
  520. var args = string.Format("{0} {1} -map_metadata -1 -threads {2} {3} {4} -copyts {5} -f dash -use_template 0 -min_seg_duration 2000 \"{6}\"",
  521. inputModifier,
  522. GetInputArgument(transcodingJobId, state),
  523. threads,
  524. GetMapArgs(state),
  525. GetVideoArguments(state),
  526. GetAudioArguments(state),
  527. outputPath
  528. ).Trim();
  529. return args;
  530. }
  531. /// <summary>
  532. /// Gets the segment file extension.
  533. /// </summary>
  534. /// <param name="state">The state.</param>
  535. /// <returns>System.String.</returns>
  536. protected override string GetSegmentFileExtension(StreamState state)
  537. {
  538. return ".m4s";
  539. }
  540. protected override TranscodingJobType TranscodingJobType
  541. {
  542. get
  543. {
  544. return TranscodingJobType.Dash;
  545. }
  546. }
  547. }
  548. }