2
0

BaseStreamingService.cs 68 KB

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