MpegDashService.cs 25 KB

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