MpegDashService.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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. var duration = 1000000 * state.SegmentLength;
  225. builder.AppendFormat("<SegmentList timescale=\"1000000\" duration=\"{0}\" startNumber=\"1\">", duration.ToString(CultureInfo.InvariantCulture));
  226. while (seconds > 0)
  227. {
  228. var segmentUrl = string.Format("dash/{3}/{0}{1}{2}",
  229. index.ToString(UsCulture),
  230. extension,
  231. SecurityElement.Escape(queryString),
  232. type);
  233. if (index == 0)
  234. {
  235. builder.AppendFormat("<Initialization sourceURL=\"{0}\"/>", segmentUrl);
  236. }
  237. else
  238. {
  239. builder.AppendFormat("<SegmentURL media=\"{0}\"/>", segmentUrl);
  240. }
  241. seconds -= state.SegmentLength;
  242. index++;
  243. }
  244. builder.Append("</SegmentList>");
  245. }
  246. private async Task<object> GetDynamicSegment(VideoStreamRequest request, string segmentId)
  247. {
  248. if ((request.StartTimeTicks ?? 0) > 0)
  249. {
  250. throw new ArgumentException("StartTimeTicks is not allowed.");
  251. }
  252. var cancellationTokenSource = new CancellationTokenSource();
  253. var cancellationToken = cancellationTokenSource.Token;
  254. var index = int.Parse(segmentId, NumberStyles.Integer, UsCulture);
  255. var state = await GetState(request, cancellationToken).ConfigureAwait(false);
  256. var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".mpd");
  257. var segmentExtension = GetSegmentFileExtension(state);
  258. var segmentPath = GetSegmentPath(playlistPath, segmentExtension, index);
  259. var segmentLength = state.SegmentLength;
  260. TranscodingJob job = null;
  261. if (File.Exists(segmentPath))
  262. {
  263. job = ApiEntryPoint.Instance.GetTranscodingJob(playlistPath, TranscodingJobType);
  264. return await GetSegmentResult(playlistPath, segmentPath, index, segmentLength, job, cancellationToken).ConfigureAwait(false);
  265. }
  266. await ApiEntryPoint.Instance.TranscodingStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
  267. try
  268. {
  269. if (File.Exists(segmentPath))
  270. {
  271. job = ApiEntryPoint.Instance.GetTranscodingJob(playlistPath, TranscodingJobType);
  272. return await GetSegmentResult(playlistPath, segmentPath, index, segmentLength, job, cancellationToken).ConfigureAwait(false);
  273. }
  274. else
  275. {
  276. var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
  277. if (currentTranscodingIndex == null || index < currentTranscodingIndex.Value || (index - currentTranscodingIndex.Value) > 4)
  278. {
  279. // If the playlist doesn't already exist, startup ffmpeg
  280. try
  281. {
  282. ApiEntryPoint.Instance.KillTranscodingJobs(j => j.Type == TranscodingJobType && string.Equals(j.DeviceId, request.DeviceId, StringComparison.OrdinalIgnoreCase), p => !string.Equals(p, playlistPath, StringComparison.OrdinalIgnoreCase));
  283. if (currentTranscodingIndex.HasValue)
  284. {
  285. DeleteLastFile(playlistPath, segmentExtension, 0);
  286. }
  287. var startSeconds = index * state.SegmentLength;
  288. request.StartTimeTicks = TimeSpan.FromSeconds(startSeconds).Ticks;
  289. job = await StartFfMpeg(state, playlistPath, cancellationTokenSource, Path.GetDirectoryName(playlistPath)).ConfigureAwait(false);
  290. }
  291. catch
  292. {
  293. state.Dispose();
  294. throw;
  295. }
  296. await WaitForMinimumSegmentCount(playlistPath, 2, cancellationTokenSource.Token).ConfigureAwait(false);
  297. }
  298. }
  299. }
  300. finally
  301. {
  302. ApiEntryPoint.Instance.TranscodingStartLock.Release();
  303. }
  304. Logger.Info("waiting for {0}", segmentPath);
  305. while (!File.Exists(segmentPath))
  306. {
  307. await Task.Delay(50, cancellationToken).ConfigureAwait(false);
  308. }
  309. Logger.Info("returning {0}", segmentPath);
  310. job = job ?? ApiEntryPoint.Instance.GetTranscodingJob(playlistPath, TranscodingJobType);
  311. return await GetSegmentResult(playlistPath, segmentPath, index, segmentLength, job, cancellationToken).ConfigureAwait(false);
  312. }
  313. private async Task<object> GetSegmentResult(string playlistPath,
  314. string segmentPath,
  315. int segmentIndex,
  316. int segmentLength,
  317. TranscodingJob transcodingJob,
  318. CancellationToken cancellationToken)
  319. {
  320. // If all transcoding has completed, just return immediately
  321. if (!IsTranscoding(playlistPath))
  322. {
  323. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  324. }
  325. var segmentFilename = Path.GetFileName(segmentPath);
  326. using (var fileStream = FileSystem.GetFileStream(playlistPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  327. {
  328. using (var reader = new StreamReader(fileStream))
  329. {
  330. var text = await reader.ReadToEndAsync().ConfigureAwait(false);
  331. // If it appears in the playlist, it's done
  332. if (text.IndexOf(segmentFilename, StringComparison.OrdinalIgnoreCase) != -1)
  333. {
  334. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  335. }
  336. }
  337. }
  338. // if a different file is encoding, it's done
  339. //var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath);
  340. //if (currentTranscodingIndex > segmentIndex)
  341. //{
  342. //return GetSegmentResult(segmentPath, segmentIndex);
  343. //}
  344. // Wait for the file to stop being written to, then stream it
  345. var length = new FileInfo(segmentPath).Length;
  346. var eofCount = 0;
  347. while (eofCount < 10)
  348. {
  349. var info = new FileInfo(segmentPath);
  350. if (!info.Exists)
  351. {
  352. break;
  353. }
  354. var newLength = info.Length;
  355. if (newLength == length)
  356. {
  357. eofCount++;
  358. }
  359. else
  360. {
  361. eofCount = 0;
  362. }
  363. length = newLength;
  364. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  365. }
  366. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  367. }
  368. private object GetSegmentResult(string segmentPath, int index, int segmentLength, TranscodingJob transcodingJob)
  369. {
  370. var segmentEndingSeconds = (1 + index) * segmentLength;
  371. var segmentEndingPositionTicks = TimeSpan.FromSeconds(segmentEndingSeconds).Ticks;
  372. return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  373. {
  374. Path = segmentPath,
  375. FileShare = FileShare.ReadWrite,
  376. OnComplete = () =>
  377. {
  378. if (transcodingJob != null)
  379. {
  380. transcodingJob.DownloadPositionTicks = Math.Max(transcodingJob.DownloadPositionTicks ?? segmentEndingPositionTicks, segmentEndingPositionTicks);
  381. }
  382. }
  383. });
  384. }
  385. private bool IsTranscoding(string playlistPath)
  386. {
  387. var job = ApiEntryPoint.Instance.GetTranscodingJob(playlistPath, TranscodingJobType);
  388. return job != null && !job.HasExited;
  389. }
  390. public int? GetCurrentTranscodingIndex(string playlist, string segmentExtension)
  391. {
  392. var file = GetLastTranscodingFile(playlist, segmentExtension, FileSystem);
  393. if (file == null)
  394. {
  395. return null;
  396. }
  397. var playlistFilename = Path.GetFileNameWithoutExtension(playlist);
  398. var indexString = Path.GetFileNameWithoutExtension(file.Name).Substring(playlistFilename.Length);
  399. return int.Parse(indexString, NumberStyles.Integer, UsCulture);
  400. }
  401. private void DeleteLastFile(string path, string segmentExtension, int retryCount)
  402. {
  403. if (retryCount >= 5)
  404. {
  405. return;
  406. }
  407. var file = GetLastTranscodingFile(path, segmentExtension, FileSystem);
  408. if (file != null)
  409. {
  410. try
  411. {
  412. FileSystem.DeleteFile(file.FullName);
  413. }
  414. catch (IOException ex)
  415. {
  416. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, file.FullName);
  417. Thread.Sleep(100);
  418. DeleteLastFile(path, segmentExtension, retryCount + 1);
  419. }
  420. catch (Exception ex)
  421. {
  422. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, file.FullName);
  423. }
  424. }
  425. }
  426. private static FileInfo GetLastTranscodingFile(string playlist, string segmentExtension, IFileSystem fileSystem)
  427. {
  428. var folder = Path.GetDirectoryName(playlist);
  429. try
  430. {
  431. return new DirectoryInfo(folder)
  432. .EnumerateFiles("*", SearchOption.TopDirectoryOnly)
  433. .Where(i => string.Equals(i.Extension, segmentExtension, StringComparison.OrdinalIgnoreCase))
  434. .OrderByDescending(fileSystem.GetLastWriteTimeUtc)
  435. .FirstOrDefault();
  436. }
  437. catch (DirectoryNotFoundException)
  438. {
  439. return null;
  440. }
  441. }
  442. protected override int GetStartNumber(StreamState state)
  443. {
  444. return GetStartNumber(state.VideoRequest);
  445. }
  446. private int GetStartNumber(VideoStreamRequest request)
  447. {
  448. var segmentId = "0";
  449. var segmentRequest = request as GetDynamicHlsVideoSegment;
  450. if (segmentRequest != null)
  451. {
  452. segmentId = segmentRequest.SegmentId;
  453. }
  454. return int.Parse(segmentId, NumberStyles.Integer, UsCulture);
  455. }
  456. private string GetSegmentPath(string playlist, string segmentExtension, int index)
  457. {
  458. var folder = Path.GetDirectoryName(playlist);
  459. var filename = Path.GetFileNameWithoutExtension(playlist);
  460. return Path.Combine(folder, filename + index.ToString("000", UsCulture) + segmentExtension);
  461. }
  462. protected override string GetAudioArguments(StreamState state)
  463. {
  464. var codec = state.OutputAudioCodec;
  465. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  466. {
  467. return "-codec:a:0 copy";
  468. }
  469. var args = "-codec:a:0 " + codec;
  470. var channels = state.OutputAudioChannels;
  471. if (channels.HasValue)
  472. {
  473. args += " -ac " + channels.Value;
  474. }
  475. var bitrate = state.OutputAudioBitrate;
  476. if (bitrate.HasValue)
  477. {
  478. args += " -ab " + bitrate.Value.ToString(UsCulture);
  479. }
  480. args += " " + GetAudioFilterParam(state, true);
  481. return args;
  482. }
  483. protected override string GetVideoArguments(StreamState state)
  484. {
  485. var codec = state.OutputVideoCodec;
  486. var args = "-codec:v:0 " + codec;
  487. if (state.EnableMpegtsM2TsMode)
  488. {
  489. args += " -mpegts_m2ts_mode 1";
  490. }
  491. // See if we can save come cpu cycles by avoiding encoding
  492. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  493. {
  494. return state.VideoStream != null && IsH264(state.VideoStream) ?
  495. args + " -bsf:v h264_mp4toannexb" :
  496. args;
  497. }
  498. var keyFrameArg = string.Format(" -force_key_frames expr:gte(t,n_forced*{0})",
  499. state.SegmentLength.ToString(UsCulture));
  500. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream;
  501. args+= " " + GetVideoQualityParam(state, H264Encoder, true) + keyFrameArg;
  502. args += " -r 24 -g 24";
  503. // Add resolution params, if specified
  504. if (!hasGraphicalSubs)
  505. {
  506. args += GetOutputSizeParam(state, codec, false);
  507. }
  508. // This is for internal graphical subs
  509. if (hasGraphicalSubs)
  510. {
  511. args += GetGraphicalSubtitleParam(state, codec);
  512. }
  513. return args;
  514. }
  515. protected override string GetCommandLineArguments(string outputPath, string transcodingJobId, StreamState state, bool isEncoding)
  516. {
  517. // 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
  518. // Good info on i-frames http://blog.streamroot.io/encode-multi-bitrate-videos-mpeg-dash-mse-based-media-players/
  519. var threads = GetNumberOfThreads(state, false);
  520. var inputModifier = GetInputModifier(state);
  521. 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}\"",
  522. inputModifier,
  523. GetInputArgument(transcodingJobId, state),
  524. threads,
  525. GetMapArgs(state),
  526. GetVideoArguments(state),
  527. GetAudioArguments(state),
  528. outputPath
  529. ).Trim();
  530. return args;
  531. }
  532. /// <summary>
  533. /// Gets the segment file extension.
  534. /// </summary>
  535. /// <param name="state">The state.</param>
  536. /// <returns>System.String.</returns>
  537. protected override string GetSegmentFileExtension(StreamState state)
  538. {
  539. return ".m4s";
  540. }
  541. protected override TranscodingJobType TranscodingJobType
  542. {
  543. get
  544. {
  545. return TranscodingJobType.Dash;
  546. }
  547. }
  548. }
  549. }