BaseProgressiveStreamingService.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. using System.Net;
  2. using System.Net.Cache;
  3. using System.Net.Http;
  4. using MediaBrowser.Api.Images;
  5. using MediaBrowser.Common.IO;
  6. using MediaBrowser.Common.MediaInfo;
  7. using MediaBrowser.Common.Net;
  8. using MediaBrowser.Controller;
  9. using MediaBrowser.Controller.Entities;
  10. using MediaBrowser.Controller.Entities.Audio;
  11. using MediaBrowser.Controller.Library;
  12. using MediaBrowser.Controller.Persistence;
  13. using MediaBrowser.Model.Dto;
  14. using MediaBrowser.Model.Entities;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.IO;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.Api.Playback.Progressive
  20. {
  21. /// <summary>
  22. /// Class BaseProgressiveStreamingService
  23. /// </summary>
  24. public abstract class BaseProgressiveStreamingService : BaseStreamingService
  25. {
  26. protected readonly IItemRepository ItemRepository;
  27. protected BaseProgressiveStreamingService(IServerApplicationPaths appPaths, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IItemRepository itemRepository) :
  28. base(appPaths, userManager, libraryManager, isoManager, mediaEncoder)
  29. {
  30. ItemRepository = itemRepository;
  31. }
  32. /// <summary>
  33. /// Gets the output file extension.
  34. /// </summary>
  35. /// <param name="state">The state.</param>
  36. /// <returns>System.String.</returns>
  37. protected override string GetOutputFileExtension(StreamState state)
  38. {
  39. var ext = base.GetOutputFileExtension(state);
  40. if (!string.IsNullOrEmpty(ext))
  41. {
  42. return ext;
  43. }
  44. var videoRequest = state.Request as VideoStreamRequest;
  45. // Try to infer based on the desired video codec
  46. if (videoRequest != null && videoRequest.VideoCodec.HasValue)
  47. {
  48. var video = state.Item as Video;
  49. if (video != null)
  50. {
  51. switch (videoRequest.VideoCodec.Value)
  52. {
  53. case VideoCodecs.H264:
  54. return ".ts";
  55. case VideoCodecs.Theora:
  56. return ".ogv";
  57. case VideoCodecs.Vpx:
  58. return ".webm";
  59. case VideoCodecs.Wmv:
  60. return ".asf";
  61. }
  62. }
  63. }
  64. // Try to infer based on the desired audio codec
  65. if (state.Request.AudioCodec.HasValue)
  66. {
  67. var audio = state.Item as Audio;
  68. if (audio != null)
  69. {
  70. switch (state.Request.AudioCodec.Value)
  71. {
  72. case AudioCodecs.Aac:
  73. return ".aac";
  74. case AudioCodecs.Mp3:
  75. return ".mp3";
  76. case AudioCodecs.Vorbis:
  77. return ".ogg";
  78. case AudioCodecs.Wma:
  79. return ".wma";
  80. }
  81. }
  82. }
  83. return null;
  84. }
  85. /// <summary>
  86. /// Adds the dlna headers.
  87. /// </summary>
  88. /// <param name="state">The state.</param>
  89. /// <param name="responseHeaders">The response headers.</param>
  90. /// <param name="isStaticallyStreamed">if set to <c>true</c> [is statically streamed].</param>
  91. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  92. private void AddDlnaHeaders(StreamState state, IDictionary<string, string> responseHeaders, bool isStaticallyStreamed)
  93. {
  94. var timeSeek = RequestContext.GetHeader("TimeSeekRange.dlna.org");
  95. if (!string.IsNullOrEmpty(timeSeek))
  96. {
  97. ResultFactory.ThrowError(406, "Time seek not supported during encoding.", responseHeaders);
  98. return;
  99. }
  100. var transferMode = RequestContext.GetHeader("transferMode.dlna.org");
  101. responseHeaders["transferMode.dlna.org"] = string.IsNullOrEmpty(transferMode) ? "Streaming" : transferMode;
  102. var contentFeatures = string.Empty;
  103. var extension = GetOutputFileExtension(state);
  104. // first bit means Time based seek supported, second byte range seek supported (not sure about the order now), so 01 = only byte seek, 10 = time based, 11 = both, 00 = none
  105. var orgOp = isStaticallyStreamed ? ";DLNA.ORG_OP=01" : ";DLNA.ORG_OP=00";
  106. // 0 = native, 1 = transcoded
  107. var orgCi = isStaticallyStreamed ? ";DLNA.ORG_CI=0" : ";DLNA.ORG_CI=1";
  108. const string dlnaflags = ";DLNA.ORG_FLAGS=01500000000000000000000000000000";
  109. if (string.Equals(extension, ".mp3", StringComparison.OrdinalIgnoreCase))
  110. {
  111. contentFeatures = "DLNA.ORG_PN=MP3";
  112. }
  113. else if (string.Equals(extension, ".aac", StringComparison.OrdinalIgnoreCase))
  114. {
  115. contentFeatures = "DLNA.ORG_PN=AAC_ISO";
  116. }
  117. else if (string.Equals(extension, ".wma", StringComparison.OrdinalIgnoreCase))
  118. {
  119. contentFeatures = "DLNA.ORG_PN=WMABASE";
  120. }
  121. else if (string.Equals(extension, ".avi", StringComparison.OrdinalIgnoreCase))
  122. {
  123. contentFeatures = "DLNA.ORG_PN=AVI";
  124. }
  125. else if (string.Equals(extension, ".mp4", StringComparison.OrdinalIgnoreCase))
  126. {
  127. contentFeatures = "DLNA.ORG_PN=MPEG4_P2_SP_AAC";
  128. }
  129. else if (string.Equals(extension, ".mpeg", StringComparison.OrdinalIgnoreCase))
  130. {
  131. contentFeatures = "DLNA.ORG_PN=MPEG_PS_PAL";
  132. }
  133. else if (string.Equals(extension, ".wmv", StringComparison.OrdinalIgnoreCase))
  134. {
  135. contentFeatures = "DLNA.ORG_PN=WMVHIGH_BASE";
  136. }
  137. else if (string.Equals(extension, ".asf", StringComparison.OrdinalIgnoreCase))
  138. {
  139. // ??
  140. contentFeatures = "DLNA.ORG_PN=WMVHIGH_BASE";
  141. }
  142. else if (string.Equals(extension, ".mkv", StringComparison.OrdinalIgnoreCase))
  143. {
  144. // ??
  145. contentFeatures = "";
  146. }
  147. if (!string.IsNullOrEmpty(contentFeatures))
  148. {
  149. responseHeaders["ContentFeatures.DLNA.ORG"] = (contentFeatures + orgOp + orgCi + dlnaflags).Trim(';');
  150. }
  151. }
  152. /// <summary>
  153. /// Gets the type of the transcoding job.
  154. /// </summary>
  155. /// <value>The type of the transcoding job.</value>
  156. protected override TranscodingJobType TranscodingJobType
  157. {
  158. get { return TranscodingJobType.Progressive; }
  159. }
  160. /// <summary>
  161. /// Processes the request.
  162. /// </summary>
  163. /// <param name="request">The request.</param>
  164. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  165. /// <returns>Task.</returns>
  166. protected object ProcessRequest(StreamRequest request, bool isHeadRequest)
  167. {
  168. var state = GetState(request);
  169. if (request.AlbumArt)
  170. {
  171. return GetAlbumArtResponse(state);
  172. }
  173. var responseHeaders = new Dictionary<string, string>();
  174. if (request.Static && state.Item.LocationType == LocationType.Remote)
  175. {
  176. return GetStaticRemoteStreamResult(state.Item, responseHeaders, isHeadRequest).Result;
  177. }
  178. var outputPath = GetOutputFilePath(state);
  179. var outputPathExists = File.Exists(outputPath);
  180. //var isStatic = request.Static ||
  181. // (outputPathExists && !ApiEntryPoint.Instance.HasActiveTranscodingJob(outputPath, TranscodingJobType.Progressive));
  182. //AddDlnaHeaders(state, responseHeaders, isStatic);
  183. if (request.Static)
  184. {
  185. return ResultFactory.GetStaticFileResult(RequestContext, state.Item.Path, responseHeaders, isHeadRequest);
  186. }
  187. if (outputPathExists && !ApiEntryPoint.Instance.HasActiveTranscodingJob(outputPath, TranscodingJobType.Progressive))
  188. {
  189. return ResultFactory.GetStaticFileResult(RequestContext, outputPath, responseHeaders, isHeadRequest);
  190. }
  191. return GetStreamResult(state, responseHeaders, isHeadRequest).Result;
  192. }
  193. /// <summary>
  194. /// Gets the static remote stream result.
  195. /// </summary>
  196. /// <param name="item">The item.</param>
  197. /// <param name="responseHeaders">The response headers.</param>
  198. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  199. /// <returns>Task{System.Object}.</returns>
  200. private async Task<object> GetStaticRemoteStreamResult(BaseItem item, Dictionary<string, string> responseHeaders, bool isHeadRequest)
  201. {
  202. responseHeaders["Accept-Ranges"] = "none";
  203. var httpClient = new HttpClient(new WebRequestHandler
  204. {
  205. CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache),
  206. AutomaticDecompression = DecompressionMethods.None
  207. });
  208. using (var message = new HttpRequestMessage(HttpMethod.Get, item.Path))
  209. {
  210. var useragent = GetUserAgent(item);
  211. if (!string.IsNullOrEmpty(useragent))
  212. {
  213. message.Headers.Add("User-Agent", useragent);
  214. }
  215. var response = await httpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
  216. response.EnsureSuccessStatusCode();
  217. var contentType = response.Content.Headers.ContentType.MediaType;
  218. // Headers only
  219. if (isHeadRequest)
  220. {
  221. response.Dispose();
  222. httpClient.Dispose();
  223. return ResultFactory.GetResult(null, contentType, responseHeaders);
  224. }
  225. var result = new StaticRemoteStreamWriter(response, httpClient);
  226. result.Options["Content-Type"] = contentType;
  227. // Add the response headers to the result object
  228. foreach (var header in responseHeaders)
  229. {
  230. result.Options[header.Key] = header.Value;
  231. }
  232. return result;
  233. }
  234. }
  235. /// <summary>
  236. /// Gets the album art response.
  237. /// </summary>
  238. /// <param name="state">The state.</param>
  239. /// <returns>System.Object.</returns>
  240. private object GetAlbumArtResponse(StreamState state)
  241. {
  242. var request = new GetItemImage
  243. {
  244. MaxWidth = 800,
  245. MaxHeight = 800,
  246. Type = ImageType.Primary,
  247. Id = state.Item.Id.ToString()
  248. };
  249. // Try and find some image to return
  250. if (!state.Item.HasImage(ImageType.Primary))
  251. {
  252. if (state.Item.HasImage(ImageType.Backdrop))
  253. {
  254. request.Type = ImageType.Backdrop;
  255. }
  256. else if (state.Item.HasImage(ImageType.Thumb))
  257. {
  258. request.Type = ImageType.Thumb;
  259. }
  260. else if (state.Item.HasImage(ImageType.Logo))
  261. {
  262. request.Type = ImageType.Logo;
  263. }
  264. }
  265. return new ImageService(UserManager, LibraryManager, ApplicationPaths, null, ItemRepository)
  266. {
  267. Logger = Logger,
  268. RequestContext = RequestContext,
  269. ResultFactory = ResultFactory
  270. }.Get(request);
  271. }
  272. /// <summary>
  273. /// Gets the stream result.
  274. /// </summary>
  275. /// <param name="state">The state.</param>
  276. /// <param name="responseHeaders">The response headers.</param>
  277. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  278. /// <returns>Task{System.Object}.</returns>
  279. private async Task<object> GetStreamResult(StreamState state, IDictionary<string, string> responseHeaders, bool isHeadRequest)
  280. {
  281. // Use the command line args with a dummy playlist path
  282. var outputPath = GetOutputFilePath(state);
  283. var contentType = MimeTypes.GetMimeType(outputPath);
  284. // Headers only
  285. if (isHeadRequest)
  286. {
  287. responseHeaders["Accept-Ranges"] = "none";
  288. return ResultFactory.GetResult(null, contentType, responseHeaders);
  289. }
  290. if (!File.Exists(outputPath))
  291. {
  292. await StartFfMpeg(state, outputPath).ConfigureAwait(false);
  293. }
  294. else
  295. {
  296. ApiEntryPoint.Instance.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive);
  297. }
  298. var result = new ProgressiveStreamWriter(outputPath, state, Logger);
  299. result.Options["Accept-Ranges"] = "none";
  300. result.Options["Content-Type"] = contentType;
  301. // Add the response headers to the result object
  302. foreach (var item in responseHeaders)
  303. {
  304. result.Options[item.Key] = item.Value;
  305. }
  306. return result;
  307. }
  308. }
  309. }