VideoHandler.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. using MediaBrowser.Common.Drawing;
  2. using MediaBrowser.Common.Net.Handlers;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Model.DTO;
  5. using MediaBrowser.Model.Entities;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.ComponentModel.Composition;
  9. using System.Drawing;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Net;
  13. namespace MediaBrowser.Api.HttpHandlers
  14. {
  15. /// <summary>
  16. /// Supported output formats: mkv,m4v,mp4,asf,wmv,mov,webm,ogv,3gp,avi,ts,flv
  17. /// </summary>
  18. [Export(typeof(BaseHandler))]
  19. class VideoHandler : BaseMediaHandler<Video, VideoOutputFormats>
  20. {
  21. public override bool HandlesRequest(HttpListenerRequest request)
  22. {
  23. return ApiService.IsApiUrlMatch("video", request);
  24. }
  25. /// <summary>
  26. /// We can output these files directly, but we can't encode them
  27. /// </summary>
  28. protected override IEnumerable<VideoOutputFormats> UnsupportedOutputEncodingFormats
  29. {
  30. get
  31. {
  32. // mp4, 3gp, mov - muxer does not support non-seekable output
  33. // avi, mov, mkv, m4v - can't stream these when encoding. the player will try to download them completely before starting playback.
  34. // wmv - can't seem to figure out the output format name
  35. return new VideoOutputFormats[] { VideoOutputFormats.Mp4, VideoOutputFormats.ThreeGP, VideoOutputFormats.M4v, VideoOutputFormats.Mkv, VideoOutputFormats.Avi, VideoOutputFormats.Mov, VideoOutputFormats.Wmv };
  36. }
  37. }
  38. /// <summary>
  39. /// Determines whether or not we can just output the original file directly
  40. /// </summary>
  41. protected override bool RequiresConversion()
  42. {
  43. string currentFormat = Path.GetExtension(LibraryItem.Path).Replace(".", string.Empty);
  44. // For now we won't allow these to pass through.
  45. // Later we'll add some intelligence to allow it when possible
  46. if (currentFormat.Equals("mp4", StringComparison.OrdinalIgnoreCase) || currentFormat.Equals("mkv", StringComparison.OrdinalIgnoreCase) || currentFormat.Equals("m4v", StringComparison.OrdinalIgnoreCase))
  47. {
  48. return true;
  49. }
  50. if (base.RequiresConversion())
  51. {
  52. return true;
  53. }
  54. // See if the video requires conversion
  55. if (RequiresVideoConversion())
  56. {
  57. return true;
  58. }
  59. // See if the audio requires conversion
  60. AudioStream audioStream = (LibraryItem.AudioStreams ?? new List<AudioStream>()).FirstOrDefault();
  61. if (audioStream != null)
  62. {
  63. if (RequiresAudioConversion(audioStream))
  64. {
  65. return true;
  66. }
  67. }
  68. // Yay
  69. return false;
  70. }
  71. /// <summary>
  72. /// Translates the output file extension to the format param that follows "-f" on the ffmpeg command line
  73. /// </summary>
  74. private string GetFFMpegOutputFormat(VideoOutputFormats outputFormat)
  75. {
  76. if (outputFormat == VideoOutputFormats.Mkv)
  77. {
  78. return "matroska";
  79. }
  80. else if (outputFormat == VideoOutputFormats.Ts)
  81. {
  82. return "mpegts";
  83. }
  84. else if (outputFormat == VideoOutputFormats.Ogv)
  85. {
  86. return "ogg";
  87. }
  88. return outputFormat.ToString().ToLower();
  89. }
  90. /// <summary>
  91. /// Creates arguments to pass to ffmpeg
  92. /// </summary>
  93. protected override string GetCommandLineArguments()
  94. {
  95. List<string> audioTranscodeParams = new List<string>();
  96. VideoOutputFormats outputFormat = GetConversionOutputFormat();
  97. return string.Format("-i \"{0}\" -threads 0 {1} {2} -f {3} -",
  98. LibraryItem.Path,
  99. GetVideoArguments(outputFormat),
  100. GetAudioArguments(outputFormat),
  101. GetFFMpegOutputFormat(outputFormat)
  102. );
  103. }
  104. /// <summary>
  105. /// Gets video arguments to pass to ffmpeg
  106. /// </summary>
  107. private string GetVideoArguments(VideoOutputFormats outputFormat)
  108. {
  109. // Get the output codec name
  110. string codec = GetVideoCodec(outputFormat);
  111. string args = "-vcodec " + codec;
  112. // If we're encoding video, add additional params
  113. if (!codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  114. {
  115. // Add resolution params, if specified
  116. if (Width.HasValue || Height.HasValue || MaxHeight.HasValue || MaxWidth.HasValue)
  117. {
  118. Size size = DrawingUtils.Resize(LibraryItem.Width, LibraryItem.Height, Width, Height, MaxWidth, MaxHeight);
  119. args += string.Format(" -s {0}x{1}", size.Width, size.Height);
  120. }
  121. }
  122. return args;
  123. }
  124. /// <summary>
  125. /// Gets audio arguments to pass to ffmpeg
  126. /// </summary>
  127. private string GetAudioArguments(VideoOutputFormats outputFormat)
  128. {
  129. AudioStream audioStream = (LibraryItem.AudioStreams ?? new List<AudioStream>()).FirstOrDefault();
  130. // If the video doesn't have an audio stream, return empty
  131. if (audioStream == null)
  132. {
  133. return string.Empty;
  134. }
  135. // Get the output codec name
  136. string codec = GetAudioCodec(audioStream, outputFormat);
  137. string args = "-acodec " + codec;
  138. // If we're encoding audio, add additional params
  139. if (!codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  140. {
  141. // Add the number of audio channels
  142. int? channels = GetNumAudioChannelsParam(codec, audioStream.Channels);
  143. if (channels.HasValue)
  144. {
  145. args += " -ac " + channels.Value;
  146. }
  147. // Add the audio sample rate
  148. int? sampleRate = GetSampleRateParam(audioStream.SampleRate);
  149. if (sampleRate.HasValue)
  150. {
  151. args += " -ar " + sampleRate.Value;
  152. }
  153. }
  154. return args;
  155. }
  156. /// <summary>
  157. /// Gets the name of the output video codec
  158. /// </summary>
  159. private string GetVideoCodec(VideoOutputFormats outputFormat)
  160. {
  161. // Some output containers require specific codecs
  162. if (outputFormat == VideoOutputFormats.Webm)
  163. {
  164. // Per webm specification, it must be vpx
  165. return "libvpx";
  166. }
  167. else if (outputFormat == VideoOutputFormats.Asf)
  168. {
  169. return "wmv2";
  170. }
  171. else if (outputFormat == VideoOutputFormats.Wmv)
  172. {
  173. return "wmv2";
  174. }
  175. else if (outputFormat == VideoOutputFormats.Ogv)
  176. {
  177. return "libtheora";
  178. }
  179. // Skip encoding when possible
  180. if (!RequiresVideoConversion())
  181. {
  182. return "copy";
  183. }
  184. return "libx264";
  185. }
  186. /// <summary>
  187. /// Gets the name of the output audio codec
  188. /// </summary>
  189. private string GetAudioCodec(AudioStream audioStream, VideoOutputFormats outputFormat)
  190. {
  191. // Some output containers require specific codecs
  192. if (outputFormat == VideoOutputFormats.Webm)
  193. {
  194. // Per webm specification, it must be vorbis
  195. return "libvorbis";
  196. }
  197. else if (outputFormat == VideoOutputFormats.Asf)
  198. {
  199. return "wmav2";
  200. }
  201. else if (outputFormat == VideoOutputFormats.Wmv)
  202. {
  203. return "wmav2";
  204. }
  205. else if (outputFormat == VideoOutputFormats.Ogv)
  206. {
  207. return "libvorbis";
  208. }
  209. // Skip encoding when possible
  210. if (!RequiresAudioConversion(audioStream))
  211. {
  212. return "copy";
  213. }
  214. return "libvo_aacenc";
  215. }
  216. /// <summary>
  217. /// Gets the number of audio channels to specify on the command line
  218. /// </summary>
  219. private int? GetNumAudioChannelsParam(string audioCodec, int libraryItemChannels)
  220. {
  221. if (libraryItemChannels > 2)
  222. {
  223. if (audioCodec.Equals("libvo_aacenc"))
  224. {
  225. // libvo_aacenc currently only supports two channel output
  226. return 2;
  227. }
  228. else if (audioCodec.Equals("wmav2"))
  229. {
  230. // wmav2 currently only supports two channel output
  231. return 2;
  232. }
  233. }
  234. return GetNumAudioChannelsParam(libraryItemChannels);
  235. }
  236. /// <summary>
  237. /// Determines if the video stream requires encoding
  238. /// </summary>
  239. private bool RequiresVideoConversion()
  240. {
  241. // Check dimensions
  242. // If a specific width is required, validate that
  243. if (Width.HasValue)
  244. {
  245. if (Width.Value != LibraryItem.Width)
  246. {
  247. return true;
  248. }
  249. }
  250. // If a specific height is required, validate that
  251. if (Height.HasValue)
  252. {
  253. if (Height.Value != LibraryItem.Height)
  254. {
  255. return true;
  256. }
  257. }
  258. // If a max width is required, validate that
  259. if (MaxWidth.HasValue)
  260. {
  261. if (MaxWidth.Value < LibraryItem.Width)
  262. {
  263. return true;
  264. }
  265. }
  266. // If a max height is required, validate that
  267. if (MaxHeight.HasValue)
  268. {
  269. if (MaxHeight.Value < LibraryItem.Height)
  270. {
  271. return true;
  272. }
  273. }
  274. // If the codec is already h264, don't encode
  275. if (LibraryItem.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 || LibraryItem.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1)
  276. {
  277. return false;
  278. }
  279. return false;
  280. }
  281. /// <summary>
  282. /// Determines if the audio stream requires encoding
  283. /// </summary>
  284. private bool RequiresAudioConversion(AudioStream audio)
  285. {
  286. // If the input stream has more audio channels than the client can handle, we need to encode
  287. if (AudioChannels.HasValue)
  288. {
  289. if (audio.Channels > AudioChannels.Value)
  290. {
  291. return true;
  292. }
  293. }
  294. // Aac, ac-3 and mp3 are all pretty much universally supported. No need to encode them
  295. if (audio.Codec.IndexOf("aac", StringComparison.OrdinalIgnoreCase) != -1)
  296. {
  297. return false;
  298. }
  299. if (audio.Codec.IndexOf("ac-3", StringComparison.OrdinalIgnoreCase) != -1 || audio.Codec.IndexOf("ac3", StringComparison.OrdinalIgnoreCase) != -1)
  300. {
  301. return false;
  302. }
  303. if (audio.Codec.IndexOf("mpeg", StringComparison.OrdinalIgnoreCase) != -1 || audio.Codec.IndexOf("mp3", StringComparison.OrdinalIgnoreCase) != -1)
  304. {
  305. return false;
  306. }
  307. return true;
  308. }
  309. /// <summary>
  310. /// Gets the fixed output video height, in pixels
  311. /// </summary>
  312. private int? Height
  313. {
  314. get
  315. {
  316. string val = QueryString["height"];
  317. if (string.IsNullOrEmpty(val))
  318. {
  319. return null;
  320. }
  321. return int.Parse(val);
  322. }
  323. }
  324. /// <summary>
  325. /// Gets the fixed output video width, in pixels
  326. /// </summary>
  327. private int? Width
  328. {
  329. get
  330. {
  331. string val = QueryString["width"];
  332. if (string.IsNullOrEmpty(val))
  333. {
  334. return null;
  335. }
  336. return int.Parse(val);
  337. }
  338. }
  339. /// <summary>
  340. /// Gets the maximum output video height, in pixels
  341. /// </summary>
  342. private int? MaxHeight
  343. {
  344. get
  345. {
  346. string val = QueryString["maxheight"];
  347. if (string.IsNullOrEmpty(val))
  348. {
  349. return null;
  350. }
  351. return int.Parse(val);
  352. }
  353. }
  354. /// <summary>
  355. /// Gets the maximum output video width, in pixels
  356. /// </summary>
  357. private int? MaxWidth
  358. {
  359. get
  360. {
  361. string val = QueryString["maxwidth"];
  362. if (string.IsNullOrEmpty(val))
  363. {
  364. return null;
  365. }
  366. return int.Parse(val);
  367. }
  368. }
  369. }
  370. }