GetTextureHandler.cs 18 KB

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