VideoHandler.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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. if (base.RequiresConversion())
  44. {
  45. return true;
  46. }
  47. // See if the video requires conversion
  48. if (RequiresVideoConversion())
  49. {
  50. return true;
  51. }
  52. // See if the audio requires conversion
  53. AudioStream audioStream = (LibraryItem.AudioStreams ?? new List<AudioStream>()).FirstOrDefault();
  54. if (audioStream != null)
  55. {
  56. if (RequiresAudioConversion(audioStream))
  57. {
  58. return true;
  59. }
  60. }
  61. // Yay
  62. return false;
  63. }
  64. /// <summary>
  65. /// Translates the output file extension to the format param that follows "-f" on the ffmpeg command line
  66. /// </summary>
  67. private string GetFfMpegOutputFormat(VideoOutputFormats outputFormat)
  68. {
  69. if (outputFormat == VideoOutputFormats.Mkv)
  70. {
  71. return "matroska";
  72. }
  73. if (outputFormat == VideoOutputFormats.Ts)
  74. {
  75. return "mpegts";
  76. }
  77. if (outputFormat == VideoOutputFormats.Ogv)
  78. {
  79. return "ogg";
  80. }
  81. return outputFormat.ToString().ToLower();
  82. }
  83. /// <summary>
  84. /// Creates arguments to pass to ffmpeg
  85. /// </summary>
  86. protected override string GetCommandLineArguments()
  87. {
  88. VideoOutputFormats outputFormat = GetConversionOutputFormat();
  89. return string.Format("-i \"{0}\" -threads 0 {1} {2} -f {3} -",
  90. LibraryItem.Path,
  91. GetVideoArguments(outputFormat),
  92. GetAudioArguments(outputFormat),
  93. GetFfMpegOutputFormat(outputFormat)
  94. );
  95. }
  96. /// <summary>
  97. /// Gets video arguments to pass to ffmpeg
  98. /// </summary>
  99. private string GetVideoArguments(VideoOutputFormats outputFormat)
  100. {
  101. // Get the output codec name
  102. string codec = GetVideoCodec(outputFormat);
  103. string args = "-vcodec " + codec;
  104. // If we're encoding video, add additional params
  105. if (!codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  106. {
  107. // Add resolution params, if specified
  108. if (Width.HasValue || Height.HasValue || MaxHeight.HasValue || MaxWidth.HasValue)
  109. {
  110. Size size = DrawingUtils.Resize(LibraryItem.Width, LibraryItem.Height, Width, Height, MaxWidth, MaxHeight);
  111. args += string.Format(" -s {0}x{1}", size.Width, size.Height);
  112. }
  113. }
  114. return args;
  115. }
  116. /// <summary>
  117. /// Gets audio arguments to pass to ffmpeg
  118. /// </summary>
  119. private string GetAudioArguments(VideoOutputFormats outputFormat)
  120. {
  121. AudioStream audioStream = (LibraryItem.AudioStreams ?? new List<AudioStream>()).FirstOrDefault();
  122. // If the video doesn't have an audio stream, return empty
  123. if (audioStream == null)
  124. {
  125. return string.Empty;
  126. }
  127. // Get the output codec name
  128. string codec = GetAudioCodec(audioStream, outputFormat);
  129. string args = "-acodec " + codec;
  130. // If we're encoding audio, add additional params
  131. if (!codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  132. {
  133. // Add the number of audio channels
  134. int? channels = GetNumAudioChannelsParam(codec, audioStream.Channels);
  135. if (channels.HasValue)
  136. {
  137. args += " -ac " + channels.Value;
  138. }
  139. // Add the audio sample rate
  140. int? sampleRate = GetSampleRateParam(audioStream.SampleRate);
  141. if (sampleRate.HasValue)
  142. {
  143. args += " -ar " + sampleRate.Value;
  144. }
  145. }
  146. return args;
  147. }
  148. /// <summary>
  149. /// Gets the name of the output video codec
  150. /// </summary>
  151. private string GetVideoCodec(VideoOutputFormats outputFormat)
  152. {
  153. // Some output containers require specific codecs
  154. if (outputFormat == VideoOutputFormats.Webm)
  155. {
  156. // Per webm specification, it must be vpx
  157. return "libvpx";
  158. }
  159. if (outputFormat == VideoOutputFormats.Asf)
  160. {
  161. return "wmv2";
  162. }
  163. if (outputFormat == VideoOutputFormats.Wmv)
  164. {
  165. return "wmv2";
  166. }
  167. if (outputFormat == VideoOutputFormats.Ogv)
  168. {
  169. return "libtheora";
  170. }
  171. // Skip encoding when possible
  172. if (!RequiresVideoConversion())
  173. {
  174. return "copy";
  175. }
  176. return "libx264";
  177. }
  178. /// <summary>
  179. /// Gets the name of the output audio codec
  180. /// </summary>
  181. private string GetAudioCodec(AudioStream audioStream, VideoOutputFormats outputFormat)
  182. {
  183. // Some output containers require specific codecs
  184. if (outputFormat == VideoOutputFormats.Webm)
  185. {
  186. // Per webm specification, it must be vorbis
  187. return "libvorbis";
  188. }
  189. if (outputFormat == VideoOutputFormats.Asf)
  190. {
  191. return "wmav2";
  192. }
  193. if (outputFormat == VideoOutputFormats.Wmv)
  194. {
  195. return "wmav2";
  196. }
  197. if (outputFormat == VideoOutputFormats.Ogv)
  198. {
  199. return "libvorbis";
  200. }
  201. // Skip encoding when possible
  202. if (!RequiresAudioConversion(audioStream))
  203. {
  204. return "copy";
  205. }
  206. return "libvo_aacenc";
  207. }
  208. /// <summary>
  209. /// Gets the number of audio channels to specify on the command line
  210. /// </summary>
  211. private int? GetNumAudioChannelsParam(string audioCodec, int libraryItemChannels)
  212. {
  213. if (libraryItemChannels > 2)
  214. {
  215. if (audioCodec.Equals("libvo_aacenc"))
  216. {
  217. // libvo_aacenc currently only supports two channel output
  218. return 2;
  219. }
  220. if (audioCodec.Equals("wmav2"))
  221. {
  222. // wmav2 currently only supports two channel output
  223. return 2;
  224. }
  225. }
  226. return GetNumAudioChannelsParam(libraryItemChannels);
  227. }
  228. /// <summary>
  229. /// Determines if the video stream requires encoding
  230. /// </summary>
  231. private bool RequiresVideoConversion()
  232. {
  233. // Check dimensions
  234. // If a specific width is required, validate that
  235. if (Width.HasValue)
  236. {
  237. if (Width.Value != LibraryItem.Width)
  238. {
  239. return true;
  240. }
  241. }
  242. // If a specific height is required, validate that
  243. if (Height.HasValue)
  244. {
  245. if (Height.Value != LibraryItem.Height)
  246. {
  247. return true;
  248. }
  249. }
  250. // If a max width is required, validate that
  251. if (MaxWidth.HasValue)
  252. {
  253. if (MaxWidth.Value < LibraryItem.Width)
  254. {
  255. return true;
  256. }
  257. }
  258. // If a max height is required, validate that
  259. if (MaxHeight.HasValue)
  260. {
  261. if (MaxHeight.Value < LibraryItem.Height)
  262. {
  263. return true;
  264. }
  265. }
  266. // If the codec is already h264, don't encode
  267. if (LibraryItem.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 || LibraryItem.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1)
  268. {
  269. return false;
  270. }
  271. return false;
  272. }
  273. /// <summary>
  274. /// Determines if the audio stream requires encoding
  275. /// </summary>
  276. private bool RequiresAudioConversion(AudioStream audio)
  277. {
  278. // If the input stream has more audio channels than the client can handle, we need to encode
  279. if (AudioChannels.HasValue)
  280. {
  281. if (audio.Channels > AudioChannels.Value)
  282. {
  283. return true;
  284. }
  285. }
  286. // Aac, ac-3 and mp3 are all pretty much universally supported. No need to encode them
  287. if (audio.Codec.IndexOf("aac", StringComparison.OrdinalIgnoreCase) != -1)
  288. {
  289. return false;
  290. }
  291. if (audio.Codec.IndexOf("ac-3", StringComparison.OrdinalIgnoreCase) != -1 || audio.Codec.IndexOf("ac3", StringComparison.OrdinalIgnoreCase) != -1)
  292. {
  293. return false;
  294. }
  295. if (audio.Codec.IndexOf("mpeg", StringComparison.OrdinalIgnoreCase) != -1 || audio.Codec.IndexOf("mp3", StringComparison.OrdinalIgnoreCase) != -1)
  296. {
  297. return false;
  298. }
  299. return true;
  300. }
  301. /// <summary>
  302. /// Gets the fixed output video height, in pixels
  303. /// </summary>
  304. private int? Height
  305. {
  306. get
  307. {
  308. string val = QueryString["height"];
  309. if (string.IsNullOrEmpty(val))
  310. {
  311. return null;
  312. }
  313. return int.Parse(val);
  314. }
  315. }
  316. /// <summary>
  317. /// Gets the fixed output video width, in pixels
  318. /// </summary>
  319. private int? Width
  320. {
  321. get
  322. {
  323. string val = QueryString["width"];
  324. if (string.IsNullOrEmpty(val))
  325. {
  326. return null;
  327. }
  328. return int.Parse(val);
  329. }
  330. }
  331. /// <summary>
  332. /// Gets the maximum output video height, in pixels
  333. /// </summary>
  334. private int? MaxHeight
  335. {
  336. get
  337. {
  338. string val = QueryString["maxheight"];
  339. if (string.IsNullOrEmpty(val))
  340. {
  341. return null;
  342. }
  343. return int.Parse(val);
  344. }
  345. }
  346. /// <summary>
  347. /// Gets the maximum output video width, in pixels
  348. /// </summary>
  349. private int? MaxWidth
  350. {
  351. get
  352. {
  353. string val = QueryString["maxwidth"];
  354. if (string.IsNullOrEmpty(val))
  355. {
  356. return null;
  357. }
  358. return int.Parse(val);
  359. }
  360. }
  361. }
  362. }