BaseStreamingService.cs 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906
  1. using System.Text;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.IO;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Dlna;
  6. using MediaBrowser.Controller.Dto;
  7. using MediaBrowser.Controller.Entities;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.LiveTv;
  10. using MediaBrowser.Controller.MediaEncoding;
  11. using MediaBrowser.Controller.Persistence;
  12. using MediaBrowser.Model.Configuration;
  13. using MediaBrowser.Model.Dlna;
  14. using MediaBrowser.Model.Drawing;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.Model.IO;
  17. using MediaBrowser.Model.Library;
  18. using MediaBrowser.Model.LiveTv;
  19. using System;
  20. using System.Collections.Generic;
  21. using System.Diagnostics;
  22. using System.Globalization;
  23. using System.IO;
  24. using System.Linq;
  25. using System.Threading;
  26. using System.Threading.Tasks;
  27. namespace MediaBrowser.Api.Playback
  28. {
  29. /// <summary>
  30. /// Class BaseStreamingService
  31. /// </summary>
  32. public abstract class BaseStreamingService : BaseApiService
  33. {
  34. /// <summary>
  35. /// Gets or sets the application paths.
  36. /// </summary>
  37. /// <value>The application paths.</value>
  38. protected IServerConfigurationManager ServerConfigurationManager { get; private set; }
  39. /// <summary>
  40. /// Gets or sets the user manager.
  41. /// </summary>
  42. /// <value>The user manager.</value>
  43. protected IUserManager UserManager { get; private set; }
  44. /// <summary>
  45. /// Gets or sets the library manager.
  46. /// </summary>
  47. /// <value>The library manager.</value>
  48. protected ILibraryManager LibraryManager { get; private set; }
  49. /// <summary>
  50. /// Gets or sets the iso manager.
  51. /// </summary>
  52. /// <value>The iso manager.</value>
  53. protected IIsoManager IsoManager { get; private set; }
  54. /// <summary>
  55. /// Gets or sets the media encoder.
  56. /// </summary>
  57. /// <value>The media encoder.</value>
  58. protected IMediaEncoder MediaEncoder { get; private set; }
  59. protected IEncodingManager EncodingManager { get; private set; }
  60. protected IDtoService DtoService { get; private set; }
  61. protected IFileSystem FileSystem { get; private set; }
  62. protected IItemRepository ItemRepository { get; private set; }
  63. protected ILiveTvManager LiveTvManager { get; private set; }
  64. protected IDlnaManager DlnaManager { get; private set; }
  65. /// <summary>
  66. /// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
  67. /// </summary>
  68. /// <param name="serverConfig">The server configuration.</param>
  69. /// <param name="userManager">The user manager.</param>
  70. /// <param name="libraryManager">The library manager.</param>
  71. /// <param name="isoManager">The iso manager.</param>
  72. /// <param name="mediaEncoder">The media encoder.</param>
  73. /// <param name="dtoService">The dto service.</param>
  74. /// <param name="fileSystem">The file system.</param>
  75. /// <param name="itemRepository">The item repository.</param>
  76. protected BaseStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IDtoService dtoService, IFileSystem fileSystem, IItemRepository itemRepository, ILiveTvManager liveTvManager, IEncodingManager encodingManager, IDlnaManager dlnaManager)
  77. {
  78. DlnaManager = dlnaManager;
  79. EncodingManager = encodingManager;
  80. LiveTvManager = liveTvManager;
  81. ItemRepository = itemRepository;
  82. FileSystem = fileSystem;
  83. DtoService = dtoService;
  84. ServerConfigurationManager = serverConfig;
  85. UserManager = userManager;
  86. LibraryManager = libraryManager;
  87. IsoManager = isoManager;
  88. MediaEncoder = mediaEncoder;
  89. }
  90. /// <summary>
  91. /// Gets the command line arguments.
  92. /// </summary>
  93. /// <param name="outputPath">The output path.</param>
  94. /// <param name="state">The state.</param>
  95. /// <param name="performSubtitleConversions">if set to <c>true</c> [perform subtitle conversions].</param>
  96. /// <returns>System.String.</returns>
  97. protected abstract string GetCommandLineArguments(string outputPath, StreamState state, bool performSubtitleConversions);
  98. /// <summary>
  99. /// Gets the type of the transcoding job.
  100. /// </summary>
  101. /// <value>The type of the transcoding job.</value>
  102. protected abstract TranscodingJobType TranscodingJobType { get; }
  103. /// <summary>
  104. /// Gets the output file extension.
  105. /// </summary>
  106. /// <param name="state">The state.</param>
  107. /// <returns>System.String.</returns>
  108. protected virtual string GetOutputFileExtension(StreamState state)
  109. {
  110. return Path.GetExtension(state.RequestedUrl);
  111. }
  112. /// <summary>
  113. /// Gets the output file path.
  114. /// </summary>
  115. /// <param name="state">The state.</param>
  116. /// <returns>System.String.</returns>
  117. protected virtual string GetOutputFilePath(StreamState state)
  118. {
  119. var folder = ServerConfigurationManager.ApplicationPaths.TranscodingTempPath;
  120. var outputFileExtension = GetOutputFileExtension(state);
  121. return Path.Combine(folder, GetCommandLineArguments("dummy\\dummy", state, false).GetMD5() + (outputFileExtension ?? string.Empty).ToLower());
  122. }
  123. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  124. /// <summary>
  125. /// The fast seek offset seconds
  126. /// </summary>
  127. private const int FastSeekOffsetSeconds = 1;
  128. /// <summary>
  129. /// Gets the fast seek command line parameter.
  130. /// </summary>
  131. /// <param name="request">The request.</param>
  132. /// <returns>System.String.</returns>
  133. /// <value>The fast seek command line parameter.</value>
  134. protected string GetFastSeekCommandLineParameter(StreamRequest request)
  135. {
  136. var time = request.StartTimeTicks;
  137. if (time.HasValue)
  138. {
  139. var seconds = TimeSpan.FromTicks(time.Value).TotalSeconds;
  140. if (seconds > 0)
  141. {
  142. return string.Format("-ss {0}", seconds.ToString(UsCulture));
  143. }
  144. }
  145. return string.Empty;
  146. }
  147. /// <summary>
  148. /// Gets the slow seek command line parameter.
  149. /// </summary>
  150. /// <param name="request">The request.</param>
  151. /// <returns>System.String.</returns>
  152. /// <value>The slow seek command line parameter.</value>
  153. protected string GetSlowSeekCommandLineParameter(StreamRequest request)
  154. {
  155. return string.Empty;
  156. }
  157. /// <summary>
  158. /// Gets the map args.
  159. /// </summary>
  160. /// <param name="state">The state.</param>
  161. /// <returns>System.String.</returns>
  162. protected virtual string GetMapArgs(StreamState state)
  163. {
  164. var args = string.Empty;
  165. if (state.IsRemote || !state.HasMediaStreams)
  166. {
  167. return string.Empty;
  168. }
  169. if (state.VideoStream != null)
  170. {
  171. args += string.Format("-map 0:{0}", state.VideoStream.Index);
  172. }
  173. else
  174. {
  175. args += "-map -0:v";
  176. }
  177. if (state.AudioStream != null)
  178. {
  179. args += string.Format(" -map 0:{0}", state.AudioStream.Index);
  180. }
  181. else
  182. {
  183. args += " -map -0:a";
  184. }
  185. if (state.SubtitleStream == null)
  186. {
  187. args += " -map -0:s";
  188. }
  189. return args;
  190. }
  191. /// <summary>
  192. /// Determines which stream will be used for playback
  193. /// </summary>
  194. /// <param name="allStream">All stream.</param>
  195. /// <param name="desiredIndex">Index of the desired.</param>
  196. /// <param name="type">The type.</param>
  197. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  198. /// <returns>MediaStream.</returns>
  199. private MediaStream GetMediaStream(IEnumerable<MediaStream> allStream, int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  200. {
  201. var streams = allStream.Where(s => s.Type == type).OrderBy(i => i.Index).ToList();
  202. if (desiredIndex.HasValue)
  203. {
  204. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  205. if (stream != null)
  206. {
  207. return stream;
  208. }
  209. }
  210. if (type == MediaStreamType.Video)
  211. {
  212. streams = streams.Where(i => !string.Equals(i.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase)).ToList();
  213. }
  214. if (returnFirstIfNoIndex && type == MediaStreamType.Audio)
  215. {
  216. return streams.FirstOrDefault(i => i.Channels.HasValue && i.Channels.Value > 0) ??
  217. streams.FirstOrDefault();
  218. }
  219. // Just return the first one
  220. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  221. }
  222. protected EncodingQuality GetQualitySetting()
  223. {
  224. var quality = ServerConfigurationManager.Configuration.MediaEncodingQuality;
  225. if (quality == EncodingQuality.Auto)
  226. {
  227. var cpuCount = Environment.ProcessorCount;
  228. if (cpuCount >= 4)
  229. {
  230. //return EncodingQuality.HighQuality;
  231. }
  232. return EncodingQuality.HighSpeed;
  233. }
  234. return quality;
  235. }
  236. /// <summary>
  237. /// Gets the number of threads.
  238. /// </summary>
  239. /// <returns>System.Int32.</returns>
  240. /// <exception cref="System.Exception">Unrecognized MediaEncodingQuality value.</exception>
  241. protected int GetNumberOfThreads(StreamState state, bool isWebm)
  242. {
  243. // Use more when this is true. -re will keep cpu usage under control
  244. if (state.ReadInputAtNativeFramerate)
  245. {
  246. if (isWebm)
  247. {
  248. return Math.Max(Environment.ProcessorCount - 1, 2);
  249. }
  250. return 0;
  251. }
  252. // Webm: http://www.webmproject.org/docs/encoder-parameters/
  253. // The decoder will usually automatically use an appropriate number of threads according to how many cores are available but it can only use multiple threads
  254. // for the coefficient data if the encoder selected --token-parts > 0 at encode time.
  255. switch (GetQualitySetting())
  256. {
  257. case EncodingQuality.HighSpeed:
  258. return 2;
  259. case EncodingQuality.HighQuality:
  260. return isWebm ? Math.Max(Environment.ProcessorCount - 1, 2) : 0;
  261. case EncodingQuality.MaxQuality:
  262. return isWebm ? Math.Max(Environment.ProcessorCount - 1, 2) : 0;
  263. default:
  264. throw new Exception("Unrecognized MediaEncodingQuality value.");
  265. }
  266. }
  267. /// <summary>
  268. /// Gets the video bitrate to specify on the command line
  269. /// </summary>
  270. /// <param name="state">The state.</param>
  271. /// <param name="videoCodec">The video codec.</param>
  272. /// <param name="isHls">if set to <c>true</c> [is HLS].</param>
  273. /// <returns>System.String.</returns>
  274. protected string GetVideoQualityParam(StreamState state, string videoCodec, bool isHls)
  275. {
  276. var param = string.Empty;
  277. var isVc1 = state.VideoStream != null &&
  278. string.Equals(state.VideoStream.Codec, "vc1", StringComparison.OrdinalIgnoreCase);
  279. var qualitySetting = GetQualitySetting();
  280. if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
  281. {
  282. switch (qualitySetting)
  283. {
  284. case EncodingQuality.HighSpeed:
  285. param = "-preset ultrafast";
  286. break;
  287. case EncodingQuality.HighQuality:
  288. param = "-preset superfast";
  289. break;
  290. case EncodingQuality.MaxQuality:
  291. param = "-preset superfast";
  292. break;
  293. }
  294. switch (qualitySetting)
  295. {
  296. case EncodingQuality.HighSpeed:
  297. param += " -crf 23";
  298. break;
  299. case EncodingQuality.HighQuality:
  300. param += " -crf 20";
  301. break;
  302. case EncodingQuality.MaxQuality:
  303. param += " -crf 18";
  304. break;
  305. }
  306. }
  307. // webm
  308. else if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  309. {
  310. // Values 0-3, 0 being highest quality but slower
  311. var profileScore = 0;
  312. string crf;
  313. switch (qualitySetting)
  314. {
  315. case EncodingQuality.HighSpeed:
  316. crf = "18";
  317. profileScore++;
  318. break;
  319. case EncodingQuality.HighQuality:
  320. crf = "10";
  321. break;
  322. case EncodingQuality.MaxQuality:
  323. crf = "4";
  324. break;
  325. default:
  326. throw new ArgumentException("Unrecognized quality setting");
  327. }
  328. if (isVc1)
  329. {
  330. profileScore++;
  331. }
  332. // http://www.webmproject.org/docs/encoder-parameters/
  333. param = string.Format("-speed 16 -quality good -profile:v {0} -slices 8 -crf {1}",
  334. profileScore.ToString(UsCulture),
  335. crf);
  336. }
  337. else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase))
  338. {
  339. param = "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  340. }
  341. // asf/wmv
  342. else if (string.Equals(videoCodec, "wmv2", StringComparison.OrdinalIgnoreCase))
  343. {
  344. param = "-qmin 2";
  345. }
  346. else if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  347. {
  348. param = "-mbd 2";
  349. }
  350. param += GetVideoBitrateParam(state, videoCodec, isHls);
  351. var framerate = GetFramerateParam(state);
  352. if (framerate.HasValue)
  353. {
  354. param += string.Format(" -r {0}", framerate.Value.ToString(UsCulture));
  355. }
  356. if (!string.IsNullOrEmpty(state.VideoSync))
  357. {
  358. param += " -vsync " + state.VideoSync;
  359. }
  360. if (!string.IsNullOrEmpty(state.VideoRequest.Profile))
  361. {
  362. param += " -profile:v " + state.VideoRequest.Profile;
  363. }
  364. if (!string.IsNullOrEmpty(state.VideoRequest.Level))
  365. {
  366. param += " -level " + state.VideoRequest.Level;
  367. }
  368. return param;
  369. }
  370. protected string GetAudioFilterParam(StreamState state, bool isHls)
  371. {
  372. var volParam = string.Empty;
  373. var audioSampleRate = string.Empty;
  374. var channels = GetNumAudioChannelsParam(state.Request, state.AudioStream);
  375. // Boost volume to 200% when downsampling from 6ch to 2ch
  376. if (channels.HasValue && channels.Value <= 2 && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5)
  377. {
  378. volParam = ",volume=2.000000";
  379. }
  380. if (state.Request.AudioSampleRate.HasValue)
  381. {
  382. audioSampleRate = state.Request.AudioSampleRate.Value + ":";
  383. }
  384. var adelay = isHls ? "adelay=1," : string.Empty;
  385. var pts = string.Empty;
  386. if (state.SubtitleStream != null)
  387. {
  388. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  389. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  390. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  391. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  392. {
  393. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  394. pts = string.Format(",asetpts=PTS-{0}/TB",
  395. Math.Round(seconds).ToString(UsCulture));
  396. }
  397. }
  398. return string.Format("-af \"{0}aresample={1}async={4}{2}{3}\"",
  399. adelay,
  400. audioSampleRate,
  401. volParam,
  402. pts,
  403. state.AudioSync);
  404. }
  405. /// <summary>
  406. /// If we're going to put a fixed size on the command line, this will calculate it
  407. /// </summary>
  408. /// <param name="state">The state.</param>
  409. /// <param name="outputVideoCodec">The output video codec.</param>
  410. /// <param name="performTextSubtitleConversion">if set to <c>true</c> [perform text subtitle conversion].</param>
  411. /// <returns>System.String.</returns>
  412. protected string GetOutputSizeParam(StreamState state, string outputVideoCodec, bool performTextSubtitleConversion)
  413. {
  414. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  415. var assSubtitleParam = string.Empty;
  416. var copyTsParam = string.Empty;
  417. var yadifParam = state.DeInterlace ? "yadif=0:-1:0," : string.Empty;
  418. var request = state.VideoRequest;
  419. if (state.SubtitleStream != null)
  420. {
  421. if (state.SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 ||
  422. state.SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1 ||
  423. string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  424. string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase))
  425. {
  426. assSubtitleParam = GetTextSubtitleParam(state, performTextSubtitleConversion);
  427. copyTsParam = " -copyts";
  428. }
  429. }
  430. // If fixed dimensions were supplied
  431. if (request.Width.HasValue && request.Height.HasValue)
  432. {
  433. var widthParam = request.Width.Value.ToString(UsCulture);
  434. var heightParam = request.Height.Value.ToString(UsCulture);
  435. return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"", yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam);
  436. }
  437. // If Max dimensions were supplied, for width selects lowest even number between input width and width req size and selects lowest even number from in width*display aspect and requested size
  438. if (request.MaxWidth.HasValue && request.MaxHeight.HasValue)
  439. {
  440. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  441. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  442. return string.Format("{4} -vf \"{0}scale=trunc(min(iw\\,{1})/2)*2:trunc(min((iw/dar)\\,{2})/2)*2{3}\"", yadifParam, maxWidthParam, maxHeightParam, assSubtitleParam, copyTsParam);
  443. }
  444. var isH264Output = outputVideoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase);
  445. // If a fixed width was requested
  446. if (request.Width.HasValue)
  447. {
  448. var widthParam = request.Width.Value.ToString(UsCulture);
  449. return isH264Output ?
  450. string.Format("{3} -vf \"{0}scale={1}:trunc(ow/a/2)*2{2}\"", yadifParam, widthParam, assSubtitleParam, copyTsParam) :
  451. string.Format("{3} -vf \"{0}scale={1}:-1{2}\"", yadifParam, widthParam, assSubtitleParam, copyTsParam);
  452. }
  453. // If a fixed height was requested
  454. if (request.Height.HasValue)
  455. {
  456. var heightParam = request.Height.Value.ToString(UsCulture);
  457. return isH264Output ?
  458. string.Format("{3} -vf \"{0}scale=trunc(oh*a*2)/2:{1}{2}\"", yadifParam, heightParam, assSubtitleParam, copyTsParam) :
  459. string.Format("{3} -vf \"{0}scale=-1:{1}{2}\"", yadifParam, heightParam, assSubtitleParam, copyTsParam);
  460. }
  461. // If a max width was requested
  462. if (request.MaxWidth.HasValue && (!request.MaxHeight.HasValue || state.VideoStream == null))
  463. {
  464. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  465. return isH264Output ?
  466. string.Format("{3} -vf \"{0}scale=min(iw\\,{1}):trunc(ow/a/2)*2{2}\"", yadifParam, maxWidthParam, assSubtitleParam, copyTsParam) :
  467. string.Format("{3} -vf \"{0}scale=min(iw\\,{1}):-1{2}\"", yadifParam, maxWidthParam, assSubtitleParam, copyTsParam);
  468. }
  469. // If a max height was requested
  470. if (request.MaxHeight.HasValue && (!request.MaxWidth.HasValue || state.VideoStream == null))
  471. {
  472. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  473. return isH264Output ?
  474. string.Format("{3} -vf \"{0}scale=trunc(oh*a*2)/2:min(ih\\,{1}){2}\"", yadifParam, maxHeightParam, assSubtitleParam, copyTsParam) :
  475. string.Format("{3} -vf \"{0}scale=-1:min(ih\\,{1}){2}\"", yadifParam, maxHeightParam, assSubtitleParam, copyTsParam);
  476. }
  477. if (state.VideoStream == null)
  478. {
  479. // No way to figure this out
  480. return string.Empty;
  481. }
  482. // Need to perform calculations manually
  483. // Try to account for bad media info
  484. var currentHeight = state.VideoStream.Height ?? request.MaxHeight ?? request.Height ?? 0;
  485. var currentWidth = state.VideoStream.Width ?? request.MaxWidth ?? request.Width ?? 0;
  486. var outputSize = DrawingUtils.Resize(currentWidth, currentHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  487. // If we're encoding with libx264, it can't handle odd numbered widths or heights, so we'll have to fix that
  488. if (isH264Output)
  489. {
  490. var widthParam = outputSize.Width.ToString(UsCulture);
  491. var heightParam = outputSize.Height.ToString(UsCulture);
  492. return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"", yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam);
  493. }
  494. // Otherwise use -vf scale since ffmpeg will ensure internally that the aspect ratio is preserved
  495. return string.Format("{3} -vf \"{0}scale={1}:-1{2}\"", yadifParam, Convert.ToInt32(outputSize.Width), assSubtitleParam, copyTsParam);
  496. }
  497. /// <summary>
  498. /// Gets the text subtitle param.
  499. /// </summary>
  500. /// <param name="state">The state.</param>
  501. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  502. /// <returns>System.String.</returns>
  503. protected string GetTextSubtitleParam(StreamState state, bool performConversion)
  504. {
  505. var path = state.SubtitleStream.IsExternal ? GetConvertedAssPath(state.MediaPath, state.SubtitleStream, performConversion) :
  506. GetExtractedAssPath(state, performConversion);
  507. if (string.IsNullOrEmpty(path))
  508. {
  509. return string.Empty;
  510. }
  511. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  512. return string.Format(",ass='{0}',setpts=PTS -{1}/TB",
  513. path.Replace('\\', '/').Replace(":/", "\\:/"),
  514. Math.Round(seconds).ToString(UsCulture));
  515. }
  516. /// <summary>
  517. /// Gets the extracted ass path.
  518. /// </summary>
  519. /// <param name="state">The state.</param>
  520. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  521. /// <returns>System.String.</returns>
  522. private string GetExtractedAssPath(StreamState state, bool performConversion)
  523. {
  524. var path = EncodingManager.GetSubtitleCachePath(state.MediaPath, state.SubtitleStream.Index, ".ass");
  525. if (performConversion)
  526. {
  527. InputType type;
  528. var inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, null, state.PlayableStreamFileNames, out type);
  529. try
  530. {
  531. var parentPath = Path.GetDirectoryName(path);
  532. Directory.CreateDirectory(parentPath);
  533. // Don't re-encode ass/ssa to ass because ffmpeg ass encoder fails if there's more than one ass rectangle. Affect Anime mostly.
  534. // See https://lists.ffmpeg.org/pipermail/ffmpeg-cvslog/2013-April/063616.html
  535. var isAssSubtitle = string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) || string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase);
  536. var task = MediaEncoder.ExtractTextSubtitle(inputPath, type, state.SubtitleStream.Index, isAssSubtitle, path, CancellationToken.None);
  537. Task.WaitAll(task);
  538. }
  539. catch
  540. {
  541. return null;
  542. }
  543. }
  544. return path;
  545. }
  546. /// <summary>
  547. /// Gets the converted ass path.
  548. /// </summary>
  549. /// <param name="mediaPath">The media path.</param>
  550. /// <param name="subtitleStream">The subtitle stream.</param>
  551. /// <param name="performConversion">if set to <c>true</c> [perform conversion].</param>
  552. /// <returns>System.String.</returns>
  553. private string GetConvertedAssPath(string mediaPath, MediaStream subtitleStream, bool performConversion)
  554. {
  555. var path = EncodingManager.GetSubtitleCachePath(subtitleStream.Path, ".ass");
  556. if (performConversion)
  557. {
  558. try
  559. {
  560. var parentPath = Path.GetDirectoryName(path);
  561. Directory.CreateDirectory(parentPath);
  562. var task = MediaEncoder.ConvertTextSubtitleToAss(subtitleStream.Path, path, subtitleStream.Language, CancellationToken.None);
  563. Task.WaitAll(task);
  564. }
  565. catch
  566. {
  567. return null;
  568. }
  569. }
  570. return path;
  571. }
  572. /// <summary>
  573. /// Gets the internal graphical subtitle param.
  574. /// </summary>
  575. /// <param name="state">The state.</param>
  576. /// <param name="outputVideoCodec">The output video codec.</param>
  577. /// <returns>System.String.</returns>
  578. protected string GetInternalGraphicalSubtitleParam(StreamState state, string outputVideoCodec)
  579. {
  580. var outputSizeParam = string.Empty;
  581. var request = state.VideoRequest;
  582. // Add resolution params, if specified
  583. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  584. {
  585. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec, false).TrimEnd('"');
  586. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  587. }
  588. var videoSizeParam = string.Empty;
  589. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  590. {
  591. videoSizeParam = string.Format(",scale={0}:{1}", state.VideoStream.Width.Value.ToString(UsCulture), state.VideoStream.Height.Value.ToString(UsCulture));
  592. }
  593. return string.Format(" -filter_complex \"[0:{0}]format=yuva444p{3},lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:{1}] [sub] overlay{2}\"",
  594. state.SubtitleStream.Index,
  595. state.VideoStream.Index,
  596. outputSizeParam,
  597. videoSizeParam);
  598. }
  599. /// <summary>
  600. /// Gets the probe size argument.
  601. /// </summary>
  602. /// <param name="mediaPath">The media path.</param>
  603. /// <param name="isVideo">if set to <c>true</c> [is video].</param>
  604. /// <param name="videoType">Type of the video.</param>
  605. /// <param name="isoType">Type of the iso.</param>
  606. /// <returns>System.String.</returns>
  607. private string GetProbeSizeArgument(string mediaPath, bool isVideo, VideoType? videoType, IsoType? isoType)
  608. {
  609. var type = !isVideo ? MediaEncoderHelpers.GetInputType(null, null) :
  610. MediaEncoderHelpers.GetInputType(videoType, isoType);
  611. return MediaEncoder.GetProbeSizeArgument(type);
  612. }
  613. /// <summary>
  614. /// Gets the number of audio channels to specify on the command line
  615. /// </summary>
  616. /// <param name="request">The request.</param>
  617. /// <param name="audioStream">The audio stream.</param>
  618. /// <returns>System.Nullable{System.Int32}.</returns>
  619. protected int? GetNumAudioChannelsParam(StreamRequest request, MediaStream audioStream)
  620. {
  621. if (audioStream != null)
  622. {
  623. var codec = request.AudioCodec ?? string.Empty;
  624. if (audioStream.Channels > 2 && codec.IndexOf("wma", StringComparison.OrdinalIgnoreCase) != -1)
  625. {
  626. // wmav2 currently only supports two channel output
  627. return 2;
  628. }
  629. }
  630. if (request.MaxAudioChannels.HasValue)
  631. {
  632. if (audioStream != null && audioStream.Channels.HasValue)
  633. {
  634. return Math.Min(request.MaxAudioChannels.Value, audioStream.Channels.Value);
  635. }
  636. return request.MaxAudioChannels.Value;
  637. }
  638. return request.AudioChannels;
  639. }
  640. /// <summary>
  641. /// Determines whether the specified stream is H264.
  642. /// </summary>
  643. /// <param name="stream">The stream.</param>
  644. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  645. protected bool IsH264(MediaStream stream)
  646. {
  647. return stream.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  648. stream.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  649. }
  650. /// <summary>
  651. /// Gets the name of the output audio codec
  652. /// </summary>
  653. /// <param name="request">The request.</param>
  654. /// <returns>System.String.</returns>
  655. protected string GetAudioCodec(StreamRequest request)
  656. {
  657. var codec = request.AudioCodec;
  658. if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase))
  659. {
  660. return "aac -strict experimental";
  661. }
  662. if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
  663. {
  664. return "libmp3lame";
  665. }
  666. if (string.Equals(codec, "vorbis", StringComparison.OrdinalIgnoreCase))
  667. {
  668. return "libvorbis";
  669. }
  670. if (string.Equals(codec, "wma", StringComparison.OrdinalIgnoreCase))
  671. {
  672. return "wmav2";
  673. }
  674. return codec.ToLower();
  675. }
  676. /// <summary>
  677. /// Gets the name of the output video codec
  678. /// </summary>
  679. /// <param name="request">The request.</param>
  680. /// <returns>System.String.</returns>
  681. protected string GetVideoCodec(VideoStreamRequest request)
  682. {
  683. var codec = request.VideoCodec;
  684. if (!string.IsNullOrEmpty(codec))
  685. {
  686. if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
  687. {
  688. return "libx264";
  689. }
  690. if (string.Equals(codec, "vpx", StringComparison.OrdinalIgnoreCase))
  691. {
  692. return "libvpx";
  693. }
  694. if (string.Equals(codec, "wmv", StringComparison.OrdinalIgnoreCase))
  695. {
  696. return "wmv2";
  697. }
  698. if (string.Equals(codec, "theora", StringComparison.OrdinalIgnoreCase))
  699. {
  700. return "libtheora";
  701. }
  702. return codec.ToLower();
  703. }
  704. return "copy";
  705. }
  706. /// <summary>
  707. /// Gets the input argument.
  708. /// </summary>
  709. /// <param name="state">The state.</param>
  710. /// <returns>System.String.</returns>
  711. protected string GetInputArgument(StreamState state)
  712. {
  713. var type = InputType.File;
  714. var inputPath = new[] { state.MediaPath };
  715. if (state.IsInputVideo)
  716. {
  717. if (!(state.VideoType == VideoType.Iso && state.IsoMount == null))
  718. {
  719. inputPath = MediaEncoderHelpers.GetInputArgument(state.MediaPath, state.IsRemote, state.VideoType, state.IsoType, state.IsoMount, state.PlayableStreamFileNames, out type);
  720. }
  721. }
  722. return MediaEncoder.GetInputArgument(inputPath, type);
  723. }
  724. /// <summary>
  725. /// Starts the FFMPEG.
  726. /// </summary>
  727. /// <param name="state">The state.</param>
  728. /// <param name="outputPath">The output path.</param>
  729. /// <returns>Task.</returns>
  730. protected async Task StartFfMpeg(StreamState state, string outputPath)
  731. {
  732. if (!File.Exists(MediaEncoder.EncoderPath))
  733. {
  734. throw new InvalidOperationException("ffmpeg was not found at " + MediaEncoder.EncoderPath);
  735. }
  736. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  737. if (state.IsInputVideo && state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  738. {
  739. state.IsoMount = await IsoManager.Mount(state.MediaPath, CancellationToken.None).ConfigureAwait(false);
  740. }
  741. var commandLineArgs = GetCommandLineArguments(outputPath, state, true);
  742. if (ServerConfigurationManager.Configuration.EnableDebugEncodingLogging)
  743. {
  744. commandLineArgs = "-loglevel debug " + commandLineArgs;
  745. }
  746. var process = new Process
  747. {
  748. StartInfo = new ProcessStartInfo
  749. {
  750. CreateNoWindow = true,
  751. UseShellExecute = false,
  752. // Must consume both stdout and stderr or deadlocks may occur
  753. RedirectStandardOutput = true,
  754. RedirectStandardError = true,
  755. FileName = MediaEncoder.EncoderPath,
  756. WorkingDirectory = Path.GetDirectoryName(MediaEncoder.EncoderPath),
  757. Arguments = commandLineArgs,
  758. WindowStyle = ProcessWindowStyle.Hidden,
  759. ErrorDialog = false
  760. },
  761. EnableRaisingEvents = true
  762. };
  763. ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath, TranscodingJobType, process, state.IsInputVideo, state.Request.StartTimeTicks, state.MediaPath, state.Request.DeviceId);
  764. var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  765. Logger.Info(commandLineLogMessage);
  766. var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid() + ".txt");
  767. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  768. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  769. state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  770. var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(commandLineLogMessage + Environment.NewLine + Environment.NewLine);
  771. await state.LogFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length).ConfigureAwait(false);
  772. process.Exited += (sender, args) => OnFfMpegProcessExited(process, state);
  773. try
  774. {
  775. process.Start();
  776. }
  777. catch (Exception ex)
  778. {
  779. Logger.ErrorException("Error starting ffmpeg", ex);
  780. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType);
  781. throw;
  782. }
  783. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  784. process.BeginOutputReadLine();
  785. #pragma warning disable 4014
  786. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  787. process.StandardError.BaseStream.CopyToAsync(state.LogFileStream);
  788. #pragma warning restore 4014
  789. // Wait for the file to exist before proceeeding
  790. while (!File.Exists(outputPath))
  791. {
  792. await Task.Delay(100).ConfigureAwait(false);
  793. }
  794. // Allow a small amount of time to buffer a little
  795. if (state.IsInputVideo)
  796. {
  797. await Task.Delay(500).ConfigureAwait(false);
  798. }
  799. // This is arbitrary, but add a little buffer time when internet streaming
  800. if (state.IsRemote)
  801. {
  802. await Task.Delay(3000).ConfigureAwait(false);
  803. }
  804. }
  805. protected int? GetVideoBitrateParamValue(StreamState state)
  806. {
  807. var bitrate = state.VideoRequest.VideoBitRate;
  808. if (state.VideoStream != null)
  809. {
  810. var isUpscaling = state.VideoRequest.Height.HasValue && state.VideoStream.Height.HasValue &&
  811. state.VideoRequest.Height.Value > state.VideoStream.Height.Value;
  812. if (state.VideoRequest.Width.HasValue && state.VideoStream.Width.HasValue &&
  813. state.VideoRequest.Width.Value > state.VideoStream.Width.Value)
  814. {
  815. isUpscaling = true;
  816. }
  817. // Don't allow bitrate increases unless upscaling
  818. if (!isUpscaling)
  819. {
  820. if (bitrate.HasValue && state.VideoStream.BitRate.HasValue)
  821. {
  822. bitrate = Math.Min(bitrate.Value, state.VideoStream.BitRate.Value);
  823. }
  824. }
  825. }
  826. return bitrate;
  827. }
  828. protected string GetVideoBitrateParam(StreamState state, string videoCodec, bool isHls)
  829. {
  830. var bitrate = GetVideoBitrateParamValue(state);
  831. if (bitrate.HasValue)
  832. {
  833. var hasFixedResolution = state.VideoRequest.HasFixedResolution;
  834. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  835. {
  836. if (hasFixedResolution)
  837. {
  838. return string.Format(" -minrate:v ({0}*.90) -maxrate:v ({0}*1.10) -bufsize:v {0} -b:v {0}", bitrate.Value.ToString(UsCulture));
  839. }
  840. // With vpx when crf is used, b:v becomes a max rate
  841. // https://trac.ffmpeg.org/wiki/vpxEncodingGuide. But higher bitrate source files -b:v causes judder so limite the bitrate but dont allow it to "saturate" the bitrate. So dont contrain it down just up.
  842. return string.Format(" -maxrate:v {0} -bufsize:v ({0}*2) -b:v {0}", bitrate.Value.ToString(UsCulture));
  843. }
  844. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  845. {
  846. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  847. }
  848. // H264
  849. if (hasFixedResolution)
  850. {
  851. if (isHls)
  852. {
  853. return string.Format(" -b:v {0} -maxrate ({0}*.80) -bufsize {0}", bitrate.Value.ToString(UsCulture));
  854. }
  855. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  856. }
  857. return string.Format(" -maxrate {0} -bufsize {1}",
  858. bitrate.Value.ToString(UsCulture),
  859. (bitrate.Value * 2).ToString(UsCulture));
  860. }
  861. return string.Empty;
  862. }
  863. protected int? GetAudioBitrateParam(StreamState state)
  864. {
  865. if (state.Request.AudioBitRate.HasValue)
  866. {
  867. // Make sure we don't request a bitrate higher than the source
  868. var currentBitrate = state.AudioStream == null ? state.Request.AudioBitRate.Value : state.AudioStream.BitRate ?? state.Request.AudioBitRate.Value;
  869. return Math.Min(currentBitrate, state.Request.AudioBitRate.Value);
  870. }
  871. return null;
  872. }
  873. /// <summary>
  874. /// Gets the user agent param.
  875. /// </summary>
  876. /// <param name="path">The path.</param>
  877. /// <returns>System.String.</returns>
  878. private string GetUserAgentParam(string path)
  879. {
  880. var useragent = GetUserAgent(path);
  881. if (!string.IsNullOrEmpty(useragent))
  882. {
  883. return "-user-agent \"" + useragent + "\"";
  884. }
  885. return string.Empty;
  886. }
  887. /// <summary>
  888. /// Gets the user agent.
  889. /// </summary>
  890. /// <param name="path">The path.</param>
  891. /// <returns>System.String.</returns>
  892. protected string GetUserAgent(string path)
  893. {
  894. if (string.IsNullOrEmpty(path))
  895. {
  896. throw new ArgumentNullException("path");
  897. }
  898. if (path.IndexOf("apple.com", StringComparison.OrdinalIgnoreCase) != -1)
  899. {
  900. return "QuickTime/7.7.4";
  901. }
  902. return string.Empty;
  903. }
  904. /// <summary>
  905. /// Processes the exited.
  906. /// </summary>
  907. /// <param name="process">The process.</param>
  908. /// <param name="state">The state.</param>
  909. protected void OnFfMpegProcessExited(Process process, StreamState state)
  910. {
  911. state.Dispose();
  912. var outputFilePath = GetOutputFilePath(state);
  913. try
  914. {
  915. Logger.Info("FFMpeg exited with code {0} for {1}", process.ExitCode, outputFilePath);
  916. }
  917. catch
  918. {
  919. Logger.Info("FFMpeg exited with an error for {0}", outputFilePath);
  920. }
  921. }
  922. protected double? GetFramerateParam(StreamState state)
  923. {
  924. if (state.VideoRequest != null)
  925. {
  926. if (state.VideoRequest.Framerate.HasValue)
  927. {
  928. return state.VideoRequest.Framerate.Value;
  929. }
  930. var maxrate = state.VideoRequest.MaxFramerate ?? 23.97602;
  931. if (state.VideoStream != null)
  932. {
  933. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  934. if (contentRate.HasValue && contentRate.Value > maxrate)
  935. {
  936. return maxrate;
  937. }
  938. }
  939. }
  940. return null;
  941. }
  942. /// <summary>
  943. /// Parses the parameters.
  944. /// </summary>
  945. /// <param name="request">The request.</param>
  946. private void ParseParams(StreamRequest request)
  947. {
  948. var vals = request.Params.Split(';');
  949. var videoRequest = request as VideoStreamRequest;
  950. for (var i = 0; i < vals.Length; i++)
  951. {
  952. var val = vals[i];
  953. if (string.IsNullOrWhiteSpace(val))
  954. {
  955. continue;
  956. }
  957. if (i == 0)
  958. {
  959. request.DeviceProfileId = val;
  960. }
  961. else if (i == 1)
  962. {
  963. request.DeviceId = val;
  964. }
  965. else if (i == 2)
  966. {
  967. request.MediaSourceId = val;
  968. }
  969. else if (i == 3)
  970. {
  971. request.Static = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  972. }
  973. else if (i == 4)
  974. {
  975. if (videoRequest != null)
  976. {
  977. videoRequest.VideoCodec = val;
  978. }
  979. }
  980. else if (i == 5)
  981. {
  982. request.AudioCodec = val;
  983. }
  984. else if (i == 6)
  985. {
  986. if (videoRequest != null)
  987. {
  988. videoRequest.AudioStreamIndex = int.Parse(val, UsCulture);
  989. }
  990. }
  991. else if (i == 7)
  992. {
  993. if (videoRequest != null)
  994. {
  995. videoRequest.SubtitleStreamIndex = int.Parse(val, UsCulture);
  996. }
  997. }
  998. else if (i == 8)
  999. {
  1000. if (videoRequest != null)
  1001. {
  1002. videoRequest.VideoBitRate = int.Parse(val, UsCulture);
  1003. }
  1004. }
  1005. else if (i == 9)
  1006. {
  1007. request.AudioBitRate = int.Parse(val, UsCulture);
  1008. }
  1009. else if (i == 10)
  1010. {
  1011. request.MaxAudioChannels = int.Parse(val, UsCulture);
  1012. }
  1013. else if (i == 11)
  1014. {
  1015. if (videoRequest != null)
  1016. {
  1017. videoRequest.MaxFramerate = double.Parse(val, UsCulture);
  1018. }
  1019. }
  1020. else if (i == 12)
  1021. {
  1022. if (videoRequest != null)
  1023. {
  1024. videoRequest.MaxWidth = int.Parse(val, UsCulture);
  1025. }
  1026. }
  1027. else if (i == 13)
  1028. {
  1029. if (videoRequest != null)
  1030. {
  1031. videoRequest.MaxHeight = int.Parse(val, UsCulture);
  1032. }
  1033. }
  1034. else if (i == 14)
  1035. {
  1036. request.StartTimeTicks = long.Parse(val, UsCulture);
  1037. }
  1038. else if (i == 15)
  1039. {
  1040. if (videoRequest != null)
  1041. {
  1042. videoRequest.Level = val;
  1043. }
  1044. }
  1045. }
  1046. }
  1047. /// <summary>
  1048. /// Parses the dlna headers.
  1049. /// </summary>
  1050. /// <param name="request">The request.</param>
  1051. private void ParseDlnaHeaders(StreamRequest request)
  1052. {
  1053. if (!request.StartTimeTicks.HasValue)
  1054. {
  1055. var timeSeek = GetHeader("TimeSeekRange.dlna.org");
  1056. request.StartTimeTicks = ParseTimeSeekHeader(timeSeek);
  1057. }
  1058. }
  1059. /// <summary>
  1060. /// Parses the time seek header.
  1061. /// </summary>
  1062. private long? ParseTimeSeekHeader(string value)
  1063. {
  1064. if (string.IsNullOrWhiteSpace(value))
  1065. {
  1066. return null;
  1067. }
  1068. if (value.IndexOf("npt=", StringComparison.OrdinalIgnoreCase) != 0)
  1069. {
  1070. throw new ArgumentException("Invalid timeseek header");
  1071. }
  1072. value = value.Substring(4).Split(new[] { '-' }, 2)[0];
  1073. if (value.IndexOf(':') == -1)
  1074. {
  1075. // Parses npt times in the format of '417.33'
  1076. double seconds;
  1077. if (double.TryParse(value, NumberStyles.Any, UsCulture, out seconds))
  1078. {
  1079. return TimeSpan.FromSeconds(seconds).Ticks;
  1080. }
  1081. throw new ArgumentException("Invalid timeseek header");
  1082. }
  1083. // Parses npt times in the format of '10:19:25.7'
  1084. var tokens = value.Split(new[] { ':' }, 3);
  1085. double secondsSum = 0;
  1086. var timeFactor = 3600;
  1087. foreach (var time in tokens)
  1088. {
  1089. double digit;
  1090. if (double.TryParse(time, NumberStyles.Any, UsCulture, out digit))
  1091. {
  1092. secondsSum += (digit * timeFactor);
  1093. }
  1094. else
  1095. {
  1096. throw new ArgumentException("Invalid timeseek header");
  1097. }
  1098. timeFactor /= 60;
  1099. }
  1100. return TimeSpan.FromSeconds(secondsSum).Ticks;
  1101. }
  1102. /// <summary>
  1103. /// Gets the state.
  1104. /// </summary>
  1105. /// <param name="request">The request.</param>
  1106. /// <param name="cancellationToken">The cancellation token.</param>
  1107. /// <returns>StreamState.</returns>
  1108. protected async Task<StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
  1109. {
  1110. ParseDlnaHeaders(request);
  1111. if (!string.IsNullOrWhiteSpace(request.Params))
  1112. {
  1113. ParseParams(request);
  1114. }
  1115. var user = AuthorizationRequestFilterAttribute.GetCurrentUser(Request, UserManager);
  1116. var url = Request.PathInfo;
  1117. if (string.IsNullOrEmpty(request.AudioCodec))
  1118. {
  1119. request.AudioCodec = InferAudioCodec(url);
  1120. }
  1121. var state = new StreamState(LiveTvManager, Logger)
  1122. {
  1123. Request = request,
  1124. RequestedUrl = url
  1125. };
  1126. var item = string.IsNullOrEmpty(request.MediaSourceId) ?
  1127. DtoService.GetItemByDtoId(request.Id) :
  1128. DtoService.GetItemByDtoId(request.MediaSourceId);
  1129. if (user != null && item.GetPlayAccess(user) != PlayAccess.Full)
  1130. {
  1131. throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
  1132. }
  1133. if (item is ILiveTvRecording)
  1134. {
  1135. var recording = await LiveTvManager.GetInternalRecording(request.Id, cancellationToken).ConfigureAwait(false);
  1136. state.VideoType = VideoType.VideoFile;
  1137. state.IsInputVideo = string.Equals(recording.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  1138. state.PlayableStreamFileNames = new List<string>();
  1139. var path = recording.RecordingInfo.Path;
  1140. var mediaUrl = recording.RecordingInfo.Url;
  1141. if (string.IsNullOrWhiteSpace(path) && string.IsNullOrWhiteSpace(mediaUrl))
  1142. {
  1143. var streamInfo = await LiveTvManager.GetRecordingStream(request.Id, cancellationToken).ConfigureAwait(false);
  1144. state.LiveTvStreamId = streamInfo.Id;
  1145. path = streamInfo.Path;
  1146. mediaUrl = streamInfo.Url;
  1147. }
  1148. if (!string.IsNullOrEmpty(path) && File.Exists(path))
  1149. {
  1150. state.MediaPath = path;
  1151. state.IsRemote = false;
  1152. }
  1153. else if (!string.IsNullOrEmpty(mediaUrl))
  1154. {
  1155. state.MediaPath = mediaUrl;
  1156. state.IsRemote = true;
  1157. }
  1158. state.RunTimeTicks = recording.RunTimeTicks;
  1159. if (recording.RecordingInfo.Status == RecordingStatus.InProgress && !state.IsRemote)
  1160. {
  1161. await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
  1162. }
  1163. state.ReadInputAtNativeFramerate = recording.RecordingInfo.Status == RecordingStatus.InProgress;
  1164. state.AudioSync = "1000";
  1165. state.DeInterlace = true;
  1166. state.InputVideoSync = "-1";
  1167. state.InputAudioSync = "1";
  1168. }
  1169. else if (item is LiveTvChannel)
  1170. {
  1171. var channel = LiveTvManager.GetInternalChannel(request.Id);
  1172. state.VideoType = VideoType.VideoFile;
  1173. state.IsInputVideo = string.Equals(channel.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  1174. state.PlayableStreamFileNames = new List<string>();
  1175. var streamInfo = await LiveTvManager.GetChannelStream(request.Id, cancellationToken).ConfigureAwait(false);
  1176. state.LiveTvStreamId = streamInfo.Id;
  1177. if (!string.IsNullOrEmpty(streamInfo.Path) && File.Exists(streamInfo.Path))
  1178. {
  1179. state.MediaPath = streamInfo.Path;
  1180. state.IsRemote = false;
  1181. await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
  1182. }
  1183. else if (!string.IsNullOrEmpty(streamInfo.Url))
  1184. {
  1185. state.MediaPath = streamInfo.Url;
  1186. state.IsRemote = true;
  1187. }
  1188. state.ReadInputAtNativeFramerate = true;
  1189. state.AudioSync = "1000";
  1190. state.DeInterlace = true;
  1191. state.InputVideoSync = "-1";
  1192. state.InputAudioSync = "1";
  1193. }
  1194. else
  1195. {
  1196. state.MediaPath = item.Path;
  1197. state.IsRemote = item.LocationType == LocationType.Remote;
  1198. var video = item as Video;
  1199. if (video != null)
  1200. {
  1201. state.IsInputVideo = true;
  1202. state.VideoType = video.VideoType;
  1203. state.IsoType = video.IsoType;
  1204. state.PlayableStreamFileNames = video.PlayableStreamFileNames == null
  1205. ? new List<string>()
  1206. : video.PlayableStreamFileNames.ToList();
  1207. }
  1208. state.RunTimeTicks = item.RunTimeTicks;
  1209. }
  1210. var videoRequest = request as VideoStreamRequest;
  1211. var mediaStreams = ItemRepository.GetMediaStreams(new MediaStreamQuery
  1212. {
  1213. ItemId = item.Id
  1214. }).ToList();
  1215. if (videoRequest != null)
  1216. {
  1217. if (string.IsNullOrEmpty(videoRequest.VideoCodec))
  1218. {
  1219. videoRequest.VideoCodec = InferVideoCodec(url);
  1220. }
  1221. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  1222. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  1223. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  1224. if (state.VideoStream != null && state.VideoStream.IsInterlaced)
  1225. {
  1226. state.DeInterlace = true;
  1227. }
  1228. EnforceResolutionLimit(state, videoRequest);
  1229. }
  1230. else
  1231. {
  1232. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  1233. }
  1234. state.HasMediaStreams = mediaStreams.Count > 0;
  1235. state.SegmentLength = state.ReadInputAtNativeFramerate ? 5 : 10;
  1236. state.HlsListSize = state.ReadInputAtNativeFramerate ? 100 : 1440;
  1237. ApplyDeviceProfileSettings(state);
  1238. if (videoRequest != null && state.VideoStream != null)
  1239. {
  1240. if (CanStreamCopyVideo(videoRequest, state.VideoStream, state.VideoType))
  1241. {
  1242. videoRequest.VideoCodec = "copy";
  1243. }
  1244. }
  1245. return state;
  1246. }
  1247. private bool CanStreamCopyVideo(VideoStreamRequest request, MediaStream videoStream, VideoType videoType)
  1248. {
  1249. if (videoStream.IsInterlaced)
  1250. {
  1251. return false;
  1252. }
  1253. // Not going to attempt this with folder rips
  1254. if (videoType != VideoType.VideoFile)
  1255. {
  1256. return false;
  1257. }
  1258. // Source and target codecs must match
  1259. if (!string.Equals(request.VideoCodec, videoStream.Codec, StringComparison.OrdinalIgnoreCase))
  1260. {
  1261. return false;
  1262. }
  1263. // If client is requesting a specific video profile, it must match the source
  1264. if (!string.IsNullOrEmpty(request.Profile) && !string.Equals(request.Profile, videoStream.Profile))
  1265. {
  1266. return false;
  1267. }
  1268. // Video width must fall within requested value
  1269. if (request.MaxWidth.HasValue)
  1270. {
  1271. if (!videoStream.Width.HasValue || videoStream.Width.Value > request.MaxWidth.Value)
  1272. {
  1273. return false;
  1274. }
  1275. }
  1276. // Video height must fall within requested value
  1277. if (request.MaxHeight.HasValue)
  1278. {
  1279. if (!videoStream.Height.HasValue || videoStream.Height.Value > request.MaxHeight.Value)
  1280. {
  1281. return false;
  1282. }
  1283. }
  1284. // Video framerate must fall within requested value
  1285. var requestedFramerate = request.MaxFramerate ?? request.Framerate;
  1286. if (requestedFramerate.HasValue)
  1287. {
  1288. var videoFrameRate = videoStream.AverageFrameRate ?? videoStream.RealFrameRate;
  1289. if (!videoFrameRate.HasValue || videoFrameRate.Value > requestedFramerate.Value)
  1290. {
  1291. return false;
  1292. }
  1293. }
  1294. // Video bitrate must fall within requested value
  1295. if (request.VideoBitRate.HasValue)
  1296. {
  1297. if (!videoStream.BitRate.HasValue || videoStream.BitRate.Value > request.VideoBitRate.Value)
  1298. {
  1299. return false;
  1300. }
  1301. }
  1302. // If a specific level was requested, the source must match or be less than
  1303. if (!string.IsNullOrEmpty(request.Level))
  1304. {
  1305. double requestLevel;
  1306. if (double.TryParse(request.Level, NumberStyles.Any, UsCulture, out requestLevel))
  1307. {
  1308. if (!videoStream.Level.HasValue)
  1309. {
  1310. return false;
  1311. }
  1312. if (videoStream.Level.Value > requestLevel)
  1313. {
  1314. return false;
  1315. }
  1316. }
  1317. return false;
  1318. }
  1319. return SupportsAutomaticVideoStreamCopy;
  1320. }
  1321. protected virtual bool SupportsAutomaticVideoStreamCopy
  1322. {
  1323. get
  1324. {
  1325. return false;
  1326. }
  1327. }
  1328. private void ApplyDeviceProfileSettings(StreamState state)
  1329. {
  1330. var headers = new Dictionary<string, string>();
  1331. foreach (var key in Request.Headers.AllKeys)
  1332. {
  1333. headers[key] = Request.Headers[key];
  1334. }
  1335. var profile = string.IsNullOrWhiteSpace(state.Request.DeviceProfileId) ?
  1336. DlnaManager.GetProfile(headers) :
  1337. DlnaManager.GetProfile(state.Request.DeviceProfileId);
  1338. if (profile == null)
  1339. {
  1340. // Don't use settings from the default profile.
  1341. // Only use a specific profile if it was requested.
  1342. return;
  1343. }
  1344. var container = Path.GetExtension(state.RequestedUrl);
  1345. if (string.IsNullOrEmpty(container))
  1346. {
  1347. container = Path.GetExtension(GetOutputFilePath(state));
  1348. }
  1349. var audioCodec = state.Request.AudioCodec;
  1350. if (string.Equals(audioCodec, "copy", StringComparison.OrdinalIgnoreCase) && state.AudioStream != null)
  1351. {
  1352. audioCodec = state.AudioStream.Codec;
  1353. }
  1354. var videoCodec = state.VideoRequest == null ? null : state.VideoRequest.VideoCodec;
  1355. if (string.Equals(videoCodec, "copy", StringComparison.OrdinalIgnoreCase) && state.VideoStream != null)
  1356. {
  1357. videoCodec = state.VideoStream.Codec;
  1358. }
  1359. var mediaProfile = state.VideoRequest == null ?
  1360. profile.GetAudioMediaProfile(container, audioCodec, state.AudioStream) :
  1361. profile.GetVideoMediaProfile(container, audioCodec, videoCodec, state.AudioStream, state.VideoStream);
  1362. if (mediaProfile != null)
  1363. {
  1364. state.MimeType = mediaProfile.MimeType;
  1365. state.OrgPn = mediaProfile.OrgPn;
  1366. }
  1367. var transcodingProfile = state.VideoRequest == null ?
  1368. profile.GetAudioTranscodingProfile(container, audioCodec) :
  1369. profile.GetVideoTranscodingProfile(container, audioCodec, videoCodec);
  1370. if (transcodingProfile != null)
  1371. {
  1372. state.EstimateContentLength = transcodingProfile.EstimateContentLength;
  1373. state.EnableMpegtsM2TsMode = transcodingProfile.EnableMpegtsM2TsMode;
  1374. state.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
  1375. if (state.VideoRequest != null && string.IsNullOrWhiteSpace(state.VideoRequest.Profile))
  1376. {
  1377. state.VideoRequest.Profile = transcodingProfile.VideoProfile;
  1378. }
  1379. }
  1380. }
  1381. /// <summary>
  1382. /// Adds the dlna headers.
  1383. /// </summary>
  1384. /// <param name="state">The state.</param>
  1385. /// <param name="responseHeaders">The response headers.</param>
  1386. /// <param name="isStaticallyStreamed">if set to <c>true</c> [is statically streamed].</param>
  1387. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1388. protected void AddDlnaHeaders(StreamState state, IDictionary<string, string> responseHeaders, bool isStaticallyStreamed)
  1389. {
  1390. var transferMode = GetHeader("transferMode.dlna.org");
  1391. responseHeaders["transferMode.dlna.org"] = string.IsNullOrEmpty(transferMode) ? "Streaming" : transferMode;
  1392. responseHeaders["realTimeInfo.dlna.org"] = "DLNA.ORG_TLAG=*";
  1393. var contentFeatures = string.Empty;
  1394. var extension = GetOutputFileExtension(state);
  1395. // first bit means Time based seek supported, second byte range seek supported (not sure about the order now), so 01 = only byte seek, 10 = time based, 11 = both, 00 = none
  1396. var orgOp = ";DLNA.ORG_OP=";
  1397. if (state.RunTimeTicks.HasValue)
  1398. {
  1399. // Time-based seeking currently only possible when transcoding
  1400. orgOp += isStaticallyStreamed ? "0" : "1";
  1401. // Byte-based seeking only possible when not transcoding
  1402. orgOp += isStaticallyStreamed || state.TranscodeSeekInfo == TranscodeSeekInfo.Bytes ? "1" : "0";
  1403. if (!isStaticallyStreamed)
  1404. {
  1405. AddTimeSeekResponseHeaders(state, responseHeaders);
  1406. }
  1407. }
  1408. else
  1409. {
  1410. // No seeking is available if we don't know the content runtime
  1411. orgOp += "00";
  1412. }
  1413. // 0 = native, 1 = transcoded
  1414. var orgCi = isStaticallyStreamed ? ";DLNA.ORG_CI=0" : ";DLNA.ORG_CI=1";
  1415. const string dlnaflags = ";DLNA.ORG_FLAGS=01500000000000000000000000000000";
  1416. if (!string.IsNullOrWhiteSpace(state.OrgPn))
  1417. {
  1418. contentFeatures = "DLNA.ORG_PN=" + state.OrgPn;
  1419. }
  1420. else if (string.Equals(extension, ".mp3", StringComparison.OrdinalIgnoreCase))
  1421. {
  1422. contentFeatures = "DLNA.ORG_PN=MP3";
  1423. }
  1424. else if (string.Equals(extension, ".aac", StringComparison.OrdinalIgnoreCase))
  1425. {
  1426. contentFeatures = "DLNA.ORG_PN=AAC_ISO";
  1427. }
  1428. else if (string.Equals(extension, ".wma", StringComparison.OrdinalIgnoreCase))
  1429. {
  1430. contentFeatures = "DLNA.ORG_PN=WMABASE";
  1431. }
  1432. else if (string.Equals(extension, ".avi", StringComparison.OrdinalIgnoreCase))
  1433. {
  1434. contentFeatures = "DLNA.ORG_PN=AVI";
  1435. }
  1436. else if (string.Equals(extension, ".mkv", StringComparison.OrdinalIgnoreCase))
  1437. {
  1438. contentFeatures = "DLNA.ORG_PN=MATROSKA";
  1439. }
  1440. else if (string.Equals(extension, ".mp4", StringComparison.OrdinalIgnoreCase))
  1441. {
  1442. contentFeatures = "DLNA.ORG_PN=AVC_MP4_MP_HD_720p_AAC";
  1443. }
  1444. else if (string.Equals(extension, ".mpeg", StringComparison.OrdinalIgnoreCase))
  1445. {
  1446. contentFeatures = "DLNA.ORG_PN=MPEG_PS_PAL";
  1447. }
  1448. else if (string.Equals(extension, ".ts", StringComparison.OrdinalIgnoreCase))
  1449. {
  1450. contentFeatures = "DLNA.ORG_PN=MPEG_PS_PAL";
  1451. }
  1452. if (!string.IsNullOrEmpty(contentFeatures))
  1453. {
  1454. responseHeaders["contentFeatures.dlna.org"] = (contentFeatures + orgOp + orgCi + dlnaflags).Trim(';');
  1455. }
  1456. foreach (var item in responseHeaders)
  1457. {
  1458. Request.Response.AddHeader(item.Key, item.Value);
  1459. }
  1460. }
  1461. private void AddTimeSeekResponseHeaders(StreamState state, IDictionary<string, string> responseHeaders)
  1462. {
  1463. var runtimeSeconds = TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds.ToString(UsCulture);
  1464. var startSeconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds.ToString(UsCulture);
  1465. responseHeaders["TimeSeekRange.dlna.org"] = string.Format("npt={0}-{1}/{1}", startSeconds, runtimeSeconds);
  1466. responseHeaders["X-AvailableSeekRange"] = string.Format("1 npt={0}-{1}", startSeconds, runtimeSeconds);
  1467. }
  1468. /// <summary>
  1469. /// Enforces the resolution limit.
  1470. /// </summary>
  1471. /// <param name="state">The state.</param>
  1472. /// <param name="videoRequest">The video request.</param>
  1473. private void EnforceResolutionLimit(StreamState state, VideoStreamRequest videoRequest)
  1474. {
  1475. // If enabled, allow whatever the client asks for
  1476. if (ServerConfigurationManager.Configuration.AllowVideoUpscaling)
  1477. {
  1478. return;
  1479. }
  1480. // Switch the incoming params to be ceilings rather than fixed values
  1481. videoRequest.MaxWidth = videoRequest.MaxWidth ?? videoRequest.Width;
  1482. videoRequest.MaxHeight = videoRequest.MaxHeight ?? videoRequest.Height;
  1483. videoRequest.Width = null;
  1484. videoRequest.Height = null;
  1485. }
  1486. protected string GetInputModifier(StreamState state)
  1487. {
  1488. var inputModifier = string.Empty;
  1489. var probeSize = GetProbeSizeArgument(state.MediaPath, state.IsInputVideo, state.VideoType, state.IsoType);
  1490. inputModifier += " " + probeSize;
  1491. inputModifier = inputModifier.Trim();
  1492. inputModifier += " " + GetUserAgentParam(state.MediaPath);
  1493. inputModifier = inputModifier.Trim();
  1494. inputModifier += " " + GetFastSeekCommandLineParameter(state.Request);
  1495. inputModifier = inputModifier.Trim();
  1496. if (state.VideoRequest != null)
  1497. {
  1498. inputModifier += " -fflags genpts";
  1499. }
  1500. if (!string.IsNullOrEmpty(state.InputFormat))
  1501. {
  1502. inputModifier += " -f " + state.InputFormat;
  1503. }
  1504. if (!string.IsNullOrEmpty(state.InputVideoCodec))
  1505. {
  1506. inputModifier += " -vcodec " + state.InputVideoCodec;
  1507. }
  1508. if (!string.IsNullOrEmpty(state.InputAudioCodec))
  1509. {
  1510. inputModifier += " -acodec " + state.InputAudioCodec;
  1511. }
  1512. if (!string.IsNullOrEmpty(state.InputAudioSync))
  1513. {
  1514. inputModifier += " -async " + state.InputAudioSync;
  1515. }
  1516. if (!string.IsNullOrEmpty(state.InputVideoSync))
  1517. {
  1518. inputModifier += " -vsync " + state.InputVideoSync;
  1519. }
  1520. if (state.ReadInputAtNativeFramerate)
  1521. {
  1522. inputModifier += " -re";
  1523. }
  1524. return inputModifier;
  1525. }
  1526. /// <summary>
  1527. /// Infers the audio codec based on the url
  1528. /// </summary>
  1529. /// <param name="url">The URL.</param>
  1530. /// <returns>System.Nullable{AudioCodecs}.</returns>
  1531. private string InferAudioCodec(string url)
  1532. {
  1533. var ext = Path.GetExtension(url);
  1534. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  1535. {
  1536. return "mp3";
  1537. }
  1538. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  1539. {
  1540. return "aac";
  1541. }
  1542. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  1543. {
  1544. return "wma";
  1545. }
  1546. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  1547. {
  1548. return "vorbis";
  1549. }
  1550. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  1551. {
  1552. return "vorbis";
  1553. }
  1554. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1555. {
  1556. return "vorbis";
  1557. }
  1558. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1559. {
  1560. return "vorbis";
  1561. }
  1562. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  1563. {
  1564. return "vorbis";
  1565. }
  1566. return "copy";
  1567. }
  1568. /// <summary>
  1569. /// Infers the video codec.
  1570. /// </summary>
  1571. /// <param name="url">The URL.</param>
  1572. /// <returns>System.Nullable{VideoCodecs}.</returns>
  1573. private string InferVideoCodec(string url)
  1574. {
  1575. var ext = Path.GetExtension(url);
  1576. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  1577. {
  1578. return "wmv";
  1579. }
  1580. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1581. {
  1582. return "vpx";
  1583. }
  1584. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1585. {
  1586. return "theora";
  1587. }
  1588. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  1589. {
  1590. return "h264";
  1591. }
  1592. return "copy";
  1593. }
  1594. }
  1595. }