aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/ClientStack/Linden/Caps/GetTextureModule.cs
diff options
context:
space:
mode:
authorDiva Canto2011-04-30 13:24:25 -0700
committerDiva Canto2011-04-30 13:24:25 -0700
commite3c27d852720ad8b743952ab4aac3b2648468a11 (patch)
tree451ee0a3a17423089dc3b5346ca17121ea38e656 /OpenSim/Region/ClientStack/Linden/Caps/GetTextureModule.cs
parentMoved several cap-based-service-providing modules from where they were into a... (diff)
downloadopensim-SC-e3c27d852720ad8b743952ab4aac3b2648468a11.zip
opensim-SC-e3c27d852720ad8b743952ab4aac3b2648468a11.tar.gz
opensim-SC-e3c27d852720ad8b743952ab4aac3b2648468a11.tar.bz2
opensim-SC-e3c27d852720ad8b743952ab4aac3b2648468a11.tar.xz
Nope, that didn't feel right. Moving all those modules to Linden space.
Diffstat (limited to 'OpenSim/Region/ClientStack/Linden/Caps/GetTextureModule.cs')
-rw-r--r--OpenSim/Region/ClientStack/Linden/Caps/GetTextureModule.cs404
1 files changed, 404 insertions, 0 deletions
diff --git a/OpenSim/Region/ClientStack/Linden/Caps/GetTextureModule.cs b/OpenSim/Region/ClientStack/Linden/Caps/GetTextureModule.cs
new file mode 100644
index 0000000..58dbc14
--- /dev/null
+++ b/OpenSim/Region/ClientStack/Linden/Caps/GetTextureModule.cs
@@ -0,0 +1,404 @@
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
28using System;
29using System.Collections;
30using System.Collections.Specialized;
31using System.Drawing;
32using System.Drawing.Imaging;
33using System.Reflection;
34using System.IO;
35using System.Web;
36using log4net;
37using Nini.Config;
38using Mono.Addins;
39using OpenMetaverse;
40using OpenMetaverse.StructuredData;
41using OpenMetaverse.Imaging;
42using OpenSim.Framework;
43using OpenSim.Framework.Servers;
44using OpenSim.Framework.Servers.HttpServer;
45using OpenSim.Region.Framework.Interfaces;
46using OpenSim.Region.Framework.Scenes;
47using OpenSim.Services.Interfaces;
48using Caps = OpenSim.Framework.Capabilities.Caps;
49
50namespace OpenSim.Region.ClientStack.Linden
51{
52 #region Stream Handler
53
54 public delegate byte[] StreamHandlerCallback(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse);
55
56 public class StreamHandler : BaseStreamHandler
57 {
58 StreamHandlerCallback m_callback;
59
60 public StreamHandler(string httpMethod, string path, StreamHandlerCallback callback)
61 : base(httpMethod, path)
62 {
63 m_callback = callback;
64 }
65
66 public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
67 {
68 return m_callback(path, request, httpRequest, httpResponse);
69 }
70 }
71
72 #endregion Stream Handler
73
74 [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
75 public class GetTextureModule : IRegionModule
76 {
77 private static readonly ILog m_log =
78 LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
79 private Scene m_scene;
80 private IAssetService m_assetService;
81
82 public const string DefaultFormat = "x-j2c";
83
84 // TODO: Change this to a config option
85 const string REDIRECT_URL = null;
86
87
88 #region IRegionModule Members
89
90 public void Initialise(Scene pScene, IConfigSource pSource)
91 {
92 m_scene = pScene;
93 }
94
95 public void PostInitialise()
96 {
97 m_assetService = m_scene.RequestModuleInterface<IAssetService>();
98 m_scene.EventManager.OnRegisterCaps += RegisterCaps;
99 }
100
101 public void Close() { }
102
103 public string Name { get { return "GetTextureModule"; } }
104 public bool IsSharedModule { get { return false; } }
105
106 public void RegisterCaps(UUID agentID, Caps caps)
107 {
108 UUID capID = UUID.Random();
109
110// m_log.InfoFormat("[GETTEXTURE]: /CAPS/{0} in region {1}", capID, m_scene.RegionInfo.RegionName);
111 caps.RegisterHandler("GetTexture", new StreamHandler("GET", "/CAPS/" + capID, ProcessGetTexture));
112 }
113
114 #endregion
115
116 private byte[] ProcessGetTexture(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
117 {
118 //m_log.DebugFormat("[GETTEXTURE]: called in {0}", m_scene.RegionInfo.RegionName);
119
120 // Try to parse the texture ID from the request URL
121 NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);
122 string textureStr = query.GetOne("texture_id");
123 string format = query.GetOne("format");
124
125 if (m_assetService == null)
126 {
127 m_log.Error("[GETTEXTURE]: Cannot fetch texture " + textureStr + " without an asset service");
128 httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
129 return null;
130 }
131
132 UUID textureID;
133 if (!String.IsNullOrEmpty(textureStr) && UUID.TryParse(textureStr, out textureID))
134 {
135 string[] formats;
136 if (format != null && format != string.Empty)
137 {
138 formats = new string[1] { format.ToLower() };
139 }
140 else
141 {
142 formats = WebUtil.GetPreferredImageTypes(httpRequest.Headers.Get("Accept"));
143 if (formats.Length == 0)
144 formats = new string[1] { DefaultFormat }; // default
145
146 }
147 // OK, we have an array with preferred formats, possibly with only one entry
148
149 httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
150 foreach (string f in formats)
151 {
152 if (FetchTexture(httpRequest, httpResponse, textureID, f))
153 break;
154 }
155
156 }
157 else
158 {
159 m_log.Warn("[GETTEXTURE]: Failed to parse a texture_id from GetTexture request: " + httpRequest.Url);
160 }
161
162 httpResponse.Send();
163 return null;
164 }
165
166 /// <summary>
167 ///
168 /// </summary>
169 /// <param name="httpRequest"></param>
170 /// <param name="httpResponse"></param>
171 /// <param name="textureID"></param>
172 /// <param name="format"></param>
173 /// <returns>False for "caller try another codec"; true otherwise</returns>
174 private bool FetchTexture(OSHttpRequest httpRequest, OSHttpResponse httpResponse, UUID textureID, string format)
175 {
176// m_log.DebugFormat("[GETTEXTURE]: {0} with requested format {1}", textureID, format);
177 AssetBase texture;
178
179 string fullID = textureID.ToString();
180 if (format != DefaultFormat)
181 fullID = fullID + "-" + format;
182
183 if (!String.IsNullOrEmpty(REDIRECT_URL))
184 {
185 // Only try to fetch locally cached textures. Misses are redirected
186 texture = m_assetService.GetCached(fullID);
187
188 if (texture != null)
189 {
190 if (texture.Type != (sbyte)AssetType.Texture)
191 {
192 httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
193 return true;
194 }
195 WriteTextureData(httpRequest, httpResponse, texture, format);
196 }
197 else
198 {
199 string textureUrl = REDIRECT_URL + textureID.ToString();
200 m_log.Debug("[GETTEXTURE]: Redirecting texture request to " + textureUrl);
201 httpResponse.RedirectLocation = textureUrl;
202 return true;
203 }
204 }
205 else // no redirect
206 {
207 // try the cache
208 texture = m_assetService.GetCached(fullID);
209
210 if (texture == null)
211 {
212 //m_log.DebugFormat("[GETTEXTURE]: texture was not in the cache");
213
214 // Fetch locally or remotely. Misses return a 404
215 texture = m_assetService.Get(textureID.ToString());
216
217 if (texture != null)
218 {
219 if (texture.Type != (sbyte)AssetType.Texture)
220 {
221 httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
222 return true;
223 }
224 if (format == DefaultFormat)
225 {
226 WriteTextureData(httpRequest, httpResponse, texture, format);
227 return true;
228 }
229 else
230 {
231 AssetBase newTexture = new AssetBase(texture.ID + "-" + format, texture.Name, (sbyte)AssetType.Texture, texture.Metadata.CreatorID);
232 newTexture.Data = ConvertTextureData(texture, format);
233 if (newTexture.Data.Length == 0)
234 return false; // !!! Caller try another codec, please!
235
236 newTexture.Flags = AssetFlags.Collectable;
237 newTexture.Temporary = true;
238 m_assetService.Store(newTexture);
239 WriteTextureData(httpRequest, httpResponse, newTexture, format);
240 return true;
241 }
242 }
243 }
244 else // it was on the cache
245 {
246 //m_log.DebugFormat("[GETTEXTURE]: texture was in the cache");
247 WriteTextureData(httpRequest, httpResponse, texture, format);
248 return true;
249 }
250 }
251
252 // not found
253// m_log.Warn("[GETTEXTURE]: Texture " + textureID + " not found");
254 httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
255 return true;
256 }
257
258 private void WriteTextureData(OSHttpRequest request, OSHttpResponse response, AssetBase texture, string format)
259 {
260 string range = request.Headers.GetOne("Range");
261 //m_log.DebugFormat("[GETTEXTURE]: Range {0}", range);
262 if (!String.IsNullOrEmpty(range)) // JP2's only
263 {
264 // Range request
265 int start, end;
266 if (TryParseRange(range, out start, out end))
267 {
268 // Before clamping start make sure we can satisfy it in order to avoid
269 // sending back the last byte instead of an error status
270 if (start >= texture.Data.Length)
271 {
272 response.StatusCode = (int)System.Net.HttpStatusCode.RequestedRangeNotSatisfiable;
273 return;
274 }
275
276 end = Utils.Clamp(end, 0, texture.Data.Length - 1);
277 start = Utils.Clamp(start, 0, end);
278 int len = end - start + 1;
279
280 //m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID);
281
282 if (len < texture.Data.Length)
283 response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent;
284
285 response.ContentLength = len;
286 response.ContentType = texture.Metadata.ContentType;
287 response.AddHeader("Content-Range", String.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length));
288
289 response.Body.Write(texture.Data, start, len);
290 }
291 else
292 {
293 m_log.Warn("[GETTEXTURE]: Malformed Range header: " + range);
294 response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
295 }
296 }
297 else // JP2's or other formats
298 {
299 // Full content request
300 response.StatusCode = (int)System.Net.HttpStatusCode.OK;
301 response.ContentLength = texture.Data.Length;
302 if (format == DefaultFormat)
303 response.ContentType = texture.Metadata.ContentType;
304 else
305 response.ContentType = "image/" + format;
306 response.Body.Write(texture.Data, 0, texture.Data.Length);
307 }
308 }
309
310 private bool TryParseRange(string header, out int start, out int end)
311 {
312 if (header.StartsWith("bytes="))
313 {
314 string[] rangeValues = header.Substring(6).Split('-');
315 if (rangeValues.Length == 2)
316 {
317 if (Int32.TryParse(rangeValues[0], out start) && Int32.TryParse(rangeValues[1], out end))
318 return true;
319 }
320 }
321
322 start = end = 0;
323 return false;
324 }
325
326
327 private byte[] ConvertTextureData(AssetBase texture, string format)
328 {
329 m_log.DebugFormat("[GETTEXTURE]: Converting texture {0} to {1}", texture.ID, format);
330 byte[] data = new byte[0];
331
332 MemoryStream imgstream = new MemoryStream();
333 Bitmap mTexture = new Bitmap(1, 1);
334 ManagedImage managedImage;
335 Image image = (Image)mTexture;
336
337 try
338 {
339 // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular data
340
341 imgstream = new MemoryStream();
342
343 // Decode image to System.Drawing.Image
344 if (OpenJPEG.DecodeToImage(texture.Data, out managedImage, out image))
345 {
346 // Save to bitmap
347 mTexture = new Bitmap(image);
348
349 EncoderParameters myEncoderParameters = new EncoderParameters();
350 myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
351
352 // Save bitmap to stream
353 ImageCodecInfo codec = GetEncoderInfo("image/" + format);
354 if (codec != null)
355 {
356 mTexture.Save(imgstream, codec, myEncoderParameters);
357 // Write the stream to a byte array for output
358 data = imgstream.ToArray();
359 }
360 else
361 m_log.WarnFormat("[GETTEXTURE]: No such codec {0}", format);
362
363 }
364 }
365 catch (Exception e)
366 {
367 m_log.WarnFormat("[GETTEXTURE]: Unable to convert texture {0} to {1}: {2}", texture.ID, format, e.Message);
368 }
369 finally
370 {
371 // Reclaim memory, these are unmanaged resources
372 // If we encountered an exception, one or more of these will be null
373 if (mTexture != null)
374 mTexture.Dispose();
375
376 if (image != null)
377 image.Dispose();
378
379 if (imgstream != null)
380 {
381 imgstream.Close();
382 imgstream.Dispose();
383 }
384 }
385
386 return data;
387 }
388
389 // From msdn
390 private static ImageCodecInfo GetEncoderInfo(String mimeType)
391 {
392 ImageCodecInfo[] encoders;
393 encoders = ImageCodecInfo.GetImageEncoders();
394 for (int j = 0; j < encoders.Length; ++j)
395 {
396 if (encoders[j].MimeType == mimeType)
397 return encoders[j];
398 }
399 return null;
400 }
401
402
403 }
404}