GetTextureHandler.cs 18 KB

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