BaseProgressiveStreamingService.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Drawing;
  5. using MediaBrowser.Controller.Dto;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.LiveTv;
  8. using MediaBrowser.Controller.MediaEncoding;
  9. using MediaBrowser.Controller.Persistence;
  10. using MediaBrowser.Model.Dto;
  11. using MediaBrowser.Model.IO;
  12. using ServiceStack.Web;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.IO;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Api.Playback.Progressive
  19. {
  20. /// <summary>
  21. /// Class BaseProgressiveStreamingService
  22. /// </summary>
  23. public abstract class BaseProgressiveStreamingService : BaseStreamingService
  24. {
  25. protected readonly IImageProcessor ImageProcessor;
  26. protected readonly IHttpClient HttpClient;
  27. protected BaseProgressiveStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IDtoService dtoService, IFileSystem fileSystem, IItemRepository itemRepository, ILiveTvManager liveTvManager, IEncodingManager encodingManager, IHttpClient httpClient, IImageProcessor imageProcessor)
  28. : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, dtoService, fileSystem, itemRepository, liveTvManager, encodingManager)
  29. {
  30. HttpClient = httpClient;
  31. ImageProcessor = imageProcessor;
  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. if (state.IsInputVideo)
  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. if (!state.IsInputVideo)
  68. {
  69. switch (state.Request.AudioCodec.Value)
  70. {
  71. case AudioCodecs.Aac:
  72. return ".aac";
  73. case AudioCodecs.Mp3:
  74. return ".mp3";
  75. case AudioCodecs.Vorbis:
  76. return ".ogg";
  77. case AudioCodecs.Wma:
  78. return ".wma";
  79. }
  80. }
  81. }
  82. return null;
  83. }
  84. /// <summary>
  85. /// Adds the dlna headers.
  86. /// </summary>
  87. /// <param name="state">The state.</param>
  88. /// <param name="responseHeaders">The response headers.</param>
  89. /// <param name="isStaticallyStreamed">if set to <c>true</c> [is statically streamed].</param>
  90. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  91. private void AddDlnaHeaders(StreamState state, IDictionary<string, string> responseHeaders, bool isStaticallyStreamed)
  92. {
  93. var timeSeek = GetHeader("TimeSeekRange.dlna.org");
  94. if (!string.IsNullOrEmpty(timeSeek))
  95. {
  96. ResultFactory.ThrowError(406, "Time seek not supported during encoding.", responseHeaders);
  97. return;
  98. }
  99. var transferMode = GetHeader("transferMode.dlna.org");
  100. responseHeaders["transferMode.dlna.org"] = string.IsNullOrEmpty(transferMode) ? "Streaming" : transferMode;
  101. responseHeaders["realTimeInfo.dlna.org"] = "DLNA.ORG_TLAG=*";
  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, ".mkv", StringComparison.OrdinalIgnoreCase))
  126. {
  127. contentFeatures = "DLNA.ORG_PN=MATROSKA";
  128. }
  129. else if (string.Equals(extension, ".mp4", StringComparison.OrdinalIgnoreCase))
  130. {
  131. contentFeatures = "DLNA.ORG_PN=AVC_MP4_MP_HD_720p_AAC";
  132. }
  133. else if (string.Equals(extension, ".mpeg", StringComparison.OrdinalIgnoreCase))
  134. {
  135. contentFeatures = "DLNA.ORG_PN=MPEG_PS_PAL";
  136. }
  137. else if (string.Equals(extension, ".ts", StringComparison.OrdinalIgnoreCase))
  138. {
  139. contentFeatures = "DLNA.ORG_PN=MPEG_PS_PAL";
  140. }
  141. //else if (string.Equals(extension, ".wmv", StringComparison.OrdinalIgnoreCase))
  142. //{
  143. // contentFeatures = "DLNA.ORG_PN=WMVHIGH_BASE";
  144. //}
  145. //else if (string.Equals(extension, ".asf", StringComparison.OrdinalIgnoreCase))
  146. //{
  147. // // ??
  148. // contentFeatures = "DLNA.ORG_PN=WMVHIGH_BASE";
  149. //}
  150. if (!string.IsNullOrEmpty(contentFeatures))
  151. {
  152. responseHeaders["contentFeatures.dlna.org"] = (contentFeatures + orgOp + orgCi + dlnaflags).Trim(';');
  153. }
  154. foreach (var item in responseHeaders)
  155. {
  156. Request.Response.AddHeader(item.Key, item.Value);
  157. }
  158. }
  159. /// <summary>
  160. /// Gets the type of the transcoding job.
  161. /// </summary>
  162. /// <value>The type of the transcoding job.</value>
  163. protected override TranscodingJobType TranscodingJobType
  164. {
  165. get { return TranscodingJobType.Progressive; }
  166. }
  167. /// <summary>
  168. /// Processes the request.
  169. /// </summary>
  170. /// <param name="request">The request.</param>
  171. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  172. /// <returns>Task.</returns>
  173. protected object ProcessRequest(StreamRequest request, bool isHeadRequest)
  174. {
  175. var state = GetState(request, CancellationToken.None).Result;
  176. var responseHeaders = new Dictionary<string, string>();
  177. if (request.Static && state.IsRemote)
  178. {
  179. AddDlnaHeaders(state, responseHeaders, true);
  180. return GetStaticRemoteStreamResult(state.MediaPath, responseHeaders, isHeadRequest).Result;
  181. }
  182. var outputPath = GetOutputFilePath(state);
  183. var outputPathExists = File.Exists(outputPath);
  184. var isStatic = request.Static ||
  185. (outputPathExists && !ApiEntryPoint.Instance.HasActiveTranscodingJob(outputPath, TranscodingJobType.Progressive));
  186. AddDlnaHeaders(state, responseHeaders, isStatic);
  187. if (request.Static)
  188. {
  189. return ResultFactory.GetStaticFileResult(Request, state.MediaPath, FileShare.Read, responseHeaders, isHeadRequest);
  190. }
  191. if (outputPathExists && !ApiEntryPoint.Instance.HasActiveTranscodingJob(outputPath, TranscodingJobType.Progressive))
  192. {
  193. return ResultFactory.GetStaticFileResult(Request, outputPath, FileShare.Read, responseHeaders, isHeadRequest);
  194. }
  195. return GetStreamResult(state, responseHeaders, isHeadRequest).Result;
  196. }
  197. /// <summary>
  198. /// Gets the static remote stream result.
  199. /// </summary>
  200. /// <param name="mediaPath">The media path.</param>
  201. /// <param name="responseHeaders">The response headers.</param>
  202. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  203. /// <returns>Task{System.Object}.</returns>
  204. private async Task<object> GetStaticRemoteStreamResult(string mediaPath, Dictionary<string, string> responseHeaders, bool isHeadRequest)
  205. {
  206. var options = new HttpRequestOptions
  207. {
  208. Url = mediaPath,
  209. UserAgent = GetUserAgent(mediaPath),
  210. BufferContent = false
  211. };
  212. var response = await HttpClient.GetResponse(options).ConfigureAwait(false);
  213. responseHeaders["Accept-Ranges"] = "none";
  214. var length = response.Headers["Content-Length"];
  215. if (!string.IsNullOrEmpty(length))
  216. {
  217. responseHeaders["Content-Length"] = length;
  218. }
  219. if (isHeadRequest)
  220. {
  221. using (response.Content)
  222. {
  223. return ResultFactory.GetResult(new byte[] { }, response.ContentType, responseHeaders);
  224. }
  225. }
  226. var result = new StaticRemoteStreamWriter(response);
  227. result.Options["Content-Type"] = response.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. /// <summary>
  236. /// Gets the stream result.
  237. /// </summary>
  238. /// <param name="state">The state.</param>
  239. /// <param name="responseHeaders">The response headers.</param>
  240. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  241. /// <returns>Task{System.Object}.</returns>
  242. private async Task<object> GetStreamResult(StreamState state, IDictionary<string, string> responseHeaders, bool isHeadRequest)
  243. {
  244. // Use the command line args with a dummy playlist path
  245. var outputPath = GetOutputFilePath(state);
  246. responseHeaders["Accept-Ranges"] = "none";
  247. var contentType = MimeTypes.GetMimeType(outputPath);
  248. // Headers only
  249. if (isHeadRequest)
  250. {
  251. var streamResult = ResultFactory.GetResult(new byte[] { }, contentType, responseHeaders);
  252. var hasOptions = streamResult as IHasOptions;
  253. if (hasOptions != null)
  254. {
  255. if (hasOptions.Options.ContainsKey("Content-Length"))
  256. {
  257. hasOptions.Options.Remove("Content-Length");
  258. }
  259. }
  260. return streamResult;
  261. }
  262. if (!File.Exists(outputPath))
  263. {
  264. await StartFfMpeg(state, outputPath).ConfigureAwait(false);
  265. }
  266. else
  267. {
  268. ApiEntryPoint.Instance.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive);
  269. }
  270. var result = new ProgressiveStreamWriter(outputPath, Logger, FileSystem);
  271. result.Options["Content-Type"] = contentType;
  272. // Add the response headers to the result object
  273. foreach (var item in responseHeaders)
  274. {
  275. result.Options[item.Key] = item.Value;
  276. }
  277. return result;
  278. }
  279. }
  280. }