MpegDashService.cs 24 KB

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