BaseProgressiveStreamingService.cs 13 KB

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