BaseStreamingService.cs 60 KB

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