MpegDashService.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  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.Diagnostics;
  7. using MediaBrowser.Controller.Dlna;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.LiveTv;
  10. using MediaBrowser.Controller.MediaEncoding;
  11. using MediaBrowser.Controller.Net;
  12. using MediaBrowser.Model.IO;
  13. using ServiceStack;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Globalization;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Security;
  20. using System.Text;
  21. using System.Threading;
  22. using System.Threading.Tasks;
  23. using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
  24. namespace MediaBrowser.Api.Playback.Hls
  25. {
  26. /// <summary>
  27. /// Options is needed for chromecast. Threw Head in there since it's related
  28. /// </summary>
  29. [Route("/Videos/{Id}/master.mpd", "GET", Summary = "Gets a video stream using Mpeg dash.")]
  30. [Route("/Videos/{Id}/master.mpd", "HEAD", Summary = "Gets a video stream using Mpeg dash.")]
  31. public class GetMasterManifest : VideoStreamRequest
  32. {
  33. public bool EnableAdaptiveBitrateStreaming { get; set; }
  34. public GetMasterManifest()
  35. {
  36. EnableAdaptiveBitrateStreaming = true;
  37. }
  38. }
  39. [Route("/Videos/{Id}/dash/{SegmentId}.ts", "GET")]
  40. [Route("/Videos/{Id}/dash/{SegmentId}.mp4", "GET")]
  41. public class GetDashSegment : VideoStreamRequest
  42. {
  43. /// <summary>
  44. /// Gets or sets the segment id.
  45. /// </summary>
  46. /// <value>The segment id.</value>
  47. public string SegmentId { get; set; }
  48. }
  49. public class MpegDashService : BaseHlsService
  50. {
  51. public MpegDashService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, ILiveTvManager liveTvManager, IDlnaManager dlnaManager, IChannelManager channelManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IProcessManager processManager, INetworkManager networkManager) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, liveTvManager, dlnaManager, channelManager, subtitleEncoder, deviceManager, processManager)
  52. {
  53. NetworkManager = networkManager;
  54. }
  55. protected INetworkManager NetworkManager { get; private set; }
  56. public object Get(GetMasterManifest request)
  57. {
  58. var result = GetAsync(request, "GET").Result;
  59. return result;
  60. }
  61. public object Head(GetMasterManifest request)
  62. {
  63. var result = GetAsync(request, "HEAD").Result;
  64. return result;
  65. }
  66. private async Task<object> GetAsync(GetMasterManifest request, string method)
  67. {
  68. if (string.Equals(request.AudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
  69. {
  70. throw new ArgumentException("Audio codec copy is not allowed here.");
  71. }
  72. if (string.Equals(request.VideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  73. {
  74. throw new ArgumentException("Video codec copy is not allowed here.");
  75. }
  76. if (string.IsNullOrEmpty(request.MediaSourceId))
  77. {
  78. throw new ArgumentException("MediaSourceId is required");
  79. }
  80. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  81. var playlistText = string.Empty;
  82. if (string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
  83. {
  84. playlistText = GetManifestText(state);
  85. }
  86. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.mpd"), new Dictionary<string, string>());
  87. }
  88. private string GetManifestText(StreamState state)
  89. {
  90. var builder = new StringBuilder();
  91. var time = TimeSpan.FromTicks(state.RunTimeTicks.Value);
  92. var duration = "PT" + time.Hours.ToString("00", UsCulture) + "H" + time.Minutes.ToString("00", UsCulture) + "M" + time.Seconds.ToString("00", UsCulture) + ".00S";
  93. builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  94. var profile = string.Equals(GetSegmentFileExtension(state), ".ts", StringComparison.OrdinalIgnoreCase)
  95. ? "urn:mpeg:dash:profile:mp2t-simple:2011"
  96. : "urn:mpeg:dash:profile:mp2t-simple:2011";
  97. builder.AppendFormat(
  98. "<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+"\">",
  99. duration,
  100. state.SegmentLength.ToString(CultureInfo.InvariantCulture));
  101. builder.Append("<ProgramInformation moreInformationURL=\"http://gpac.sourceforge.net\">");
  102. builder.Append("</ProgramInformation>");
  103. builder.AppendFormat("<Period start=\"PT0S\" duration=\"{0}\">", duration);
  104. builder.Append("<AdaptationSet segmentAlignment=\"true\">");
  105. builder.Append("<ContentComponent id=\"1\" contentType=\"video\"/>");
  106. var lang = state.AudioStream != null ? state.AudioStream.Language : null;
  107. if (string.IsNullOrWhiteSpace(lang)) lang = "und";
  108. builder.AppendFormat("<ContentComponent id=\"2\" contentType=\"audio\" lang=\"{0}\"/>", lang);
  109. builder.Append(GetRepresentationOpenElement(state, lang));
  110. AppendSegmentList(state, builder);
  111. builder.Append("</Representation>");
  112. builder.Append("</AdaptationSet>");
  113. builder.Append("</Period>");
  114. builder.Append("</MPD>");
  115. return builder.ToString();
  116. }
  117. private string GetRepresentationOpenElement(StreamState state, string language)
  118. {
  119. var codecs = GetVideoCodecDescriptor(state) + "," + GetAudioCodecDescriptor(state);
  120. var mime = string.Equals(GetSegmentFileExtension(state), ".ts", StringComparison.OrdinalIgnoreCase)
  121. ? "video/mp2t"
  122. : "video/mp4";
  123. var xml = "<Representation id=\"1\" mimeType=\"" + mime + "\" startWithSAP=\"1\" codecs=\"" + codecs + "\"";
  124. if (state.OutputWidth.HasValue)
  125. {
  126. xml += " width=\"" + state.OutputWidth.Value.ToString(UsCulture) + "\"";
  127. }
  128. if (state.OutputHeight.HasValue)
  129. {
  130. xml += " height=\"" + state.OutputHeight.Value.ToString(UsCulture) + "\"";
  131. }
  132. if (state.OutputAudioSampleRate.HasValue)
  133. {
  134. xml += " sampleRate=\"" + state.OutputAudioSampleRate.Value.ToString(UsCulture) + "\"";
  135. }
  136. if (state.TotalOutputBitrate.HasValue)
  137. {
  138. xml += " bandwidth=\"" + state.TotalOutputBitrate.Value.ToString(UsCulture) + "\"";
  139. }
  140. xml += ">";
  141. return xml;
  142. }
  143. private string GetVideoCodecDescriptor(StreamState state)
  144. {
  145. // https://developer.apple.com/library/ios/documentation/networkinginternet/conceptual/streamingmediaguide/FrequentlyAskedQuestions/FrequentlyAskedQuestions.html
  146. // http://www.chipwreck.de/blog/2010/02/25/html-5-video-tag-and-attributes/
  147. var level = state.TargetVideoLevel ?? 0;
  148. var profile = state.TargetVideoProfile ?? string.Empty;
  149. if (profile.IndexOf("high", StringComparison.OrdinalIgnoreCase) != -1)
  150. {
  151. if (level >= 4.1)
  152. {
  153. return "avc1.640028";
  154. }
  155. if (level >= 4)
  156. {
  157. return "avc1.640028";
  158. }
  159. return "avc1.64001f";
  160. }
  161. if (profile.IndexOf("main", StringComparison.OrdinalIgnoreCase) != -1)
  162. {
  163. if (level >= 4)
  164. {
  165. return "avc1.4d0028";
  166. }
  167. if (level >= 3.1)
  168. {
  169. return "avc1.4d001f";
  170. }
  171. return "avc1.4d001e";
  172. }
  173. if (level >= 3.1)
  174. {
  175. return "avc1.42001f";
  176. }
  177. return "avc1.42E01E";
  178. }
  179. private string GetAudioCodecDescriptor(StreamState state)
  180. {
  181. // https://developer.apple.com/library/ios/documentation/networkinginternet/conceptual/streamingmediaguide/FrequentlyAskedQuestions/FrequentlyAskedQuestions.html
  182. if (string.Equals(state.OutputAudioCodec, "mp3", StringComparison.OrdinalIgnoreCase))
  183. {
  184. return "mp4a.40.34";
  185. }
  186. // AAC 5ch
  187. if (state.OutputAudioChannels.HasValue && state.OutputAudioChannels.Value >= 5)
  188. {
  189. return "mp4a.40.5";
  190. }
  191. // AAC 2ch
  192. return "mp4a.40.2";
  193. }
  194. public object Get(GetDashSegment request)
  195. {
  196. return GetDynamicSegment(request, request.SegmentId).Result;
  197. }
  198. private void AppendSegmentList(StreamState state, StringBuilder builder)
  199. {
  200. var extension = GetSegmentFileExtension(state);
  201. var seconds = TimeSpan.FromTicks(state.RunTimeTicks ?? 0).TotalSeconds;
  202. var queryStringIndex = Request.RawUrl.IndexOf('?');
  203. var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
  204. var index = 0;
  205. builder.Append("<SegmentList timescale=\"1000\" duration=\"10000\">");
  206. while (seconds > 0)
  207. {
  208. var segmentUrl = string.Format("dash/{0}{1}{2}",
  209. index.ToString(UsCulture),
  210. extension,
  211. SecurityElement.Escape(queryString));
  212. if (index == 0)
  213. {
  214. builder.AppendFormat("<Initialization sourceURL=\"{0}\"/>", segmentUrl);
  215. }
  216. else
  217. {
  218. builder.AppendFormat("<SegmentURL media=\"{0}\"/>", segmentUrl);
  219. }
  220. seconds -= state.SegmentLength;
  221. index++;
  222. }
  223. builder.Append("</SegmentList>");
  224. }
  225. private async Task<object> GetDynamicSegment(VideoStreamRequest request, string segmentId)
  226. {
  227. if ((request.StartTimeTicks ?? 0) > 0)
  228. {
  229. throw new ArgumentException("StartTimeTicks is not allowed.");
  230. }
  231. var cancellationTokenSource = new CancellationTokenSource();
  232. var cancellationToken = cancellationTokenSource.Token;
  233. var index = int.Parse(segmentId, NumberStyles.Integer, UsCulture);
  234. var state = await GetState(request, cancellationToken).ConfigureAwait(false);
  235. var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8");
  236. var segmentExtension = GetSegmentFileExtension(state);
  237. var segmentPath = GetSegmentPath(playlistPath, segmentExtension, index);
  238. var segmentLength = state.SegmentLength;
  239. TranscodingJob job = null;
  240. if (File.Exists(segmentPath))
  241. {
  242. return await GetSegmentResult(playlistPath, segmentPath, index, segmentLength, job, cancellationToken).ConfigureAwait(false);
  243. }
  244. await ApiEntryPoint.Instance.TranscodingStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
  245. try
  246. {
  247. if (File.Exists(segmentPath))
  248. {
  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. FileSystem.DeleteFile(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. var args = "-codec:v:0 " + codec;
  464. if (state.EnableMpegtsM2TsMode)
  465. {
  466. args += " -mpegts_m2ts_mode 1";
  467. }
  468. // See if we can save come cpu cycles by avoiding encoding
  469. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  470. {
  471. return state.VideoStream != null && IsH264(state.VideoStream) ?
  472. args + " -bsf:v h264_mp4toannexb" :
  473. args;
  474. }
  475. var keyFrameArg = string.Format(" -force_key_frames expr:gte(t,n_forced*{0})",
  476. state.SegmentLength.ToString(UsCulture));
  477. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream;
  478. args+= " " + GetVideoQualityParam(state, H264Encoder, true) + keyFrameArg;
  479. args += " -r 24 -g 24";
  480. // Add resolution params, if specified
  481. if (!hasGraphicalSubs)
  482. {
  483. args += GetOutputSizeParam(state, codec, false);
  484. }
  485. // This is for internal graphical subs
  486. if (hasGraphicalSubs)
  487. {
  488. args += GetGraphicalSubtitleParam(state, codec);
  489. }
  490. return args;
  491. }
  492. protected override string GetCommandLineArguments(string outputPath, string transcodingJobId, StreamState state, bool isEncoding)
  493. {
  494. // 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
  495. // Good info on i-frames http://blog.streamroot.io/encode-multi-bitrate-videos-mpeg-dash-mse-based-media-players/
  496. var threads = GetNumberOfThreads(state, false);
  497. var inputModifier = GetInputModifier(state);
  498. // If isEncoding is true we're actually starting ffmpeg
  499. var startNumberParam = isEncoding ? GetStartNumber(state).ToString(UsCulture) : "0";
  500. var segmentFilename = Path.GetFileNameWithoutExtension(outputPath) + "%03d" + GetSegmentFileExtension(state);
  501. 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}",
  502. inputModifier,
  503. GetInputArgument(transcodingJobId, state),
  504. threads,
  505. GetMapArgs(state),
  506. GetVideoArguments(state),
  507. GetAudioArguments(state),
  508. state.SegmentLength.ToString(UsCulture),
  509. startNumberParam,
  510. state.HlsListSize.ToString(UsCulture),
  511. outputPath,
  512. segmentFilename
  513. ).Trim();
  514. return args;
  515. }
  516. /// <summary>
  517. /// Gets the segment file extension.
  518. /// </summary>
  519. /// <param name="state">The state.</param>
  520. /// <returns>System.String.</returns>
  521. protected override string GetSegmentFileExtension(StreamState state)
  522. {
  523. return ".mp4";
  524. }
  525. protected override TranscodingJobType TranscodingJobType
  526. {
  527. get
  528. {
  529. return TranscodingJobType.Dash;
  530. }
  531. }
  532. }
  533. }