BaseStreamingService.cs 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Devices;
  4. using MediaBrowser.Controller.Dlna;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.MediaEncoding;
  8. using MediaBrowser.Model.Dlna;
  9. using MediaBrowser.Model.Dto;
  10. using MediaBrowser.Model.Entities;
  11. using MediaBrowser.Model.Extensions;
  12. using MediaBrowser.Model.IO;
  13. using MediaBrowser.Model.MediaInfo;
  14. using MediaBrowser.Model.Serialization;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Diagnostics;
  18. using System.Globalization;
  19. using System.IO;
  20. using System.Linq;
  21. using System.Text;
  22. using System.Threading;
  23. using System.Threading.Tasks;
  24. using CommonIO;
  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 IFileSystem FileSystem { get; private set; }
  58. protected IDlnaManager DlnaManager { get; private set; }
  59. protected IDeviceManager DeviceManager { get; private set; }
  60. protected ISubtitleEncoder SubtitleEncoder { get; private set; }
  61. protected IMediaSourceManager MediaSourceManager { get; private set; }
  62. protected IZipClient ZipClient { get; private set; }
  63. protected IJsonSerializer JsonSerializer { get; private set; }
  64. /// <summary>
  65. /// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
  66. /// </summary>
  67. protected BaseStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer)
  68. {
  69. JsonSerializer = jsonSerializer;
  70. ZipClient = zipClient;
  71. MediaSourceManager = mediaSourceManager;
  72. DeviceManager = deviceManager;
  73. SubtitleEncoder = subtitleEncoder;
  74. DlnaManager = dlnaManager;
  75. FileSystem = fileSystem;
  76. ServerConfigurationManager = serverConfig;
  77. UserManager = userManager;
  78. LibraryManager = libraryManager;
  79. IsoManager = isoManager;
  80. MediaEncoder = mediaEncoder;
  81. }
  82. /// <summary>
  83. /// Gets the command line arguments.
  84. /// </summary>
  85. /// <param name="outputPath">The output path.</param>
  86. /// <param name="state">The state.</param>
  87. /// <param name="isEncoding">if set to <c>true</c> [is encoding].</param>
  88. /// <returns>System.String.</returns>
  89. protected abstract string GetCommandLineArguments(string outputPath, StreamState state, bool isEncoding);
  90. /// <summary>
  91. /// Gets the type of the transcoding job.
  92. /// </summary>
  93. /// <value>The type of the transcoding job.</value>
  94. protected abstract TranscodingJobType TranscodingJobType { get; }
  95. /// <summary>
  96. /// Gets the output file extension.
  97. /// </summary>
  98. /// <param name="state">The state.</param>
  99. /// <returns>System.String.</returns>
  100. protected virtual string GetOutputFileExtension(StreamState state)
  101. {
  102. return Path.GetExtension(state.RequestedUrl);
  103. }
  104. /// <summary>
  105. /// Gets the output file path.
  106. /// </summary>
  107. /// <param name="state">The state.</param>
  108. /// <returns>System.String.</returns>
  109. private string GetOutputFilePath(StreamState state)
  110. {
  111. var folder = ServerConfigurationManager.ApplicationPaths.TranscodingTempPath;
  112. var outputFileExtension = GetOutputFileExtension(state);
  113. var data = GetCommandLineArguments("dummy\\dummy", state, false);
  114. data += "-" + (state.Request.DeviceId ?? string.Empty);
  115. data += "-" + (state.Request.PlaySessionId ?? string.Empty);
  116. var dataHash = data.GetMD5().ToString("N");
  117. if (EnableOutputInSubFolder)
  118. {
  119. return Path.Combine(folder, dataHash, dataHash + (outputFileExtension ?? string.Empty).ToLower());
  120. }
  121. return Path.Combine(folder, dataHash + (outputFileExtension ?? string.Empty).ToLower());
  122. }
  123. protected virtual bool EnableOutputInSubFolder
  124. {
  125. get { return false; }
  126. }
  127. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  128. /// <summary>
  129. /// Gets the fast seek command line parameter.
  130. /// </summary>
  131. /// <param name="request">The request.</param>
  132. /// <returns>System.String.</returns>
  133. /// <value>The fast seek command line parameter.</value>
  134. protected string GetFastSeekCommandLineParameter(StreamRequest request)
  135. {
  136. var time = request.StartTimeTicks ?? 0;
  137. if (time > 0)
  138. {
  139. return string.Format("-ss {0}", MediaEncoder.GetTimeParameter(time));
  140. }
  141. return string.Empty;
  142. }
  143. /// <summary>
  144. /// Gets the map args.
  145. /// </summary>
  146. /// <param name="state">The state.</param>
  147. /// <returns>System.String.</returns>
  148. protected virtual string GetMapArgs(StreamState state)
  149. {
  150. // If we don't have known media info
  151. // If input is video, use -sn to drop subtitles
  152. // Otherwise just return empty
  153. if (state.VideoStream == null && state.AudioStream == null)
  154. {
  155. return state.IsInputVideo ? "-sn" : string.Empty;
  156. }
  157. // We have media info, but we don't know the stream indexes
  158. if (state.VideoStream != null && state.VideoStream.Index == -1)
  159. {
  160. return "-sn";
  161. }
  162. // We have media info, but we don't know the stream indexes
  163. if (state.AudioStream != null && state.AudioStream.Index == -1)
  164. {
  165. return state.IsInputVideo ? "-sn" : string.Empty;
  166. }
  167. var args = string.Empty;
  168. if (state.VideoStream != null)
  169. {
  170. args += string.Format("-map 0:{0}", state.VideoStream.Index);
  171. }
  172. else
  173. {
  174. args += "-map -0:v";
  175. }
  176. if (state.AudioStream != null)
  177. {
  178. args += string.Format(" -map 0:{0}", state.AudioStream.Index);
  179. }
  180. else
  181. {
  182. args += " -map -0:a";
  183. }
  184. if (state.SubtitleStream == null || state.VideoRequest.SubtitleMethod == SubtitleDeliveryMethod.Hls)
  185. {
  186. args += " -map -0:s";
  187. }
  188. else if (state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  189. {
  190. args += " -map 1:0 -sn";
  191. }
  192. return args;
  193. }
  194. /// <summary>
  195. /// Determines which stream will be used for playback
  196. /// </summary>
  197. /// <param name="allStream">All stream.</param>
  198. /// <param name="desiredIndex">Index of the desired.</param>
  199. /// <param name="type">The type.</param>
  200. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  201. /// <returns>MediaStream.</returns>
  202. private MediaStream GetMediaStream(IEnumerable<MediaStream> allStream, int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  203. {
  204. var streams = allStream.Where(s => s.Type == type).OrderBy(i => i.Index).ToList();
  205. if (desiredIndex.HasValue)
  206. {
  207. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  208. if (stream != null)
  209. {
  210. return stream;
  211. }
  212. }
  213. if (type == MediaStreamType.Video)
  214. {
  215. streams = streams.Where(i => !string.Equals(i.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase)).ToList();
  216. }
  217. if (returnFirstIfNoIndex && type == MediaStreamType.Audio)
  218. {
  219. return streams.FirstOrDefault(i => i.Channels.HasValue && i.Channels.Value > 0) ??
  220. streams.FirstOrDefault();
  221. }
  222. // Just return the first one
  223. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  224. }
  225. /// <summary>
  226. /// Gets the number of threads.
  227. /// </summary>
  228. /// <returns>System.Int32.</returns>
  229. protected int GetNumberOfThreads(StreamState state, bool isWebm)
  230. {
  231. var threads = ApiEntryPoint.Instance.GetEncodingOptions().EncodingThreadCount;
  232. if (isWebm)
  233. {
  234. // Recommended per docs
  235. return Math.Max(Environment.ProcessorCount - 1, 2);
  236. }
  237. // Automatic
  238. if (threads == -1)
  239. {
  240. return 0;
  241. }
  242. return threads;
  243. }
  244. protected string GetH264Encoder(StreamState state)
  245. {
  246. if (string.Equals(ApiEntryPoint.Instance.GetEncodingOptions().HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase) ||
  247. string.Equals(ApiEntryPoint.Instance.GetEncodingOptions().HardwareAccelerationType, "h264_qsv", StringComparison.OrdinalIgnoreCase))
  248. {
  249. return "h264_qsv";
  250. }
  251. if (string.Equals(ApiEntryPoint.Instance.GetEncodingOptions().HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase))
  252. {
  253. return "h264_nvenc";
  254. }
  255. if (string.Equals(ApiEntryPoint.Instance.GetEncodingOptions().HardwareAccelerationType, "h264_omx", StringComparison.OrdinalIgnoreCase))
  256. {
  257. return "h264_omx";
  258. }
  259. return "libx264";
  260. }
  261. /// <summary>
  262. /// Gets the video bitrate to specify on the command line
  263. /// </summary>
  264. /// <param name="state">The state.</param>
  265. /// <param name="videoCodec">The video codec.</param>
  266. /// <returns>System.String.</returns>
  267. protected string GetVideoQualityParam(StreamState state, string videoCodec)
  268. {
  269. var param = string.Empty;
  270. var isVc1 = state.VideoStream != null &&
  271. string.Equals(state.VideoStream.Codec, "vc1", StringComparison.OrdinalIgnoreCase);
  272. if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
  273. {
  274. param = "-preset superfast";
  275. param += " -crf 23";
  276. }
  277. else if (string.Equals(videoCodec, "libx265", StringComparison.OrdinalIgnoreCase))
  278. {
  279. param = "-preset fast";
  280. param += " -crf 28";
  281. }
  282. // h264 (h264_qsv)
  283. else if (string.Equals(videoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase))
  284. {
  285. param = "-preset 7 -look_ahead 0";
  286. }
  287. // h264 (h264_nvenc)
  288. else if (string.Equals(videoCodec, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
  289. {
  290. param = "-preset high-performance";
  291. }
  292. // webm
  293. else if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  294. {
  295. // Values 0-3, 0 being highest quality but slower
  296. var profileScore = 0;
  297. string crf;
  298. var qmin = "0";
  299. var qmax = "50";
  300. crf = "10";
  301. if (isVc1)
  302. {
  303. profileScore++;
  304. }
  305. // Max of 2
  306. profileScore = Math.Min(profileScore, 2);
  307. // http://www.webmproject.org/docs/encoder-parameters/
  308. param = string.Format("-speed 16 -quality good -profile:v {0} -slices 8 -crf {1} -qmin {2} -qmax {3}",
  309. profileScore.ToString(UsCulture),
  310. crf,
  311. qmin,
  312. qmax);
  313. }
  314. else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase))
  315. {
  316. param = "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  317. }
  318. // asf/wmv
  319. else if (string.Equals(videoCodec, "wmv2", StringComparison.OrdinalIgnoreCase))
  320. {
  321. param = "-qmin 2";
  322. }
  323. else if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  324. {
  325. param = "-mbd 2";
  326. }
  327. param += GetVideoBitrateParam(state, videoCodec);
  328. var framerate = GetFramerateParam(state);
  329. if (framerate.HasValue)
  330. {
  331. param += string.Format(" -r {0}", framerate.Value.ToString(UsCulture));
  332. }
  333. if (!string.IsNullOrEmpty(state.OutputVideoSync))
  334. {
  335. param += " -vsync " + state.OutputVideoSync;
  336. }
  337. if (!string.IsNullOrEmpty(state.VideoRequest.Profile))
  338. {
  339. if (!string.Equals(videoCodec, "h264_omx", StringComparison.OrdinalIgnoreCase))
  340. {
  341. // not supported by h264_omx
  342. param += " -profile:v " + state.VideoRequest.Profile;
  343. }
  344. }
  345. if (!string.IsNullOrEmpty(state.VideoRequest.Level))
  346. {
  347. // h264_qsv and h264_nvenc expect levels to be expressed as a decimal. libx264 supports decimal and non-decimal format
  348. if (string.Equals(videoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase) ||
  349. string.Equals(videoCodec, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
  350. {
  351. switch (state.VideoRequest.Level)
  352. {
  353. case "30":
  354. param += " -level 3";
  355. break;
  356. case "31":
  357. param += " -level 3.1";
  358. break;
  359. case "32":
  360. param += " -level 3.2";
  361. break;
  362. case "40":
  363. param += " -level 4";
  364. break;
  365. case "41":
  366. param += " -level 4.1";
  367. break;
  368. case "42":
  369. param += " -level 4.2";
  370. break;
  371. case "50":
  372. param += " -level 5";
  373. break;
  374. case "51":
  375. param += " -level 5.1";
  376. break;
  377. case "52":
  378. param += " -level 5.2";
  379. break;
  380. default:
  381. param += " -level " + state.VideoRequest.Level;
  382. break;
  383. }
  384. }
  385. else if (!string.Equals(videoCodec, "h264_omx", StringComparison.OrdinalIgnoreCase))
  386. {
  387. param += " -level " + state.VideoRequest.Level;
  388. }
  389. }
  390. if (!string.Equals(videoCodec, "h264_omx", StringComparison.OrdinalIgnoreCase) &&
  391. !string.Equals(videoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase) &&
  392. !string.Equals(videoCodec, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
  393. {
  394. param = "-pix_fmt yuv420p " + param;
  395. }
  396. return param;
  397. }
  398. protected string GetAudioFilterParam(StreamState state, bool isHls)
  399. {
  400. var volParam = string.Empty;
  401. var audioSampleRate = string.Empty;
  402. var channels = state.OutputAudioChannels;
  403. // Boost volume to 200% when downsampling from 6ch to 2ch
  404. if (channels.HasValue && channels.Value <= 2)
  405. {
  406. if (state.AudioStream != null && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5 && !ApiEntryPoint.Instance.GetEncodingOptions().DownMixAudioBoost.Equals(1))
  407. {
  408. volParam = ",volume=" + ApiEntryPoint.Instance.GetEncodingOptions().DownMixAudioBoost.ToString(UsCulture);
  409. }
  410. }
  411. if (state.OutputAudioSampleRate.HasValue)
  412. {
  413. audioSampleRate = state.OutputAudioSampleRate.Value + ":";
  414. }
  415. var adelay = isHls ? "adelay=1," : string.Empty;
  416. var pts = string.Empty;
  417. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.VideoRequest.SubtitleMethod == SubtitleDeliveryMethod.Encode && !state.VideoRequest.CopyTimestamps)
  418. {
  419. var seconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds;
  420. pts = string.Format(",asetpts=PTS-{0}/TB", Math.Round(seconds).ToString(UsCulture));
  421. }
  422. return string.Format("-af \"{0}aresample={1}async={4}{2}{3}\"",
  423. adelay,
  424. audioSampleRate,
  425. volParam,
  426. pts,
  427. state.OutputAudioSync);
  428. }
  429. /// <summary>
  430. /// If we're going to put a fixed size on the command line, this will calculate it
  431. /// </summary>
  432. /// <param name="state">The state.</param>
  433. /// <param name="outputVideoCodec">The output video codec.</param>
  434. /// <param name="allowTimeStampCopy">if set to <c>true</c> [allow time stamp copy].</param>
  435. /// <returns>System.String.</returns>
  436. protected string GetOutputSizeParam(StreamState state,
  437. string outputVideoCodec,
  438. bool allowTimeStampCopy = true)
  439. {
  440. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  441. var request = state.VideoRequest;
  442. var filters = new List<string>();
  443. if (state.DeInterlace)
  444. {
  445. filters.Add("yadif=0:-1:0");
  446. }
  447. // If fixed dimensions were supplied
  448. if (request.Width.HasValue && request.Height.HasValue)
  449. {
  450. var widthParam = request.Width.Value.ToString(UsCulture);
  451. var heightParam = request.Height.Value.ToString(UsCulture);
  452. filters.Add(string.Format("scale=trunc({0}/2)*2:trunc({1}/2)*2", widthParam, heightParam));
  453. }
  454. // 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
  455. else if (request.MaxWidth.HasValue && request.MaxHeight.HasValue)
  456. {
  457. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  458. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  459. filters.Add(string.Format("scale=trunc(min(max(iw\\,ih*dar)\\,min({0}\\,{1}*dar))/2)*2:trunc(min(max(iw/dar\\,ih)\\,min({0}/dar\\,{1}))/2)*2", maxWidthParam, maxHeightParam));
  460. }
  461. // If a fixed width was requested
  462. else if (request.Width.HasValue)
  463. {
  464. var widthParam = request.Width.Value.ToString(UsCulture);
  465. filters.Add(string.Format("scale={0}:trunc(ow/a/2)*2", widthParam));
  466. }
  467. // If a fixed height was requested
  468. else if (request.Height.HasValue)
  469. {
  470. var heightParam = request.Height.Value.ToString(UsCulture);
  471. filters.Add(string.Format("scale=trunc(oh*a/2)*2:{0}", heightParam));
  472. }
  473. // If a max width was requested
  474. else if (request.MaxWidth.HasValue)
  475. {
  476. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  477. filters.Add(string.Format("scale=trunc(min(max(iw\\,ih*dar)\\,{0})/2)*2:trunc(ow/dar/2)*2", maxWidthParam));
  478. }
  479. // If a max height was requested
  480. else if (request.MaxHeight.HasValue)
  481. {
  482. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  483. filters.Add(string.Format("scale=trunc(oh*a/2)*2:min(ih\\,{0})", maxHeightParam));
  484. }
  485. var output = string.Empty;
  486. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.VideoRequest.SubtitleMethod == SubtitleDeliveryMethod.Encode)
  487. {
  488. var subParam = GetTextSubtitleParam(state);
  489. filters.Add(subParam);
  490. if (allowTimeStampCopy)
  491. {
  492. output += " -copyts";
  493. }
  494. }
  495. if (filters.Count > 0)
  496. {
  497. output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray()));
  498. }
  499. return output;
  500. }
  501. /// <summary>
  502. /// Gets the text subtitle param.
  503. /// </summary>
  504. /// <param name="state">The state.</param>
  505. /// <returns>System.String.</returns>
  506. protected string GetTextSubtitleParam(StreamState state)
  507. {
  508. var seconds = Math.Round(TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds);
  509. var setPtsParam = state.VideoRequest.CopyTimestamps
  510. ? string.Empty
  511. : string.Format(",setpts=PTS -{0}/TB", seconds.ToString(UsCulture));
  512. if (state.SubtitleStream.IsExternal)
  513. {
  514. var subtitlePath = state.SubtitleStream.Path;
  515. var charsetParam = string.Empty;
  516. if (!string.IsNullOrEmpty(state.SubtitleStream.Language))
  517. {
  518. var charenc = SubtitleEncoder.GetSubtitleFileCharacterSet(subtitlePath, state.SubtitleStream.Language, state.MediaSource.Protocol, CancellationToken.None).Result;
  519. if (!string.IsNullOrEmpty(charenc))
  520. {
  521. charsetParam = ":charenc=" + charenc;
  522. }
  523. }
  524. // TODO: Perhaps also use original_size=1920x800 ??
  525. return string.Format("subtitles=filename='{0}'{1}{2}",
  526. MediaEncoder.EscapeSubtitleFilterPath(subtitlePath),
  527. charsetParam,
  528. setPtsParam);
  529. }
  530. var mediaPath = state.MediaPath ?? string.Empty;
  531. return string.Format("subtitles='{0}:si={1}'{2}",
  532. MediaEncoder.EscapeSubtitleFilterPath(mediaPath),
  533. state.InternalSubtitleStreamOffset.ToString(UsCulture),
  534. setPtsParam);
  535. }
  536. /// <summary>
  537. /// Gets the internal graphical subtitle param.
  538. /// </summary>
  539. /// <param name="state">The state.</param>
  540. /// <param name="outputVideoCodec">The output video codec.</param>
  541. /// <returns>System.String.</returns>
  542. protected string GetGraphicalSubtitleParam(StreamState state, string outputVideoCodec)
  543. {
  544. var outputSizeParam = string.Empty;
  545. var request = state.VideoRequest;
  546. // Add resolution params, if specified
  547. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  548. {
  549. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec).TrimEnd('"');
  550. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  551. }
  552. var videoSizeParam = string.Empty;
  553. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  554. {
  555. videoSizeParam = string.Format(",scale={0}:{1}", state.VideoStream.Width.Value.ToString(UsCulture), state.VideoStream.Height.Value.ToString(UsCulture));
  556. }
  557. var mapPrefix = state.SubtitleStream.IsExternal ?
  558. 1 :
  559. 0;
  560. var subtitleStreamIndex = state.SubtitleStream.IsExternal
  561. ? 0
  562. : state.SubtitleStream.Index;
  563. return string.Format(" -filter_complex \"[{0}:{1}]format=yuva444p{4},lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:{2}] [sub] overlay{3}\"",
  564. mapPrefix.ToString(UsCulture),
  565. subtitleStreamIndex.ToString(UsCulture),
  566. state.VideoStream.Index.ToString(UsCulture),
  567. outputSizeParam,
  568. videoSizeParam);
  569. }
  570. /// <summary>
  571. /// Gets the probe size argument.
  572. /// </summary>
  573. /// <param name="state">The state.</param>
  574. /// <returns>System.String.</returns>
  575. private string GetProbeSizeArgument(StreamState state)
  576. {
  577. if (state.PlayableStreamFileNames.Count > 0)
  578. {
  579. return MediaEncoder.GetProbeSizeArgument(state.PlayableStreamFileNames.ToArray(), state.InputProtocol);
  580. }
  581. return MediaEncoder.GetProbeSizeArgument(new[] { state.MediaPath }, state.InputProtocol);
  582. }
  583. /// <summary>
  584. /// Gets the number of audio channels to specify on the command line
  585. /// </summary>
  586. /// <param name="request">The request.</param>
  587. /// <param name="audioStream">The audio stream.</param>
  588. /// <param name="outputAudioCodec">The output audio codec.</param>
  589. /// <returns>System.Nullable{System.Int32}.</returns>
  590. private int? GetNumAudioChannelsParam(StreamRequest request, MediaStream audioStream, string outputAudioCodec)
  591. {
  592. var inputChannels = audioStream == null
  593. ? null
  594. : audioStream.Channels;
  595. if (inputChannels <= 0)
  596. {
  597. inputChannels = null;
  598. }
  599. int? resultChannels = null;
  600. var codec = outputAudioCodec ?? string.Empty;
  601. if (codec.IndexOf("wma", StringComparison.OrdinalIgnoreCase) != -1)
  602. {
  603. // wmav2 currently only supports two channel output
  604. resultChannels = Math.Min(2, inputChannels ?? 2);
  605. }
  606. else if (request.MaxAudioChannels.HasValue)
  607. {
  608. var channelLimit = codec.IndexOf("mp3", StringComparison.OrdinalIgnoreCase) != -1
  609. ? 2
  610. : 6;
  611. if (inputChannels.HasValue)
  612. {
  613. channelLimit = Math.Min(channelLimit, inputChannels.Value);
  614. }
  615. // If we don't have any media info then limit it to 5 to prevent encoding errors due to asking for too many channels
  616. resultChannels = Math.Min(request.MaxAudioChannels.Value, channelLimit);
  617. }
  618. if (resultChannels.HasValue && !string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
  619. {
  620. if (request.TranscodingMaxAudioChannels.HasValue)
  621. {
  622. resultChannels = Math.Min(request.TranscodingMaxAudioChannels.Value, resultChannels.Value);
  623. }
  624. }
  625. return resultChannels ?? request.AudioChannels;
  626. }
  627. /// <summary>
  628. /// Determines whether the specified stream is H264.
  629. /// </summary>
  630. /// <param name="stream">The stream.</param>
  631. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  632. protected bool IsH264(MediaStream stream)
  633. {
  634. var codec = stream.Codec ?? string.Empty;
  635. return codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  636. codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  637. }
  638. /// <summary>
  639. /// Gets the audio encoder.
  640. /// </summary>
  641. /// <param name="state">The state.</param>
  642. /// <returns>System.String.</returns>
  643. protected string GetAudioEncoder(StreamState state)
  644. {
  645. var codec = state.OutputAudioCodec;
  646. if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase))
  647. {
  648. return "aac -strict experimental";
  649. }
  650. if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
  651. {
  652. return "libmp3lame";
  653. }
  654. if (string.Equals(codec, "vorbis", StringComparison.OrdinalIgnoreCase))
  655. {
  656. return "libvorbis";
  657. }
  658. if (string.Equals(codec, "wma", StringComparison.OrdinalIgnoreCase))
  659. {
  660. return "wmav2";
  661. }
  662. return codec.ToLower();
  663. }
  664. /// <summary>
  665. /// Gets the name of the output video codec
  666. /// </summary>
  667. /// <param name="state">The state.</param>
  668. /// <returns>System.String.</returns>
  669. protected string GetVideoEncoder(StreamState state)
  670. {
  671. var codec = state.OutputVideoCodec;
  672. if (!string.IsNullOrEmpty(codec))
  673. {
  674. if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
  675. {
  676. return GetH264Encoder(state);
  677. }
  678. if (string.Equals(codec, "vpx", StringComparison.OrdinalIgnoreCase))
  679. {
  680. return "libvpx";
  681. }
  682. if (string.Equals(codec, "wmv", StringComparison.OrdinalIgnoreCase))
  683. {
  684. return "wmv2";
  685. }
  686. if (string.Equals(codec, "theora", StringComparison.OrdinalIgnoreCase))
  687. {
  688. return "libtheora";
  689. }
  690. return codec.ToLower();
  691. }
  692. return "copy";
  693. }
  694. /// <summary>
  695. /// Gets the name of the output video codec
  696. /// </summary>
  697. /// <param name="state">The state.</param>
  698. /// <returns>System.String.</returns>
  699. protected string GetVideoDecoder(StreamState state)
  700. {
  701. if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  702. {
  703. return null;
  704. }
  705. if (state.VideoStream != null && !string.IsNullOrWhiteSpace(state.VideoStream.Codec))
  706. {
  707. if (string.Equals(ApiEntryPoint.Instance.GetEncodingOptions().HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
  708. {
  709. switch (state.MediaSource.VideoStream.Codec.ToLower())
  710. {
  711. case "avc":
  712. case "h264":
  713. if (MediaEncoder.SupportsDecoder("h264_qsv"))
  714. {
  715. // Seeing stalls and failures with decoding. Not worth it compared to encoding.
  716. return "-c:v h264_qsv ";
  717. }
  718. break;
  719. case "mpeg2video":
  720. if (MediaEncoder.SupportsDecoder("mpeg2_qsv"))
  721. {
  722. return "-c:v mpeg2_qsv ";
  723. }
  724. break;
  725. case "vc1":
  726. if (MediaEncoder.SupportsDecoder("vc1_qsv"))
  727. {
  728. return "-c:v vc1_qsv ";
  729. }
  730. break;
  731. }
  732. }
  733. }
  734. // leave blank so ffmpeg will decide
  735. return null;
  736. }
  737. /// <summary>
  738. /// Gets the input argument.
  739. /// </summary>
  740. /// <param name="state">The state.</param>
  741. /// <returns>System.String.</returns>
  742. protected string GetInputArgument(StreamState state)
  743. {
  744. var arg = string.Format("-i {0}", GetInputPathArgument(state));
  745. if (state.SubtitleStream != null && state.VideoRequest.SubtitleMethod == SubtitleDeliveryMethod.Encode)
  746. {
  747. if (state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  748. {
  749. if (state.VideoStream != null && state.VideoStream.Width.HasValue)
  750. {
  751. // This is hacky but not sure how to get the exact subtitle resolution
  752. double height = state.VideoStream.Width.Value;
  753. height /= 16;
  754. height *= 9;
  755. arg += string.Format(" -canvas_size {0}:{1}", state.VideoStream.Width.Value.ToString(CultureInfo.InvariantCulture), Convert.ToInt32(height).ToString(CultureInfo.InvariantCulture));
  756. }
  757. arg += " -i \"" + state.SubtitleStream.Path + "\"";
  758. }
  759. }
  760. return arg.Trim();
  761. }
  762. private string GetInputPathArgument(StreamState state)
  763. {
  764. var protocol = state.InputProtocol;
  765. var mediaPath = state.MediaPath ?? string.Empty;
  766. var inputPath = new[] { mediaPath };
  767. if (state.IsInputVideo)
  768. {
  769. if (!(state.VideoType == VideoType.Iso && state.IsoMount == null))
  770. {
  771. inputPath = MediaEncoderHelpers.GetInputArgument(FileSystem, mediaPath, state.InputProtocol, state.IsoMount, state.PlayableStreamFileNames);
  772. }
  773. }
  774. return MediaEncoder.GetInputArgument(inputPath, protocol);
  775. }
  776. private async Task AcquireResources(StreamState state, CancellationTokenSource cancellationTokenSource)
  777. {
  778. if (state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  779. {
  780. state.IsoMount = await IsoManager.Mount(state.MediaPath, cancellationTokenSource.Token).ConfigureAwait(false);
  781. }
  782. if (state.MediaSource.RequiresOpening && string.IsNullOrWhiteSpace(state.Request.LiveStreamId))
  783. {
  784. var liveStreamResponse = await MediaSourceManager.OpenLiveStream(new LiveStreamRequest
  785. {
  786. OpenToken = state.MediaSource.OpenToken
  787. }, false, cancellationTokenSource.Token).ConfigureAwait(false);
  788. AttachMediaSourceInfo(state, liveStreamResponse.MediaSource, state.VideoRequest, state.RequestedUrl);
  789. if (state.VideoRequest != null)
  790. {
  791. TryStreamCopy(state, state.VideoRequest);
  792. }
  793. }
  794. if (state.MediaSource.BufferMs.HasValue)
  795. {
  796. await Task.Delay(state.MediaSource.BufferMs.Value, cancellationTokenSource.Token).ConfigureAwait(false);
  797. }
  798. }
  799. /// <summary>
  800. /// Starts the FFMPEG.
  801. /// </summary>
  802. /// <param name="state">The state.</param>
  803. /// <param name="outputPath">The output path.</param>
  804. /// <param name="cancellationTokenSource">The cancellation token source.</param>
  805. /// <param name="workingDirectory">The working directory.</param>
  806. /// <returns>Task.</returns>
  807. protected async Task<TranscodingJob> StartFfMpeg(StreamState state,
  808. string outputPath,
  809. CancellationTokenSource cancellationTokenSource,
  810. string workingDirectory = null)
  811. {
  812. FileSystem.CreateDirectory(Path.GetDirectoryName(outputPath));
  813. await AcquireResources(state, cancellationTokenSource).ConfigureAwait(false);
  814. if (state.VideoRequest != null && !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  815. {
  816. var auth = AuthorizationContext.GetAuthorizationInfo(Request);
  817. if (!string.IsNullOrWhiteSpace(auth.UserId))
  818. {
  819. var user = UserManager.GetUserById(auth.UserId);
  820. if (!user.Policy.EnableVideoPlaybackTranscoding)
  821. {
  822. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType, state);
  823. throw new ArgumentException("User does not have access to video transcoding");
  824. }
  825. }
  826. }
  827. var transcodingId = Guid.NewGuid().ToString("N");
  828. var commandLineArgs = GetCommandLineArguments(outputPath, state, true);
  829. var process = new Process
  830. {
  831. StartInfo = new ProcessStartInfo
  832. {
  833. CreateNoWindow = true,
  834. UseShellExecute = false,
  835. // Must consume both stdout and stderr or deadlocks may occur
  836. //RedirectStandardOutput = true,
  837. RedirectStandardError = true,
  838. RedirectStandardInput = true,
  839. FileName = MediaEncoder.EncoderPath,
  840. Arguments = commandLineArgs,
  841. WindowStyle = ProcessWindowStyle.Hidden,
  842. ErrorDialog = false
  843. },
  844. EnableRaisingEvents = true
  845. };
  846. if (!string.IsNullOrWhiteSpace(workingDirectory))
  847. {
  848. process.StartInfo.WorkingDirectory = workingDirectory;
  849. }
  850. var transcodingJob = ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath,
  851. state.Request.PlaySessionId,
  852. state.MediaSource.LiveStreamId,
  853. transcodingId,
  854. TranscodingJobType,
  855. process,
  856. state.Request.DeviceId,
  857. state,
  858. cancellationTokenSource);
  859. var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  860. Logger.Info(commandLineLogMessage);
  861. var logFilePrefix = "transcode";
  862. if (state.VideoRequest != null && string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase) && string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
  863. {
  864. logFilePrefix = "directstream";
  865. }
  866. else if (state.VideoRequest != null && string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  867. {
  868. logFilePrefix = "remux";
  869. }
  870. var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + "-" + Guid.NewGuid() + ".txt");
  871. FileSystem.CreateDirectory(Path.GetDirectoryName(logFilePath));
  872. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  873. state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  874. var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(Request.AbsoluteUri + Environment.NewLine + Environment.NewLine + JsonSerializer.SerializeToString(state.MediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine);
  875. await state.LogFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationTokenSource.Token).ConfigureAwait(false);
  876. process.Exited += (sender, args) => OnFfMpegProcessExited(process, transcodingJob, state);
  877. try
  878. {
  879. process.Start();
  880. }
  881. catch (Exception ex)
  882. {
  883. Logger.ErrorException("Error starting ffmpeg", ex);
  884. ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType, state);
  885. throw;
  886. }
  887. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  888. //process.BeginOutputReadLine();
  889. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  890. Task.Run(() => StartStreamingLog(transcodingJob, state, process.StandardError.BaseStream, state.LogFileStream));
  891. // Wait for the file to exist before proceeeding
  892. while (!FileSystem.FileExists(state.WaitForPath ?? outputPath) && !transcodingJob.HasExited)
  893. {
  894. await Task.Delay(100, cancellationTokenSource.Token).ConfigureAwait(false);
  895. }
  896. if (state.IsInputVideo && transcodingJob.Type == TranscodingJobType.Progressive)
  897. {
  898. await Task.Delay(1000, cancellationTokenSource.Token).ConfigureAwait(false);
  899. if (state.ReadInputAtNativeFramerate)
  900. {
  901. await Task.Delay(1500, cancellationTokenSource.Token).ConfigureAwait(false);
  902. }
  903. }
  904. StartThrottler(state, transcodingJob);
  905. return transcodingJob;
  906. }
  907. private void StartThrottler(StreamState state, TranscodingJob transcodingJob)
  908. {
  909. if (EnableThrottling(state) && state.InputProtocol == MediaProtocol.File &&
  910. state.RunTimeTicks.HasValue &&
  911. state.VideoType == VideoType.VideoFile &&
  912. !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  913. {
  914. if (state.RunTimeTicks.Value >= TimeSpan.FromMinutes(5).Ticks && state.IsInputVideo)
  915. {
  916. transcodingJob.TranscodingThrottler = state.TranscodingThrottler = new TranscodingThrottler(transcodingJob, Logger, ServerConfigurationManager);
  917. state.TranscodingThrottler.Start();
  918. }
  919. }
  920. }
  921. protected virtual bool EnableThrottling(StreamState state)
  922. {
  923. return true;
  924. }
  925. private async Task StartStreamingLog(TranscodingJob transcodingJob, StreamState state, Stream source, Stream target)
  926. {
  927. try
  928. {
  929. using (var reader = new StreamReader(source))
  930. {
  931. while (!reader.EndOfStream)
  932. {
  933. var line = await reader.ReadLineAsync().ConfigureAwait(false);
  934. ParseLogLine(line, transcodingJob, state);
  935. var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
  936. await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  937. await target.FlushAsync().ConfigureAwait(false);
  938. }
  939. }
  940. }
  941. catch (ObjectDisposedException)
  942. {
  943. // Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux
  944. }
  945. catch (Exception ex)
  946. {
  947. Logger.ErrorException("Error reading ffmpeg log", ex);
  948. }
  949. }
  950. private void ParseLogLine(string line, TranscodingJob transcodingJob, StreamState state)
  951. {
  952. float? framerate = null;
  953. double? percent = null;
  954. TimeSpan? transcodingPosition = null;
  955. long? bytesTranscoded = null;
  956. var parts = line.Split(' ');
  957. var totalMs = state.RunTimeTicks.HasValue
  958. ? TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalMilliseconds
  959. : 0;
  960. var startMs = state.Request.StartTimeTicks.HasValue
  961. ? TimeSpan.FromTicks(state.Request.StartTimeTicks.Value).TotalMilliseconds
  962. : 0;
  963. for (var i = 0; i < parts.Length; i++)
  964. {
  965. var part = parts[i];
  966. if (string.Equals(part, "fps=", StringComparison.OrdinalIgnoreCase) &&
  967. (i + 1 < parts.Length))
  968. {
  969. var rate = parts[i + 1];
  970. float val;
  971. if (float.TryParse(rate, NumberStyles.Any, UsCulture, out val))
  972. {
  973. framerate = val;
  974. }
  975. }
  976. else if (state.RunTimeTicks.HasValue &&
  977. part.StartsWith("time=", StringComparison.OrdinalIgnoreCase))
  978. {
  979. var time = part.Split(new[] { '=' }, 2).Last();
  980. TimeSpan val;
  981. if (TimeSpan.TryParse(time, UsCulture, out val))
  982. {
  983. var currentMs = startMs + val.TotalMilliseconds;
  984. var percentVal = currentMs / totalMs;
  985. percent = 100 * percentVal;
  986. transcodingPosition = val;
  987. }
  988. }
  989. else if (part.StartsWith("size=", StringComparison.OrdinalIgnoreCase))
  990. {
  991. var size = part.Split(new[] { '=' }, 2).Last();
  992. int? scale = null;
  993. if (size.IndexOf("kb", StringComparison.OrdinalIgnoreCase) != -1)
  994. {
  995. scale = 1024;
  996. size = size.Replace("kb", string.Empty, StringComparison.OrdinalIgnoreCase);
  997. }
  998. if (scale.HasValue)
  999. {
  1000. long val;
  1001. if (long.TryParse(size, NumberStyles.Any, UsCulture, out val))
  1002. {
  1003. bytesTranscoded = val * scale.Value;
  1004. }
  1005. }
  1006. }
  1007. }
  1008. if (framerate.HasValue || percent.HasValue)
  1009. {
  1010. ApiEntryPoint.Instance.ReportTranscodingProgress(transcodingJob, state, transcodingPosition, framerate, percent, bytesTranscoded);
  1011. }
  1012. }
  1013. private int? GetVideoBitrateParamValue(VideoStreamRequest request, MediaStream videoStream, string outputVideoCodec)
  1014. {
  1015. var bitrate = request.VideoBitRate;
  1016. if (videoStream != null)
  1017. {
  1018. var isUpscaling = request.Height.HasValue && videoStream.Height.HasValue &&
  1019. request.Height.Value > videoStream.Height.Value;
  1020. if (request.Width.HasValue && videoStream.Width.HasValue &&
  1021. request.Width.Value > videoStream.Width.Value)
  1022. {
  1023. isUpscaling = true;
  1024. }
  1025. // Don't allow bitrate increases unless upscaling
  1026. if (!isUpscaling)
  1027. {
  1028. if (bitrate.HasValue && videoStream.BitRate.HasValue)
  1029. {
  1030. bitrate = Math.Min(bitrate.Value, videoStream.BitRate.Value);
  1031. }
  1032. }
  1033. }
  1034. if (bitrate.HasValue)
  1035. {
  1036. var inputVideoCodec = videoStream == null ? null : videoStream.Codec;
  1037. bitrate = ResolutionNormalizer.ScaleBitrate(bitrate.Value, inputVideoCodec, outputVideoCodec);
  1038. // If a max bitrate was requested, don't let the scaled bitrate exceed it
  1039. if (request.VideoBitRate.HasValue)
  1040. {
  1041. bitrate = Math.Min(bitrate.Value, request.VideoBitRate.Value);
  1042. }
  1043. }
  1044. return bitrate;
  1045. }
  1046. protected string GetVideoBitrateParam(StreamState state, string videoCodec)
  1047. {
  1048. var bitrate = state.OutputVideoBitrate;
  1049. if (bitrate.HasValue)
  1050. {
  1051. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  1052. {
  1053. // With vpx when crf is used, b:v becomes a max rate
  1054. // https://trac.ffmpeg.org/wiki/vpxEncodingGuide. But higher bitrate source files -b:v causes judder so limite the bitrate but dont allow it to "saturate" the bitrate. So dont contrain it down just up.
  1055. return string.Format(" -maxrate:v {0} -bufsize:v ({0}*2) -b:v {0}", bitrate.Value.ToString(UsCulture));
  1056. }
  1057. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  1058. {
  1059. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  1060. }
  1061. // h264
  1062. return string.Format(" -b:v {0} -maxrate {0} -bufsize {1}",
  1063. bitrate.Value.ToString(UsCulture),
  1064. (bitrate.Value * 2).ToString(UsCulture));
  1065. }
  1066. return string.Empty;
  1067. }
  1068. private int? GetAudioBitrateParam(StreamRequest request, MediaStream audioStream)
  1069. {
  1070. if (request.AudioBitRate.HasValue)
  1071. {
  1072. // Make sure we don't request a bitrate higher than the source
  1073. var currentBitrate = audioStream == null ? request.AudioBitRate.Value : audioStream.BitRate ?? request.AudioBitRate.Value;
  1074. return request.AudioBitRate.Value;
  1075. //return Math.Min(currentBitrate, request.AudioBitRate.Value);
  1076. }
  1077. return null;
  1078. }
  1079. /// <summary>
  1080. /// Gets the user agent param.
  1081. /// </summary>
  1082. /// <param name="state">The state.</param>
  1083. /// <returns>System.String.</returns>
  1084. private string GetUserAgentParam(StreamState state)
  1085. {
  1086. string useragent = null;
  1087. state.RemoteHttpHeaders.TryGetValue("User-Agent", out useragent);
  1088. if (!string.IsNullOrWhiteSpace(useragent))
  1089. {
  1090. return "-user-agent \"" + useragent + "\"";
  1091. }
  1092. return string.Empty;
  1093. }
  1094. /// <summary>
  1095. /// Processes the exited.
  1096. /// </summary>
  1097. /// <param name="process">The process.</param>
  1098. /// <param name="job">The job.</param>
  1099. /// <param name="state">The state.</param>
  1100. private void OnFfMpegProcessExited(Process process, TranscodingJob job, StreamState state)
  1101. {
  1102. if (job != null)
  1103. {
  1104. job.HasExited = true;
  1105. }
  1106. Logger.Debug("Disposing stream resources");
  1107. state.Dispose();
  1108. try
  1109. {
  1110. Logger.Info("FFMpeg exited with code {0}", process.ExitCode);
  1111. }
  1112. catch
  1113. {
  1114. Logger.Error("FFMpeg exited with an error.");
  1115. }
  1116. // This causes on exited to be called twice:
  1117. //try
  1118. //{
  1119. // // Dispose the process
  1120. // process.Dispose();
  1121. //}
  1122. //catch (Exception ex)
  1123. //{
  1124. // Logger.ErrorException("Error disposing ffmpeg.", ex);
  1125. //}
  1126. }
  1127. protected double? GetFramerateParam(StreamState state)
  1128. {
  1129. if (state.VideoRequest != null)
  1130. {
  1131. if (state.VideoRequest.Framerate.HasValue)
  1132. {
  1133. return state.VideoRequest.Framerate.Value;
  1134. }
  1135. var maxrate = state.VideoRequest.MaxFramerate;
  1136. if (maxrate.HasValue && state.VideoStream != null)
  1137. {
  1138. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  1139. if (contentRate.HasValue && contentRate.Value > maxrate.Value)
  1140. {
  1141. return maxrate;
  1142. }
  1143. }
  1144. }
  1145. return null;
  1146. }
  1147. /// <summary>
  1148. /// Parses the parameters.
  1149. /// </summary>
  1150. /// <param name="request">The request.</param>
  1151. private void ParseParams(StreamRequest request)
  1152. {
  1153. var vals = request.Params.Split(';');
  1154. var videoRequest = request as VideoStreamRequest;
  1155. for (var i = 0; i < vals.Length; i++)
  1156. {
  1157. var val = vals[i];
  1158. if (string.IsNullOrWhiteSpace(val))
  1159. {
  1160. continue;
  1161. }
  1162. if (i == 0)
  1163. {
  1164. request.DeviceProfileId = val;
  1165. }
  1166. else if (i == 1)
  1167. {
  1168. request.DeviceId = val;
  1169. }
  1170. else if (i == 2)
  1171. {
  1172. request.MediaSourceId = val;
  1173. }
  1174. else if (i == 3)
  1175. {
  1176. request.Static = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  1177. }
  1178. else if (i == 4)
  1179. {
  1180. if (videoRequest != null)
  1181. {
  1182. videoRequest.VideoCodec = val;
  1183. }
  1184. }
  1185. else if (i == 5)
  1186. {
  1187. request.AudioCodec = val;
  1188. }
  1189. else if (i == 6)
  1190. {
  1191. if (videoRequest != null)
  1192. {
  1193. videoRequest.AudioStreamIndex = int.Parse(val, UsCulture);
  1194. }
  1195. }
  1196. else if (i == 7)
  1197. {
  1198. if (videoRequest != null)
  1199. {
  1200. videoRequest.SubtitleStreamIndex = int.Parse(val, UsCulture);
  1201. }
  1202. }
  1203. else if (i == 8)
  1204. {
  1205. if (videoRequest != null)
  1206. {
  1207. videoRequest.VideoBitRate = int.Parse(val, UsCulture);
  1208. }
  1209. }
  1210. else if (i == 9)
  1211. {
  1212. request.AudioBitRate = int.Parse(val, UsCulture);
  1213. }
  1214. else if (i == 10)
  1215. {
  1216. request.MaxAudioChannels = int.Parse(val, UsCulture);
  1217. }
  1218. else if (i == 11)
  1219. {
  1220. if (videoRequest != null)
  1221. {
  1222. videoRequest.MaxFramerate = float.Parse(val, UsCulture);
  1223. }
  1224. }
  1225. else if (i == 12)
  1226. {
  1227. if (videoRequest != null)
  1228. {
  1229. videoRequest.MaxWidth = int.Parse(val, UsCulture);
  1230. }
  1231. }
  1232. else if (i == 13)
  1233. {
  1234. if (videoRequest != null)
  1235. {
  1236. videoRequest.MaxHeight = int.Parse(val, UsCulture);
  1237. }
  1238. }
  1239. else if (i == 14)
  1240. {
  1241. request.StartTimeTicks = long.Parse(val, UsCulture);
  1242. }
  1243. else if (i == 15)
  1244. {
  1245. if (videoRequest != null)
  1246. {
  1247. videoRequest.Level = val;
  1248. }
  1249. }
  1250. else if (i == 16)
  1251. {
  1252. if (videoRequest != null)
  1253. {
  1254. videoRequest.MaxRefFrames = int.Parse(val, UsCulture);
  1255. }
  1256. }
  1257. else if (i == 17)
  1258. {
  1259. if (videoRequest != null)
  1260. {
  1261. videoRequest.MaxVideoBitDepth = int.Parse(val, UsCulture);
  1262. }
  1263. }
  1264. else if (i == 18)
  1265. {
  1266. if (videoRequest != null)
  1267. {
  1268. videoRequest.Profile = val;
  1269. }
  1270. }
  1271. else if (i == 19)
  1272. {
  1273. // cabac no longer used
  1274. }
  1275. else if (i == 20)
  1276. {
  1277. request.PlaySessionId = val;
  1278. }
  1279. else if (i == 21)
  1280. {
  1281. // api_key
  1282. }
  1283. else if (i == 22)
  1284. {
  1285. request.LiveStreamId = val;
  1286. }
  1287. else if (i == 23)
  1288. {
  1289. // Duplicating ItemId because of MediaMonkey
  1290. }
  1291. else if (i == 24)
  1292. {
  1293. if (videoRequest != null)
  1294. {
  1295. videoRequest.CopyTimestamps = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  1296. }
  1297. }
  1298. else if (i == 25)
  1299. {
  1300. if (videoRequest != null)
  1301. {
  1302. videoRequest.ForceLiveStream = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  1303. }
  1304. }
  1305. else if (i == 26)
  1306. {
  1307. if (!string.IsNullOrWhiteSpace(val) && videoRequest != null)
  1308. {
  1309. SubtitleDeliveryMethod method;
  1310. if (Enum.TryParse(val, out method))
  1311. {
  1312. videoRequest.SubtitleMethod = method;
  1313. }
  1314. }
  1315. }
  1316. else if (i == 27)
  1317. {
  1318. request.TranscodingMaxAudioChannels = int.Parse(val, UsCulture);
  1319. }
  1320. }
  1321. }
  1322. /// <summary>
  1323. /// Parses the dlna headers.
  1324. /// </summary>
  1325. /// <param name="request">The request.</param>
  1326. private void ParseDlnaHeaders(StreamRequest request)
  1327. {
  1328. if (!request.StartTimeTicks.HasValue)
  1329. {
  1330. var timeSeek = GetHeader("TimeSeekRange.dlna.org");
  1331. request.StartTimeTicks = ParseTimeSeekHeader(timeSeek);
  1332. }
  1333. }
  1334. /// <summary>
  1335. /// Parses the time seek header.
  1336. /// </summary>
  1337. private long? ParseTimeSeekHeader(string value)
  1338. {
  1339. if (string.IsNullOrWhiteSpace(value))
  1340. {
  1341. return null;
  1342. }
  1343. if (value.IndexOf("npt=", StringComparison.OrdinalIgnoreCase) != 0)
  1344. {
  1345. throw new ArgumentException("Invalid timeseek header");
  1346. }
  1347. value = value.Substring(4).Split(new[] { '-' }, 2)[0];
  1348. if (value.IndexOf(':') == -1)
  1349. {
  1350. // Parses npt times in the format of '417.33'
  1351. double seconds;
  1352. if (double.TryParse(value, NumberStyles.Any, UsCulture, out seconds))
  1353. {
  1354. return TimeSpan.FromSeconds(seconds).Ticks;
  1355. }
  1356. throw new ArgumentException("Invalid timeseek header");
  1357. }
  1358. // Parses npt times in the format of '10:19:25.7'
  1359. var tokens = value.Split(new[] { ':' }, 3);
  1360. double secondsSum = 0;
  1361. var timeFactor = 3600;
  1362. foreach (var time in tokens)
  1363. {
  1364. double digit;
  1365. if (double.TryParse(time, NumberStyles.Any, UsCulture, out digit))
  1366. {
  1367. secondsSum += digit * timeFactor;
  1368. }
  1369. else
  1370. {
  1371. throw new ArgumentException("Invalid timeseek header");
  1372. }
  1373. timeFactor /= 60;
  1374. }
  1375. return TimeSpan.FromSeconds(secondsSum).Ticks;
  1376. }
  1377. /// <summary>
  1378. /// Gets the state.
  1379. /// </summary>
  1380. /// <param name="request">The request.</param>
  1381. /// <param name="cancellationToken">The cancellation token.</param>
  1382. /// <returns>StreamState.</returns>
  1383. protected async Task<StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
  1384. {
  1385. ParseDlnaHeaders(request);
  1386. if (!string.IsNullOrWhiteSpace(request.Params))
  1387. {
  1388. ParseParams(request);
  1389. }
  1390. var url = Request.PathInfo;
  1391. if (string.IsNullOrEmpty(request.AudioCodec))
  1392. {
  1393. request.AudioCodec = InferAudioCodec(url);
  1394. }
  1395. var state = new StreamState(MediaSourceManager, Logger)
  1396. {
  1397. Request = request,
  1398. RequestedUrl = url,
  1399. UserAgent = Request.UserAgent
  1400. };
  1401. //if ((Request.UserAgent ?? string.Empty).IndexOf("iphone", StringComparison.OrdinalIgnoreCase) != -1 ||
  1402. // (Request.UserAgent ?? string.Empty).IndexOf("ipad", StringComparison.OrdinalIgnoreCase) != -1 ||
  1403. // (Request.UserAgent ?? string.Empty).IndexOf("ipod", StringComparison.OrdinalIgnoreCase) != -1)
  1404. //{
  1405. // state.SegmentLength = 6;
  1406. //}
  1407. if (!string.IsNullOrWhiteSpace(request.AudioCodec))
  1408. {
  1409. state.SupportedAudioCodecs = request.AudioCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
  1410. state.Request.AudioCodec = state.SupportedAudioCodecs.FirstOrDefault(i => MediaEncoder.CanEncodeToAudioCodec(i))
  1411. ?? state.SupportedAudioCodecs.FirstOrDefault();
  1412. }
  1413. var item = LibraryManager.GetItemById(request.Id);
  1414. state.IsInputVideo = string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  1415. var archivable = item as IArchivable;
  1416. state.IsInputArchive = archivable != null && archivable.IsArchive;
  1417. MediaSourceInfo mediaSource;
  1418. if (string.IsNullOrWhiteSpace(request.LiveStreamId))
  1419. {
  1420. var mediaSources = (await MediaSourceManager.GetPlayackMediaSources(request.Id, null, false, new[] { MediaType.Audio, MediaType.Video }, cancellationToken).ConfigureAwait(false)).ToList();
  1421. mediaSource = string.IsNullOrEmpty(request.MediaSourceId)
  1422. ? mediaSources.First()
  1423. : mediaSources.FirstOrDefault(i => string.Equals(i.Id, request.MediaSourceId));
  1424. if (mediaSource == null && string.Equals(request.Id, request.MediaSourceId, StringComparison.OrdinalIgnoreCase))
  1425. {
  1426. mediaSource = mediaSources.First();
  1427. }
  1428. }
  1429. else
  1430. {
  1431. mediaSource = await MediaSourceManager.GetLiveStream(request.LiveStreamId, cancellationToken).ConfigureAwait(false);
  1432. }
  1433. var videoRequest = request as VideoStreamRequest;
  1434. AttachMediaSourceInfo(state, mediaSource, videoRequest, url);
  1435. var container = Path.GetExtension(state.RequestedUrl);
  1436. if (string.IsNullOrEmpty(container))
  1437. {
  1438. container = request.Static ?
  1439. state.InputContainer :
  1440. (Path.GetExtension(GetOutputFilePath(state)) ?? string.Empty).TrimStart('.');
  1441. }
  1442. state.OutputContainer = (container ?? string.Empty).TrimStart('.');
  1443. state.OutputAudioBitrate = GetAudioBitrateParam(state.Request, state.AudioStream);
  1444. state.OutputAudioSampleRate = request.AudioSampleRate;
  1445. state.OutputAudioCodec = state.Request.AudioCodec;
  1446. state.OutputAudioChannels = GetNumAudioChannelsParam(state.Request, state.AudioStream, state.OutputAudioCodec);
  1447. if (videoRequest != null)
  1448. {
  1449. state.OutputVideoCodec = state.VideoRequest.VideoCodec;
  1450. state.OutputVideoBitrate = GetVideoBitrateParamValue(state.VideoRequest, state.VideoStream, state.OutputVideoCodec);
  1451. if (state.OutputVideoBitrate.HasValue)
  1452. {
  1453. var resolution = ResolutionNormalizer.Normalize(
  1454. state.VideoStream == null ? (int?)null : state.VideoStream.BitRate,
  1455. state.OutputVideoBitrate.Value,
  1456. state.VideoStream == null ? null : state.VideoStream.Codec,
  1457. state.OutputVideoCodec,
  1458. videoRequest.MaxWidth,
  1459. videoRequest.MaxHeight);
  1460. videoRequest.MaxWidth = resolution.MaxWidth;
  1461. videoRequest.MaxHeight = resolution.MaxHeight;
  1462. }
  1463. }
  1464. ApplyDeviceProfileSettings(state);
  1465. if (videoRequest != null)
  1466. {
  1467. TryStreamCopy(state, videoRequest);
  1468. }
  1469. state.OutputFilePath = GetOutputFilePath(state);
  1470. return state;
  1471. }
  1472. private void TryStreamCopy(StreamState state, VideoStreamRequest videoRequest)
  1473. {
  1474. if (state.VideoStream != null && CanStreamCopyVideo(state))
  1475. {
  1476. state.OutputVideoCodec = "copy";
  1477. }
  1478. if (state.AudioStream != null && CanStreamCopyAudio(state, state.SupportedAudioCodecs))
  1479. {
  1480. state.OutputAudioCodec = "copy";
  1481. }
  1482. }
  1483. private void AttachMediaSourceInfo(StreamState state,
  1484. MediaSourceInfo mediaSource,
  1485. VideoStreamRequest videoRequest,
  1486. string requestedUrl)
  1487. {
  1488. state.MediaPath = mediaSource.Path;
  1489. state.InputProtocol = mediaSource.Protocol;
  1490. state.InputContainer = mediaSource.Container;
  1491. state.InputFileSize = mediaSource.Size;
  1492. state.InputBitrate = mediaSource.Bitrate;
  1493. state.RunTimeTicks = mediaSource.RunTimeTicks;
  1494. state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
  1495. if (mediaSource.VideoType.HasValue)
  1496. {
  1497. state.VideoType = mediaSource.VideoType.Value;
  1498. }
  1499. state.IsoType = mediaSource.IsoType;
  1500. state.PlayableStreamFileNames = mediaSource.PlayableStreamFileNames.ToList();
  1501. if (mediaSource.Timestamp.HasValue)
  1502. {
  1503. state.InputTimestamp = mediaSource.Timestamp.Value;
  1504. }
  1505. state.InputProtocol = mediaSource.Protocol;
  1506. state.MediaPath = mediaSource.Path;
  1507. state.RunTimeTicks = mediaSource.RunTimeTicks;
  1508. state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
  1509. state.InputBitrate = mediaSource.Bitrate;
  1510. state.InputFileSize = mediaSource.Size;
  1511. state.ReadInputAtNativeFramerate = mediaSource.ReadAtNativeFramerate;
  1512. if (state.ReadInputAtNativeFramerate ||
  1513. mediaSource.Protocol == MediaProtocol.File && string.Equals(mediaSource.Container, "wtv", StringComparison.OrdinalIgnoreCase))
  1514. {
  1515. state.OutputAudioSync = "1000";
  1516. state.InputVideoSync = "-1";
  1517. state.InputAudioSync = "1";
  1518. }
  1519. if (string.Equals(mediaSource.Container, "wma", StringComparison.OrdinalIgnoreCase))
  1520. {
  1521. // Seeing some stuttering when transcoding wma to audio-only HLS
  1522. state.InputAudioSync = "1";
  1523. }
  1524. var mediaStreams = mediaSource.MediaStreams;
  1525. if (videoRequest != null)
  1526. {
  1527. if (string.IsNullOrEmpty(videoRequest.VideoCodec))
  1528. {
  1529. videoRequest.VideoCodec = InferVideoCodec(requestedUrl);
  1530. }
  1531. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  1532. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  1533. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  1534. if (state.SubtitleStream != null && !state.SubtitleStream.IsExternal)
  1535. {
  1536. state.InternalSubtitleStreamOffset = mediaStreams.Where(i => i.Type == MediaStreamType.Subtitle && !i.IsExternal).ToList().IndexOf(state.SubtitleStream);
  1537. }
  1538. if (state.VideoStream != null && state.VideoStream.IsInterlaced)
  1539. {
  1540. state.DeInterlace = true;
  1541. }
  1542. EnforceResolutionLimit(state, videoRequest);
  1543. }
  1544. else
  1545. {
  1546. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  1547. }
  1548. state.MediaSource = mediaSource;
  1549. }
  1550. protected virtual bool CanStreamCopyVideo(StreamState state)
  1551. {
  1552. var request = state.VideoRequest;
  1553. var videoStream = state.VideoStream;
  1554. if (videoStream.IsInterlaced)
  1555. {
  1556. return false;
  1557. }
  1558. if (videoStream.IsAnamorphic ?? false)
  1559. {
  1560. return false;
  1561. }
  1562. // Can't stream copy if we're burning in subtitles
  1563. if (request.SubtitleStreamIndex.HasValue)
  1564. {
  1565. if (request.SubtitleMethod == SubtitleDeliveryMethod.Encode)
  1566. {
  1567. return false;
  1568. }
  1569. }
  1570. if (string.Equals("h264", videoStream.Codec, StringComparison.OrdinalIgnoreCase))
  1571. {
  1572. if (videoStream.IsAVC.HasValue && !videoStream.IsAVC.Value)
  1573. {
  1574. Logger.Debug("Cannot stream copy video. Stream is marked as not AVC");
  1575. return false;
  1576. }
  1577. }
  1578. // Source and target codecs must match
  1579. if (!string.Equals(request.VideoCodec, videoStream.Codec, StringComparison.OrdinalIgnoreCase))
  1580. {
  1581. return false;
  1582. }
  1583. // If client is requesting a specific video profile, it must match the source
  1584. if (!string.IsNullOrEmpty(request.Profile))
  1585. {
  1586. if (string.IsNullOrEmpty(videoStream.Profile))
  1587. {
  1588. //return false;
  1589. }
  1590. if (!string.IsNullOrEmpty(videoStream.Profile) && !string.Equals(request.Profile, videoStream.Profile, StringComparison.OrdinalIgnoreCase))
  1591. {
  1592. var currentScore = GetVideoProfileScore(videoStream.Profile);
  1593. var requestedScore = GetVideoProfileScore(request.Profile);
  1594. if (currentScore == -1 || currentScore > requestedScore)
  1595. {
  1596. return false;
  1597. }
  1598. }
  1599. }
  1600. // Video width must fall within requested value
  1601. if (request.MaxWidth.HasValue)
  1602. {
  1603. if (!videoStream.Width.HasValue || videoStream.Width.Value > request.MaxWidth.Value)
  1604. {
  1605. return false;
  1606. }
  1607. }
  1608. // Video height must fall within requested value
  1609. if (request.MaxHeight.HasValue)
  1610. {
  1611. if (!videoStream.Height.HasValue || videoStream.Height.Value > request.MaxHeight.Value)
  1612. {
  1613. return false;
  1614. }
  1615. }
  1616. // Video framerate must fall within requested value
  1617. var requestedFramerate = request.MaxFramerate ?? request.Framerate;
  1618. if (requestedFramerate.HasValue)
  1619. {
  1620. var videoFrameRate = videoStream.AverageFrameRate ?? videoStream.RealFrameRate;
  1621. if (!videoFrameRate.HasValue || videoFrameRate.Value > requestedFramerate.Value)
  1622. {
  1623. return false;
  1624. }
  1625. }
  1626. // Video bitrate must fall within requested value
  1627. if (request.VideoBitRate.HasValue)
  1628. {
  1629. if (!videoStream.BitRate.HasValue || videoStream.BitRate.Value > request.VideoBitRate.Value)
  1630. {
  1631. return false;
  1632. }
  1633. }
  1634. if (request.MaxVideoBitDepth.HasValue)
  1635. {
  1636. if (videoStream.BitDepth.HasValue && videoStream.BitDepth.Value > request.MaxVideoBitDepth.Value)
  1637. {
  1638. return false;
  1639. }
  1640. }
  1641. if (request.MaxRefFrames.HasValue)
  1642. {
  1643. if (videoStream.RefFrames.HasValue && videoStream.RefFrames.Value > request.MaxRefFrames.Value)
  1644. {
  1645. return false;
  1646. }
  1647. }
  1648. // If a specific level was requested, the source must match or be less than
  1649. if (!string.IsNullOrEmpty(request.Level))
  1650. {
  1651. double requestLevel;
  1652. if (double.TryParse(request.Level, NumberStyles.Any, UsCulture, out requestLevel))
  1653. {
  1654. if (!videoStream.Level.HasValue)
  1655. {
  1656. //return false;
  1657. }
  1658. if (videoStream.Level.HasValue && videoStream.Level.Value > requestLevel)
  1659. {
  1660. return false;
  1661. }
  1662. }
  1663. }
  1664. return request.EnableAutoStreamCopy;
  1665. }
  1666. private int GetVideoProfileScore(string profile)
  1667. {
  1668. var list = new List<string>
  1669. {
  1670. "Constrained Baseline",
  1671. "Baseline",
  1672. "Extended",
  1673. "Main",
  1674. "High",
  1675. "Progressive High",
  1676. "Constrained High"
  1677. };
  1678. return Array.FindIndex(list.ToArray(), t => string.Equals(t, profile, StringComparison.OrdinalIgnoreCase));
  1679. }
  1680. protected virtual bool CanStreamCopyAudio(StreamState state, List<string> supportedAudioCodecs)
  1681. {
  1682. var request = state.VideoRequest;
  1683. var audioStream = state.AudioStream;
  1684. // Source and target codecs must match
  1685. if (string.IsNullOrEmpty(audioStream.Codec) || !supportedAudioCodecs.Contains(audioStream.Codec, StringComparer.OrdinalIgnoreCase))
  1686. {
  1687. return false;
  1688. }
  1689. // Video bitrate must fall within requested value
  1690. if (request.AudioBitRate.HasValue)
  1691. {
  1692. if (!audioStream.BitRate.HasValue || audioStream.BitRate.Value <= 0)
  1693. {
  1694. return false;
  1695. }
  1696. if (audioStream.BitRate.Value > request.AudioBitRate.Value)
  1697. {
  1698. return false;
  1699. }
  1700. }
  1701. // Channels must fall within requested value
  1702. var channels = request.AudioChannels ?? request.MaxAudioChannels;
  1703. if (channels.HasValue)
  1704. {
  1705. if (!audioStream.Channels.HasValue || audioStream.Channels.Value <= 0)
  1706. {
  1707. return false;
  1708. }
  1709. if (audioStream.Channels.Value > channels.Value)
  1710. {
  1711. return false;
  1712. }
  1713. }
  1714. // Sample rate must fall within requested value
  1715. if (request.AudioSampleRate.HasValue)
  1716. {
  1717. if (!audioStream.SampleRate.HasValue || audioStream.SampleRate.Value <= 0)
  1718. {
  1719. return false;
  1720. }
  1721. if (audioStream.SampleRate.Value > request.AudioSampleRate.Value)
  1722. {
  1723. return false;
  1724. }
  1725. }
  1726. return request.EnableAutoStreamCopy;
  1727. }
  1728. private void ApplyDeviceProfileSettings(StreamState state)
  1729. {
  1730. var headers = new Dictionary<string, string>();
  1731. foreach (var key in Request.Headers.AllKeys)
  1732. {
  1733. headers[key] = Request.Headers[key];
  1734. }
  1735. if (!string.IsNullOrWhiteSpace(state.Request.DeviceProfileId))
  1736. {
  1737. state.DeviceProfile = DlnaManager.GetProfile(state.Request.DeviceProfileId);
  1738. }
  1739. else
  1740. {
  1741. if (!string.IsNullOrWhiteSpace(state.Request.DeviceId))
  1742. {
  1743. var caps = DeviceManager.GetCapabilities(state.Request.DeviceId);
  1744. if (caps != null)
  1745. {
  1746. state.DeviceProfile = caps.DeviceProfile;
  1747. }
  1748. else
  1749. {
  1750. state.DeviceProfile = DlnaManager.GetProfile(headers);
  1751. }
  1752. }
  1753. }
  1754. var profile = state.DeviceProfile;
  1755. if (profile == null)
  1756. {
  1757. // Don't use settings from the default profile.
  1758. // Only use a specific profile if it was requested.
  1759. return;
  1760. }
  1761. var audioCodec = state.ActualOutputAudioCodec;
  1762. var videoCodec = state.ActualOutputVideoCodec;
  1763. var mediaProfile = state.VideoRequest == null ?
  1764. profile.GetAudioMediaProfile(state.OutputContainer, audioCodec, state.OutputAudioChannels, state.OutputAudioBitrate) :
  1765. profile.GetVideoMediaProfile(state.OutputContainer,
  1766. audioCodec,
  1767. videoCodec,
  1768. state.OutputWidth,
  1769. state.OutputHeight,
  1770. state.TargetVideoBitDepth,
  1771. state.OutputVideoBitrate,
  1772. state.TargetVideoProfile,
  1773. state.TargetVideoLevel,
  1774. state.TargetFramerate,
  1775. state.TargetPacketLength,
  1776. state.TargetTimestamp,
  1777. state.IsTargetAnamorphic,
  1778. state.TargetRefFrames,
  1779. state.TargetVideoStreamCount,
  1780. state.TargetAudioStreamCount,
  1781. state.TargetVideoCodecTag);
  1782. if (mediaProfile != null)
  1783. {
  1784. state.MimeType = mediaProfile.MimeType;
  1785. }
  1786. if (!state.Request.Static)
  1787. {
  1788. var transcodingProfile = state.VideoRequest == null ?
  1789. profile.GetAudioTranscodingProfile(state.OutputContainer, audioCodec) :
  1790. profile.GetVideoTranscodingProfile(state.OutputContainer, audioCodec, videoCodec);
  1791. if (transcodingProfile != null)
  1792. {
  1793. state.EstimateContentLength = transcodingProfile.EstimateContentLength;
  1794. state.EnableMpegtsM2TsMode = transcodingProfile.EnableMpegtsM2TsMode;
  1795. state.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
  1796. if (state.VideoRequest != null)
  1797. {
  1798. state.VideoRequest.CopyTimestamps = transcodingProfile.CopyTimestamps;
  1799. state.VideoRequest.ForceLiveStream = transcodingProfile.ForceLiveStream;
  1800. }
  1801. }
  1802. }
  1803. }
  1804. /// <summary>
  1805. /// Adds the dlna headers.
  1806. /// </summary>
  1807. /// <param name="state">The state.</param>
  1808. /// <param name="responseHeaders">The response headers.</param>
  1809. /// <param name="isStaticallyStreamed">if set to <c>true</c> [is statically streamed].</param>
  1810. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1811. protected void AddDlnaHeaders(StreamState state, IDictionary<string, string> responseHeaders, bool isStaticallyStreamed)
  1812. {
  1813. var profile = state.DeviceProfile;
  1814. var transferMode = GetHeader("transferMode.dlna.org");
  1815. responseHeaders["transferMode.dlna.org"] = string.IsNullOrEmpty(transferMode) ? "Streaming" : transferMode;
  1816. responseHeaders["realTimeInfo.dlna.org"] = "DLNA.ORG_TLAG=*";
  1817. if (string.Equals(GetHeader("getMediaInfo.sec"), "1", StringComparison.OrdinalIgnoreCase))
  1818. {
  1819. if (state.RunTimeTicks.HasValue)
  1820. {
  1821. var ms = TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalMilliseconds;
  1822. responseHeaders["MediaInfo.sec"] = string.Format("SEC_Duration={0};", Convert.ToInt32(ms).ToString(CultureInfo.InvariantCulture));
  1823. }
  1824. }
  1825. if (state.RunTimeTicks.HasValue && !isStaticallyStreamed && profile != null)
  1826. {
  1827. AddTimeSeekResponseHeaders(state, responseHeaders);
  1828. }
  1829. if (profile == null)
  1830. {
  1831. profile = DlnaManager.GetDefaultProfile();
  1832. }
  1833. var audioCodec = state.ActualOutputAudioCodec;
  1834. if (state.VideoRequest == null)
  1835. {
  1836. responseHeaders["contentFeatures.dlna.org"] = new ContentFeatureBuilder(profile)
  1837. .BuildAudioHeader(
  1838. state.OutputContainer,
  1839. audioCodec,
  1840. state.OutputAudioBitrate,
  1841. state.OutputAudioSampleRate,
  1842. state.OutputAudioChannels,
  1843. isStaticallyStreamed,
  1844. state.RunTimeTicks,
  1845. state.TranscodeSeekInfo
  1846. );
  1847. }
  1848. else
  1849. {
  1850. var videoCodec = state.ActualOutputVideoCodec;
  1851. responseHeaders["contentFeatures.dlna.org"] = new ContentFeatureBuilder(profile)
  1852. .BuildVideoHeader(
  1853. state.OutputContainer,
  1854. videoCodec,
  1855. audioCodec,
  1856. state.OutputWidth,
  1857. state.OutputHeight,
  1858. state.TargetVideoBitDepth,
  1859. state.OutputVideoBitrate,
  1860. state.TargetTimestamp,
  1861. isStaticallyStreamed,
  1862. state.RunTimeTicks,
  1863. state.TargetVideoProfile,
  1864. state.TargetVideoLevel,
  1865. state.TargetFramerate,
  1866. state.TargetPacketLength,
  1867. state.TranscodeSeekInfo,
  1868. state.IsTargetAnamorphic,
  1869. state.TargetRefFrames,
  1870. state.TargetVideoStreamCount,
  1871. state.TargetAudioStreamCount,
  1872. state.TargetVideoCodecTag
  1873. ).FirstOrDefault() ?? string.Empty;
  1874. }
  1875. foreach (var item in responseHeaders)
  1876. {
  1877. Request.Response.AddHeader(item.Key, item.Value);
  1878. }
  1879. }
  1880. private void AddTimeSeekResponseHeaders(StreamState state, IDictionary<string, string> responseHeaders)
  1881. {
  1882. var runtimeSeconds = TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds.ToString(UsCulture);
  1883. var startSeconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds.ToString(UsCulture);
  1884. responseHeaders["TimeSeekRange.dlna.org"] = string.Format("npt={0}-{1}/{1}", startSeconds, runtimeSeconds);
  1885. responseHeaders["X-AvailableSeekRange"] = string.Format("1 npt={0}-{1}", startSeconds, runtimeSeconds);
  1886. }
  1887. /// <summary>
  1888. /// Enforces the resolution limit.
  1889. /// </summary>
  1890. /// <param name="state">The state.</param>
  1891. /// <param name="videoRequest">The video request.</param>
  1892. private void EnforceResolutionLimit(StreamState state, VideoStreamRequest videoRequest)
  1893. {
  1894. // Switch the incoming params to be ceilings rather than fixed values
  1895. videoRequest.MaxWidth = videoRequest.MaxWidth ?? videoRequest.Width;
  1896. videoRequest.MaxHeight = videoRequest.MaxHeight ?? videoRequest.Height;
  1897. videoRequest.Width = null;
  1898. videoRequest.Height = null;
  1899. }
  1900. protected string GetInputModifier(StreamState state, bool genPts = true)
  1901. {
  1902. var inputModifier = string.Empty;
  1903. var probeSize = GetProbeSizeArgument(state);
  1904. inputModifier += " " + probeSize;
  1905. inputModifier = inputModifier.Trim();
  1906. var userAgentParam = GetUserAgentParam(state);
  1907. if (!string.IsNullOrWhiteSpace(userAgentParam))
  1908. {
  1909. inputModifier += " " + userAgentParam;
  1910. }
  1911. inputModifier = inputModifier.Trim();
  1912. inputModifier += " " + GetFastSeekCommandLineParameter(state.Request);
  1913. inputModifier = inputModifier.Trim();
  1914. if (state.VideoRequest != null && genPts)
  1915. {
  1916. inputModifier += " -fflags +genpts";
  1917. }
  1918. if (!string.IsNullOrEmpty(state.InputAudioSync))
  1919. {
  1920. inputModifier += " -async " + state.InputAudioSync;
  1921. }
  1922. if (!string.IsNullOrEmpty(state.InputVideoSync))
  1923. {
  1924. inputModifier += " -vsync " + state.InputVideoSync;
  1925. }
  1926. if (state.ReadInputAtNativeFramerate)
  1927. {
  1928. inputModifier += " -re";
  1929. }
  1930. var videoDecoder = GetVideoDecoder(state);
  1931. if (!string.IsNullOrWhiteSpace(videoDecoder))
  1932. {
  1933. inputModifier += " " + videoDecoder;
  1934. }
  1935. if (state.VideoRequest != null)
  1936. {
  1937. // Important: If this is ever re-enabled, make sure not to use it with wtv because it breaks seeking
  1938. if (string.Equals(state.OutputContainer, "mkv", StringComparison.OrdinalIgnoreCase) && state.VideoRequest.CopyTimestamps)
  1939. {
  1940. //inputModifier += " -noaccurate_seek";
  1941. }
  1942. }
  1943. return inputModifier;
  1944. }
  1945. /// <summary>
  1946. /// Infers the audio codec based on the url
  1947. /// </summary>
  1948. /// <param name="url">The URL.</param>
  1949. /// <returns>System.Nullable{AudioCodecs}.</returns>
  1950. private string InferAudioCodec(string url)
  1951. {
  1952. var ext = Path.GetExtension(url);
  1953. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  1954. {
  1955. return "mp3";
  1956. }
  1957. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  1958. {
  1959. return "aac";
  1960. }
  1961. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  1962. {
  1963. return "wma";
  1964. }
  1965. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  1966. {
  1967. return "vorbis";
  1968. }
  1969. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  1970. {
  1971. return "vorbis";
  1972. }
  1973. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  1974. {
  1975. return "vorbis";
  1976. }
  1977. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  1978. {
  1979. return "vorbis";
  1980. }
  1981. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  1982. {
  1983. return "vorbis";
  1984. }
  1985. return "copy";
  1986. }
  1987. /// <summary>
  1988. /// Infers the video codec.
  1989. /// </summary>
  1990. /// <param name="url">The URL.</param>
  1991. /// <returns>System.Nullable{VideoCodecs}.</returns>
  1992. private string InferVideoCodec(string url)
  1993. {
  1994. var ext = Path.GetExtension(url);
  1995. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  1996. {
  1997. return "wmv";
  1998. }
  1999. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  2000. {
  2001. return "vpx";
  2002. }
  2003. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  2004. {
  2005. return "theora";
  2006. }
  2007. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  2008. {
  2009. return "h264";
  2010. }
  2011. return "copy";
  2012. }
  2013. }
  2014. }