BaseStreamingService.cs 72 KB

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