GetTextureHandler.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections;
  29. using System.Collections.Specialized;
  30. using System.Drawing;
  31. using System.Drawing.Imaging;
  32. using System.Reflection;
  33. using System.IO;
  34. using System.Web;
  35. using log4net;
  36. using Nini.Config;
  37. using OpenMetaverse;
  38. using OpenMetaverse.StructuredData;
  39. using OpenMetaverse.Imaging;
  40. using OpenSim.Framework;
  41. using OpenSim.Framework.Servers;
  42. using OpenSim.Framework.Servers.HttpServer;
  43. using OpenSim.Region.Framework.Interfaces;
  44. using OpenSim.Services.Interfaces;
  45. using Caps = OpenSim.Framework.Capabilities.Caps;
  46. namespace OpenSim.Capabilities.Handlers
  47. {
  48. public class GetTextureHandler : BaseStreamHandler
  49. {
  50. private static readonly ILog m_log =
  51. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  52. private IAssetService m_assetService;
  53. public const string DefaultFormat = "x-j2c";
  54. // TODO: Change this to a config option
  55. const string REDIRECT_URL = null;
  56. public GetTextureHandler(string path, IAssetService assService) :
  57. base("GET", path)
  58. {
  59. m_assetService = assService;
  60. }
  61. public override byte[] Handle(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  62. {
  63. // Try to parse the texture ID from the request URL
  64. NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);
  65. string textureStr = query.GetOne("texture_id");
  66. string format = query.GetOne("format");
  67. //m_log.DebugFormat("[GETTEXTURE]: called {0}", textureStr);
  68. if (m_assetService == null)
  69. {
  70. m_log.Error("[GETTEXTURE]: Cannot fetch texture " + textureStr + " without an asset service");
  71. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
  72. return null;
  73. }
  74. UUID textureID;
  75. if (!String.IsNullOrEmpty(textureStr) && UUID.TryParse(textureStr, out textureID))
  76. {
  77. // m_log.DebugFormat("[GETTEXTURE]: Received request for texture id {0}", textureID);
  78. string[] formats;
  79. if (format != null && format != string.Empty)
  80. {
  81. formats = new string[1] { format.ToLower() };
  82. }
  83. else
  84. {
  85. formats = WebUtil.GetPreferredImageTypes(httpRequest.Headers.Get("Accept"));
  86. if (formats.Length == 0)
  87. formats = new string[1] { DefaultFormat }; // default
  88. }
  89. // OK, we have an array with preferred formats, possibly with only one entry
  90. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
  91. foreach (string f in formats)
  92. {
  93. if (FetchTexture(httpRequest, httpResponse, textureID, f))
  94. break;
  95. }
  96. }
  97. else
  98. {
  99. m_log.Warn("[GETTEXTURE]: Failed to parse a texture_id from GetTexture request: " + httpRequest.Url);
  100. }
  101. // m_log.DebugFormat(
  102. // "[GETTEXTURE]: For texture {0} sending back response {1}, data length {2}",
  103. // textureID, httpResponse.StatusCode, httpResponse.ContentLength);
  104. httpResponse.Send();
  105. return null;
  106. }
  107. /// <summary>
  108. ///
  109. /// </summary>
  110. /// <param name="httpRequest"></param>
  111. /// <param name="httpResponse"></param>
  112. /// <param name="textureID"></param>
  113. /// <param name="format"></param>
  114. /// <returns>False for "caller try another codec"; true otherwise</returns>
  115. private bool FetchTexture(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, UUID textureID, string format)
  116. {
  117. // m_log.DebugFormat("[GETTEXTURE]: {0} with requested format {1}", textureID, format);
  118. AssetBase texture;
  119. string fullID = textureID.ToString();
  120. if (format != DefaultFormat)
  121. fullID = fullID + "-" + format;
  122. if (!String.IsNullOrEmpty(REDIRECT_URL))
  123. {
  124. // Only try to fetch locally cached textures. Misses are redirected
  125. texture = m_assetService.GetCached(fullID);
  126. if (texture != null)
  127. {
  128. if (texture.Type != (sbyte)AssetType.Texture)
  129. {
  130. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
  131. return true;
  132. }
  133. WriteTextureData(httpRequest, httpResponse, texture, format);
  134. }
  135. else
  136. {
  137. string textureUrl = REDIRECT_URL + textureID.ToString();
  138. m_log.Debug("[GETTEXTURE]: Redirecting texture request to " + textureUrl);
  139. httpResponse.RedirectLocation = textureUrl;
  140. return true;
  141. }
  142. }
  143. else // no redirect
  144. {
  145. // try the cache
  146. texture = m_assetService.GetCached(fullID);
  147. if (texture == null)
  148. {
  149. //m_log.DebugFormat("[GETTEXTURE]: texture was not in the cache");
  150. // Fetch locally or remotely. Misses return a 404
  151. texture = m_assetService.Get(textureID.ToString());
  152. if (texture != null)
  153. {
  154. if (texture.Type != (sbyte)AssetType.Texture)
  155. {
  156. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
  157. return true;
  158. }
  159. if (format == DefaultFormat)
  160. {
  161. WriteTextureData(httpRequest, httpResponse, texture, format);
  162. return true;
  163. }
  164. else
  165. {
  166. AssetBase newTexture = new AssetBase(texture.ID + "-" + format, texture.Name, (sbyte)AssetType.Texture, texture.Metadata.CreatorID);
  167. newTexture.Data = ConvertTextureData(texture, format);
  168. if (newTexture.Data.Length == 0)
  169. return false; // !!! Caller try another codec, please!
  170. newTexture.Flags = AssetFlags.Collectable;
  171. newTexture.Temporary = true;
  172. m_assetService.Store(newTexture);
  173. WriteTextureData(httpRequest, httpResponse, newTexture, format);
  174. return true;
  175. }
  176. }
  177. }
  178. else // it was on the cache
  179. {
  180. //m_log.DebugFormat("[GETTEXTURE]: texture was in the cache");
  181. WriteTextureData(httpRequest, httpResponse, texture, format);
  182. return true;
  183. }
  184. }
  185. // not found
  186. // m_log.Warn("[GETTEXTURE]: Texture " + textureID + " not found");
  187. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
  188. return true;
  189. }
  190. private void WriteTextureData(IOSHttpRequest request, IOSHttpResponse response, AssetBase texture, string format)
  191. {
  192. string range = request.Headers.GetOne("Range");
  193. if (!String.IsNullOrEmpty(range)) // JP2's only
  194. {
  195. // Range request
  196. int start, end;
  197. if (TryParseRange(range, out start, out end))
  198. {
  199. // Before clamping start make sure we can satisfy it in order to avoid
  200. // sending back the last byte instead of an error status
  201. if (start >= texture.Data.Length)
  202. {
  203. response.StatusCode = (int)System.Net.HttpStatusCode.RequestedRangeNotSatisfiable;
  204. }
  205. else
  206. {
  207. end = Utils.Clamp(end, 0, texture.Data.Length - 1);
  208. start = Utils.Clamp(start, 0, end);
  209. int len = end - start + 1;
  210. //m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID);
  211. // Always return PartialContent, even if the range covered the entire data length
  212. // We were accidentally sending back 404 before in this situation
  213. // https://issues.apache.org/bugzilla/show_bug.cgi?id=51878 supports sending 206 even if the
  214. // entire range is requested, and viewer 3.2.2 (and very probably earlier) seems fine with this.
  215. response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent;
  216. response.ContentLength = len;
  217. response.ContentType = texture.Metadata.ContentType;
  218. response.AddHeader("Content-Range", String.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length));
  219. response.Body.Write(texture.Data, start, len);
  220. }
  221. }
  222. else
  223. {
  224. m_log.Warn("[GETTEXTURE]: Malformed Range header: " + range);
  225. response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
  226. }
  227. }
  228. else // JP2's or other formats
  229. {
  230. // Full content request
  231. response.StatusCode = (int)System.Net.HttpStatusCode.OK;
  232. response.ContentLength = texture.Data.Length;
  233. if (format == DefaultFormat)
  234. response.ContentType = texture.Metadata.ContentType;
  235. else
  236. response.ContentType = "image/" + format;
  237. response.Body.Write(texture.Data, 0, texture.Data.Length);
  238. }
  239. // if (response.StatusCode < 200 || response.StatusCode > 299)
  240. // m_log.WarnFormat(
  241. // "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})",
  242. // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length);
  243. // else
  244. // m_log.DebugFormat(
  245. // "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})",
  246. // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length);
  247. }
  248. private bool TryParseRange(string header, out int start, out int end)
  249. {
  250. if (header.StartsWith("bytes="))
  251. {
  252. string[] rangeValues = header.Substring(6).Split('-');
  253. if (rangeValues.Length == 2)
  254. {
  255. if (Int32.TryParse(rangeValues[0], out start) && Int32.TryParse(rangeValues[1], out end))
  256. return true;
  257. }
  258. }
  259. start = end = 0;
  260. return false;
  261. }
  262. private byte[] ConvertTextureData(AssetBase texture, string format)
  263. {
  264. m_log.DebugFormat("[GETTEXTURE]: Converting texture {0} to {1}", texture.ID, format);
  265. byte[] data = new byte[0];
  266. MemoryStream imgstream = new MemoryStream();
  267. Bitmap mTexture = new Bitmap(1, 1);
  268. ManagedImage managedImage;
  269. Image image = (Image)mTexture;
  270. try
  271. {
  272. // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular data
  273. imgstream = new MemoryStream();
  274. // Decode image to System.Drawing.Image
  275. if (OpenJPEG.DecodeToImage(texture.Data, out managedImage, out image))
  276. {
  277. // Save to bitmap
  278. mTexture = new Bitmap(image);
  279. EncoderParameters myEncoderParameters = new EncoderParameters();
  280. myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
  281. // Save bitmap to stream
  282. ImageCodecInfo codec = GetEncoderInfo("image/" + format);
  283. if (codec != null)
  284. {
  285. mTexture.Save(imgstream, codec, myEncoderParameters);
  286. // Write the stream to a byte array for output
  287. data = imgstream.ToArray();
  288. }
  289. else
  290. m_log.WarnFormat("[GETTEXTURE]: No such codec {0}", format);
  291. }
  292. }
  293. catch (Exception e)
  294. {
  295. m_log.WarnFormat("[GETTEXTURE]: Unable to convert texture {0} to {1}: {2}", texture.ID, format, e.Message);
  296. }
  297. finally
  298. {
  299. // Reclaim memory, these are unmanaged resources
  300. // If we encountered an exception, one or more of these will be null
  301. if (mTexture != null)
  302. mTexture.Dispose();
  303. if (image != null)
  304. image.Dispose();
  305. if (imgstream != null)
  306. {
  307. imgstream.Close();
  308. imgstream.Dispose();
  309. }
  310. }
  311. return data;
  312. }
  313. // From msdn
  314. private static ImageCodecInfo GetEncoderInfo(String mimeType)
  315. {
  316. ImageCodecInfo[] encoders;
  317. encoders = ImageCodecInfo.GetImageEncoders();
  318. for (int j = 0; j < encoders.Length; ++j)
  319. {
  320. if (encoders[j].MimeType == mimeType)
  321. return encoders[j];
  322. }
  323. return null;
  324. }
  325. }
  326. }