GetTextureHandler.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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
  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. public GetTextureHandler(IAssetService assService)
  55. {
  56. m_assetService = assService;
  57. }
  58. public Hashtable Handle(Hashtable request)
  59. {
  60. Hashtable ret = new Hashtable();
  61. ret["int_response_code"] = (int)System.Net.HttpStatusCode.NotFound;
  62. ret["content_type"] = "text/plain";
  63. ret["int_bytes"] = 0;
  64. string textureStr = (string)request["texture_id"];
  65. string format = (string)request["format"];
  66. //m_log.DebugFormat("[GETTEXTURE]: called {0}", textureStr);
  67. if (m_assetService == null)
  68. {
  69. m_log.Error("[GETTEXTURE]: Cannot fetch texture " + textureStr + " without an asset service");
  70. }
  71. UUID textureID;
  72. if (!String.IsNullOrEmpty(textureStr) && UUID.TryParse(textureStr, out textureID))
  73. {
  74. // m_log.DebugFormat("[GETTEXTURE]: Received request for texture id {0}", textureID);
  75. string[] formats;
  76. if (!string.IsNullOrEmpty(format))
  77. {
  78. formats = new string[1] { format.ToLower() };
  79. }
  80. else
  81. {
  82. formats = new string[1] { DefaultFormat }; // default
  83. if (((Hashtable)request["headers"])["Accept"] != null)
  84. formats = WebUtil.GetPreferredImageTypes((string)((Hashtable)request["headers"])["Accept"]);
  85. if (formats.Length == 0)
  86. formats = new string[1] { DefaultFormat }; // default
  87. }
  88. // OK, we have an array with preferred formats, possibly with only one entry
  89. bool foundtexture = false;
  90. foreach (string f in formats)
  91. {
  92. foundtexture = FetchTexture(request, ret, textureID, f);
  93. if (foundtexture)
  94. break;
  95. }
  96. if (!foundtexture)
  97. {
  98. ret["int_response_code"] = 404;
  99. ret["error_status_text"] = "not found";
  100. ret["str_response_string"] = "not found";
  101. ret["content_type"] = "text/plain";
  102. ret["int_bytes"] = 0;
  103. }
  104. }
  105. else
  106. {
  107. m_log.Warn("[GETTEXTURE]: Failed to parse a texture_id from GetTexture request: " + (string)request["uri"]);
  108. }
  109. // m_log.DebugFormat(
  110. // "[GETTEXTURE]: For texture {0} sending back response {1}, data length {2}",
  111. // textureID, httpResponse.StatusCode, httpResponse.ContentLength);
  112. return ret;
  113. }
  114. /// <summary>
  115. ///
  116. /// </summary>
  117. /// <param name="httpRequest"></param>
  118. /// <param name="httpResponse"></param>
  119. /// <param name="textureID"></param>
  120. /// <param name="format"></param>
  121. /// <returns>False for "caller try another codec"; true otherwise</returns>
  122. private bool FetchTexture(Hashtable request, Hashtable response, UUID textureID, string format)
  123. {
  124. // m_log.DebugFormat("[GETTEXTURE]: {0} with requested format {1}", textureID, format);
  125. AssetBase texture;
  126. string fullID = textureID.ToString();
  127. if (format != DefaultFormat)
  128. fullID = fullID + "-" + format;
  129. // try the cache
  130. texture = m_assetService.GetCached(fullID);
  131. if (texture == null)
  132. {
  133. //m_log.DebugFormat("[GETTEXTURE]: texture was not in the cache");
  134. // Fetch locally or remotely. Misses return a 404
  135. texture = m_assetService.Get(textureID.ToString());
  136. if (texture != null)
  137. {
  138. if (texture.Type != (sbyte)AssetType.Texture)
  139. return true;
  140. if (format == DefaultFormat)
  141. {
  142. WriteTextureData(request, response, texture, format);
  143. return true;
  144. }
  145. else
  146. {
  147. AssetBase newTexture = new AssetBase(texture.ID + "-" + format, texture.Name, (sbyte)AssetType.Texture, texture.Metadata.CreatorID);
  148. newTexture.Data = ConvertTextureData(texture, format);
  149. if (newTexture.Data.Length == 0)
  150. return false; // !!! Caller try another codec, please!
  151. newTexture.Flags = AssetFlags.Collectable;
  152. newTexture.Temporary = true;
  153. newTexture.Local = true;
  154. m_assetService.Store(newTexture);
  155. WriteTextureData(request, response, newTexture, format);
  156. return true;
  157. }
  158. }
  159. }
  160. else // it was on the cache
  161. {
  162. //m_log.DebugFormat("[GETTEXTURE]: texture was in the cache");
  163. WriteTextureData(request, response, texture, format);
  164. return true;
  165. }
  166. //response = new Hashtable();
  167. //WriteTextureData(request,response,null,format);
  168. // not found
  169. //m_log.Warn("[GETTEXTURE]: Texture " + textureID + " not found");
  170. return false;
  171. }
  172. private void WriteTextureData(Hashtable request, Hashtable response, AssetBase texture, string format)
  173. {
  174. Hashtable headers = new Hashtable();
  175. response["headers"] = headers;
  176. string range = String.Empty;
  177. if (((Hashtable)request["headers"])["range"] != null)
  178. range = (string)((Hashtable)request["headers"])["range"];
  179. else if (((Hashtable)request["headers"])["Range"] != null)
  180. range = (string)((Hashtable)request["headers"])["Range"];
  181. if (!String.IsNullOrEmpty(range)) // JP2's only
  182. {
  183. // Range request
  184. int start, end;
  185. if (TryParseRange(range, out start, out end))
  186. {
  187. // Before clamping start make sure we can satisfy it in order to avoid
  188. // sending back the last byte instead of an error status
  189. if (start >= texture.Data.Length)
  190. {
  191. // m_log.DebugFormat(
  192. // "[GETTEXTURE]: Client requested range for texture {0} starting at {1} but texture has end of {2}",
  193. // texture.ID, start, texture.Data.Length);
  194. // Stricly speaking, as per http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html, we should be sending back
  195. // Requested Range Not Satisfiable (416) here. However, it appears that at least recent implementations
  196. // of the Linden Lab viewer (3.2.1 and 3.3.4 and probably earlier), a viewer that has previously
  197. // received a very small texture may attempt to fetch bytes from the server past the
  198. // range of data that it received originally. Whether this happens appears to depend on whether
  199. // the viewer's estimation of how large a request it needs to make for certain discard levels
  200. // (http://wiki.secondlife.com/wiki/Image_System#Discard_Level_and_Mip_Mapping), chiefly discard
  201. // level 2. If this estimate is greater than the total texture size, returning a RequestedRangeNotSatisfiable
  202. // here will cause the viewer to treat the texture as bad and never display the full resolution
  203. // However, if we return PartialContent (or OK) instead, the viewer will display that resolution.
  204. // response.StatusCode = (int)System.Net.HttpStatusCode.RequestedRangeNotSatisfiable;
  205. // viewers don't seem to handle RequestedRangeNotSatisfiable and keep retrying with same parameters
  206. response["int_response_code"] = (int)System.Net.HttpStatusCode.NotFound;
  207. }
  208. else
  209. {
  210. // Handle the case where no second range value was given. This is equivalent to requesting
  211. // the rest of the entity.
  212. if (end == -1)
  213. end = int.MaxValue;
  214. end = Utils.Clamp(end, 0, texture.Data.Length - 1);
  215. start = Utils.Clamp(start, 0, end);
  216. int len = end - start + 1;
  217. // m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID);
  218. response["content-type"] = texture.Metadata.ContentType;
  219. response["int_response_code"] = (int)System.Net.HttpStatusCode.PartialContent;
  220. headers["Content-Range"] = String.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length);
  221. byte[] d = new byte[len];
  222. Array.Copy(texture.Data, start, d, 0, len);
  223. response["bin_response_data"] = d;
  224. response["int_bytes"] = len;
  225. }
  226. }
  227. else
  228. {
  229. m_log.Warn("[GETTEXTURE]: Malformed Range header: " + range);
  230. response["int_response_code"] = (int)System.Net.HttpStatusCode.BadRequest;
  231. }
  232. }
  233. else // JP2's or other formats
  234. {
  235. // Full content request
  236. response["int_response_code"] = (int)System.Net.HttpStatusCode.OK;
  237. if (format == DefaultFormat)
  238. response["content_type"] = texture.Metadata.ContentType;
  239. else
  240. response["content_type"] = "image/" + format;
  241. response["bin_response_data"] = texture.Data;
  242. response["int_bytes"] = texture.Data.Length;
  243. // response.Body.Write(texture.Data, 0, texture.Data.Length);
  244. }
  245. // if (response.StatusCode < 200 || response.StatusCode > 299)
  246. // m_log.WarnFormat(
  247. // "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})",
  248. // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length);
  249. // else
  250. // m_log.DebugFormat(
  251. // "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})",
  252. // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length);
  253. }
  254. /// <summary>
  255. /// Parse a range header.
  256. /// </summary>
  257. /// <remarks>
  258. /// As per http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html,
  259. /// this obeys range headers with two values (e.g. 533-4165) and no second value (e.g. 533-).
  260. /// Where there is no value, -1 is returned.
  261. /// FIXME: Need to cover the case where only a second value is specified (e.g. -4165), probably by returning -1
  262. /// for start.</remarks>
  263. /// <returns></returns>
  264. /// <param name='header'></param>
  265. /// <param name='start'>Start of the range. Undefined if this was not a number.</param>
  266. /// <param name='end'>End of the range. Will be -1 if no end specified. Undefined if there was a raw string but this was not a number.</param>
  267. private bool TryParseRange(string header, out int start, out int end)
  268. {
  269. start = end = 0;
  270. if (header.StartsWith("bytes="))
  271. {
  272. string[] rangeValues = header.Substring(6).Split('-');
  273. if (rangeValues.Length == 2)
  274. {
  275. if (!Int32.TryParse(rangeValues[0], out start))
  276. return false;
  277. string rawEnd = rangeValues[1];
  278. if (rawEnd == "")
  279. {
  280. end = -1;
  281. return true;
  282. }
  283. else if (Int32.TryParse(rawEnd, out end))
  284. {
  285. return true;
  286. }
  287. }
  288. }
  289. start = end = 0;
  290. return false;
  291. }
  292. private byte[] ConvertTextureData(AssetBase texture, string format)
  293. {
  294. m_log.DebugFormat("[GETTEXTURE]: Converting texture {0} to {1}", texture.ID, format);
  295. byte[] data = new byte[0];
  296. MemoryStream imgstream = new MemoryStream();
  297. Bitmap mTexture = null;
  298. ManagedImage managedImage = null;
  299. Image image = null;
  300. try
  301. {
  302. // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular data
  303. // Decode image to System.Drawing.Image
  304. if (OpenJPEG.DecodeToImage(texture.Data, out managedImage, out image) && image != null)
  305. {
  306. // Save to bitmap
  307. mTexture = new Bitmap(image);
  308. using(EncoderParameters myEncoderParameters = new EncoderParameters())
  309. {
  310. myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality,95L);
  311. // Save bitmap to stream
  312. ImageCodecInfo codec = GetEncoderInfo("image/" + format);
  313. if (codec != null)
  314. {
  315. mTexture.Save(imgstream, codec, myEncoderParameters);
  316. // Write the stream to a byte array for output
  317. data = imgstream.ToArray();
  318. }
  319. else
  320. m_log.WarnFormat("[GETTEXTURE]: No such codec {0}", format);
  321. }
  322. }
  323. }
  324. catch (Exception e)
  325. {
  326. m_log.WarnFormat("[GETTEXTURE]: Unable to convert texture {0} to {1}: {2}", texture.ID, format, e.Message);
  327. }
  328. finally
  329. {
  330. // Reclaim memory, these are unmanaged resources
  331. // If we encountered an exception, one or more of these will be null
  332. if (mTexture != null)
  333. mTexture.Dispose();
  334. if (image != null)
  335. image.Dispose();
  336. if(managedImage != null)
  337. managedImage.Clear();
  338. if (imgstream != null)
  339. imgstream.Dispose();
  340. }
  341. return data;
  342. }
  343. // From msdn
  344. private static ImageCodecInfo GetEncoderInfo(String mimeType)
  345. {
  346. ImageCodecInfo[] encoders;
  347. encoders = ImageCodecInfo.GetImageEncoders();
  348. for (int j = 0; j < encoders.Length; ++j)
  349. {
  350. if (encoders[j].MimeType == mimeType)
  351. return encoders[j];
  352. }
  353. return null;
  354. }
  355. }
  356. }