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