MpegDashService.cs 25 KB

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