GetTextureHandler.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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, OSHttpRequest httpRequest, OSHttpResponse 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. httpResponse.Send();
  102. return null;
  103. }
  104. /// <summary>
  105. ///
  106. /// </summary>
  107. /// <param name="httpRequest"></param>
  108. /// <param name="httpResponse"></param>
  109. /// <param name="textureID"></param>
  110. /// <param name="format"></param>
  111. /// <returns>False for "caller try another codec"; true otherwise</returns>
  112. private bool FetchTexture(OSHttpRequest httpRequest, OSHttpResponse httpResponse, UUID textureID, string format)
  113. {
  114. // m_log.DebugFormat("[GETTEXTURE]: {0} with requested format {1}", textureID, format);
  115. AssetBase texture;
  116. string fullID = textureID.ToString();
  117. if (format != DefaultFormat)
  118. fullID = fullID + "-" + format;
  119. if (!String.IsNullOrEmpty(REDIRECT_URL))
  120. {
  121. // Only try to fetch locally cached textures. Misses are redirected
  122. texture = m_assetService.GetCached(fullID);
  123. if (texture != null)
  124. {
  125. if (texture.Type != (sbyte)AssetType.Texture)
  126. {
  127. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
  128. return true;
  129. }
  130. WriteTextureData(httpRequest, httpResponse, texture, format);
  131. }
  132. else
  133. {
  134. string textureUrl = REDIRECT_URL + textureID.ToString();
  135. m_log.Debug("[GETTEXTURE]: Redirecting texture request to " + textureUrl);
  136. httpResponse.RedirectLocation = textureUrl;
  137. return true;
  138. }
  139. }
  140. else // no redirect
  141. {
  142. // try the cache
  143. texture = m_assetService.GetCached(fullID);
  144. if (texture == null)
  145. {
  146. //m_log.DebugFormat("[GETTEXTURE]: texture was not in the cache");
  147. // Fetch locally or remotely. Misses return a 404
  148. texture = m_assetService.Get(textureID.ToString());
  149. if (texture != null)
  150. {
  151. if (texture.Type != (sbyte)AssetType.Texture)
  152. {
  153. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
  154. return true;
  155. }
  156. if (format == DefaultFormat)
  157. {
  158. WriteTextureData(httpRequest, httpResponse, texture, format);
  159. return true;
  160. }
  161. else
  162. {
  163. AssetBase newTexture = new AssetBase(texture.ID + "-" + format, texture.Name, (sbyte)AssetType.Texture, texture.Metadata.CreatorID);
  164. newTexture.Data = ConvertTextureData(texture, format);
  165. if (newTexture.Data.Length == 0)
  166. return false; // !!! Caller try another codec, please!
  167. newTexture.Flags = AssetFlags.Collectable;
  168. newTexture.Temporary = true;
  169. m_assetService.Store(newTexture);
  170. WriteTextureData(httpRequest, httpResponse, newTexture, format);
  171. return true;
  172. }
  173. }
  174. }
  175. else // it was on the cache
  176. {
  177. //m_log.DebugFormat("[GETTEXTURE]: texture was in the cache");
  178. WriteTextureData(httpRequest, httpResponse, texture, format);
  179. return true;
  180. }
  181. }
  182. // not found
  183. // m_log.Warn("[GETTEXTURE]: Texture " + textureID + " not found");
  184. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
  185. return true;
  186. }
  187. private void WriteTextureData(OSHttpRequest request, OSHttpResponse response, AssetBase texture, string format)
  188. {
  189. string range = request.Headers.GetOne("Range");
  190. //m_log.DebugFormat("[GETTEXTURE]: Range {0}", range);
  191. if (!String.IsNullOrEmpty(range)) // JP2's only
  192. {
  193. // Range request
  194. int start, end;
  195. if (TryParseRange(range, out start, out end))
  196. {
  197. // Before clamping start make sure we can satisfy it in order to avoid
  198. // sending back the last byte instead of an error status
  199. if (start >= texture.Data.Length)
  200. {
  201. response.StatusCode = (int)System.Net.HttpStatusCode.RequestedRangeNotSatisfiable;
  202. return;
  203. }
  204. end = Utils.Clamp(end, 0, texture.Data.Length - 1);
  205. start = Utils.Clamp(start, 0, end);
  206. int len = end - start + 1;
  207. //m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID);
  208. if (len < texture.Data.Length)
  209. response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent;
  210. response.ContentLength = len;
  211. response.ContentType = texture.Metadata.ContentType;
  212. response.AddHeader("Content-Range", String.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length));
  213. response.Body.Write(texture.Data, start, len);
  214. }
  215. else
  216. {
  217. m_log.Warn("[GETTEXTURE]: Malformed Range header: " + range);
  218. response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
  219. }
  220. }
  221. else // JP2's or other formats
  222. {
  223. // Full content request
  224. response.StatusCode = (int)System.Net.HttpStatusCode.OK;
  225. response.ContentLength = texture.Data.Length;
  226. if (format == DefaultFormat)
  227. response.ContentType = texture.Metadata.ContentType;
  228. else
  229. response.ContentType = "image/" + format;
  230. response.Body.Write(texture.Data, 0, texture.Data.Length);
  231. }
  232. }
  233. private bool TryParseRange(string header, out int start, out int end)
  234. {
  235. if (header.StartsWith("bytes="))
  236. {
  237. string[] rangeValues = header.Substring(6).Split('-');
  238. if (rangeValues.Length == 2)
  239. {
  240. if (Int32.TryParse(rangeValues[0], out start) && Int32.TryParse(rangeValues[1], out end))
  241. return true;
  242. }
  243. }
  244. start = end = 0;
  245. return false;
  246. }
  247. private byte[] ConvertTextureData(AssetBase texture, string format)
  248. {
  249. m_log.DebugFormat("[GETTEXTURE]: Converting texture {0} to {1}", texture.ID, format);
  250. byte[] data = new byte[0];
  251. MemoryStream imgstream = new MemoryStream();
  252. Bitmap mTexture = new Bitmap(1, 1);
  253. ManagedImage managedImage;
  254. Image image = (Image)mTexture;
  255. try
  256. {
  257. // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular data
  258. imgstream = new MemoryStream();
  259. // Decode image to System.Drawing.Image
  260. if (OpenJPEG.DecodeToImage(texture.Data, out managedImage, out image))
  261. {
  262. // Save to bitmap
  263. mTexture = new Bitmap(image);
  264. EncoderParameters myEncoderParameters = new EncoderParameters();
  265. myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
  266. // Save bitmap to stream
  267. ImageCodecInfo codec = GetEncoderInfo("image/" + format);
  268. if (codec != null)
  269. {
  270. mTexture.Save(imgstream, codec, myEncoderParameters);
  271. // Write the stream to a byte array for output
  272. data = imgstream.ToArray();
  273. }
  274. else
  275. m_log.WarnFormat("[GETTEXTURE]: No such codec {0}", format);
  276. }
  277. }
  278. catch (Exception e)
  279. {
  280. m_log.WarnFormat("[GETTEXTURE]: Unable to convert texture {0} to {1}: {2}", texture.ID, format, e.Message);
  281. }
  282. finally
  283. {
  284. // Reclaim memory, these are unmanaged resources
  285. // If we encountered an exception, one or more of these will be null
  286. if (mTexture != null)
  287. mTexture.Dispose();
  288. if (image != null)
  289. image.Dispose();
  290. if (imgstream != null)
  291. {
  292. imgstream.Close();
  293. imgstream.Dispose();
  294. }
  295. }
  296. return data;
  297. }
  298. // From msdn
  299. private static ImageCodecInfo GetEncoderInfo(String mimeType)
  300. {
  301. ImageCodecInfo[] encoders;
  302. encoders = ImageCodecInfo.GetImageEncoders();
  303. for (int j = 0; j < encoders.Length; ++j)
  304. {
  305. if (encoders[j].MimeType == mimeType)
  306. return encoders[j];
  307. }
  308. return null;
  309. }
  310. }
  311. }