GetTextureHandler.cs 14 KB

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