diff options
Diffstat (limited to 'OpenSim/Capabilities/Handlers/GetTexture')
4 files changed, 531 insertions, 140 deletions
diff --git a/OpenSim/Capabilities/Handlers/GetTexture/GetTextureHandler.cs b/OpenSim/Capabilities/Handlers/GetTexture/GetTextureHandler.cs index 828e943..e73cf9e 100644 --- a/OpenSim/Capabilities/Handlers/GetTexture/GetTextureHandler.cs +++ b/OpenSim/Capabilities/Handlers/GetTexture/GetTextureHandler.cs | |||
@@ -47,46 +47,43 @@ using Caps = OpenSim.Framework.Capabilities.Caps; | |||
47 | 47 | ||
48 | namespace OpenSim.Capabilities.Handlers | 48 | namespace OpenSim.Capabilities.Handlers |
49 | { | 49 | { |
50 | public class GetTextureHandler : BaseStreamHandler | 50 | public class GetTextureHandler |
51 | { | 51 | { |
52 | private static readonly ILog m_log = | 52 | private static readonly ILog m_log = |
53 | LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); | 53 | LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); |
54 | |||
54 | private IAssetService m_assetService; | 55 | private IAssetService m_assetService; |
55 | 56 | ||
56 | public const string DefaultFormat = "x-j2c"; | 57 | public const string DefaultFormat = "x-j2c"; |
57 | 58 | ||
58 | // TODO: Change this to a config option | 59 | public GetTextureHandler(IAssetService assService) |
59 | private string m_RedirectURL = null; | ||
60 | |||
61 | public GetTextureHandler(string path, IAssetService assService, string name, string description, string redirectURL) | ||
62 | : base("GET", path, name, description) | ||
63 | { | 60 | { |
64 | m_assetService = assService; | 61 | m_assetService = assService; |
65 | m_RedirectURL = redirectURL; | ||
66 | if (m_RedirectURL != null && !m_RedirectURL.EndsWith("/")) | ||
67 | m_RedirectURL += "/"; | ||
68 | } | 62 | } |
69 | 63 | ||
70 | protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) | 64 | public Hashtable Handle(Hashtable request) |
71 | { | 65 | { |
72 | // Try to parse the texture ID from the request URL | 66 | Hashtable ret = new Hashtable(); |
73 | NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query); | 67 | ret["int_response_code"] = (int)System.Net.HttpStatusCode.NotFound; |
74 | string textureStr = query.GetOne("texture_id"); | 68 | ret["content_type"] = "text/plain"; |
75 | string format = query.GetOne("format"); | 69 | ret["keepalive"] = false; |
70 | ret["reusecontext"] = false; | ||
71 | ret["int_bytes"] = 0; | ||
72 | string textureStr = (string)request["texture_id"]; | ||
73 | string format = (string)request["format"]; | ||
76 | 74 | ||
77 | //m_log.DebugFormat("[GETTEXTURE]: called {0}", textureStr); | 75 | //m_log.DebugFormat("[GETTEXTURE]: called {0}", textureStr); |
78 | 76 | ||
79 | if (m_assetService == null) | 77 | if (m_assetService == null) |
80 | { | 78 | { |
81 | m_log.Error("[GETTEXTURE]: Cannot fetch texture " + textureStr + " without an asset service"); | 79 | m_log.Error("[GETTEXTURE]: Cannot fetch texture " + textureStr + " without an asset service"); |
82 | httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; | ||
83 | } | 80 | } |
84 | 81 | ||
85 | UUID textureID; | 82 | UUID textureID; |
86 | if (!String.IsNullOrEmpty(textureStr) && UUID.TryParse(textureStr, out textureID)) | 83 | if (!String.IsNullOrEmpty(textureStr) && UUID.TryParse(textureStr, out textureID)) |
87 | { | 84 | { |
88 | // m_log.DebugFormat("[GETTEXTURE]: Received request for texture id {0}", textureID); | 85 | // m_log.DebugFormat("[GETTEXTURE]: Received request for texture id {0}", textureID); |
89 | 86 | ||
90 | string[] formats; | 87 | string[] formats; |
91 | if (!string.IsNullOrEmpty(format)) | 88 | if (!string.IsNullOrEmpty(format)) |
92 | { | 89 | { |
@@ -94,41 +91,52 @@ namespace OpenSim.Capabilities.Handlers | |||
94 | } | 91 | } |
95 | else | 92 | else |
96 | { | 93 | { |
97 | formats = WebUtil.GetPreferredImageTypes(httpRequest.Headers.Get("Accept")); | 94 | formats = new string[1] { DefaultFormat }; // default |
95 | if (((Hashtable)request["headers"])["Accept"] != null) | ||
96 | formats = WebUtil.GetPreferredImageTypes((string)((Hashtable)request["headers"])["Accept"]); | ||
98 | if (formats.Length == 0) | 97 | if (formats.Length == 0) |
99 | formats = new string[1] { DefaultFormat }; // default | 98 | formats = new string[1] { DefaultFormat }; // default |
100 | 99 | ||
101 | } | 100 | } |
102 | // OK, we have an array with preferred formats, possibly with only one entry | 101 | // OK, we have an array with preferred formats, possibly with only one entry |
103 | 102 | bool foundtexture = false; | |
104 | httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; | ||
105 | foreach (string f in formats) | 103 | foreach (string f in formats) |
106 | { | 104 | { |
107 | if (FetchTexture(httpRequest, httpResponse, textureID, f)) | 105 | foundtexture = FetchTexture(request, ret, textureID, f); |
106 | if (foundtexture) | ||
108 | break; | 107 | break; |
109 | } | 108 | } |
109 | if (!foundtexture) | ||
110 | { | ||
111 | ret["int_response_code"] = 404; | ||
112 | ret["error_status_text"] = "not found"; | ||
113 | ret["str_response_string"] = "not found"; | ||
114 | ret["content_type"] = "text/plain"; | ||
115 | ret["keepalive"] = false; | ||
116 | ret["reusecontext"] = false; | ||
117 | ret["int_bytes"] = 0; | ||
118 | } | ||
110 | } | 119 | } |
111 | else | 120 | else |
112 | { | 121 | { |
113 | m_log.Warn("[GETTEXTURE]: Failed to parse a texture_id from GetTexture request: " + httpRequest.Url); | 122 | m_log.Warn("[GETTEXTURE]: Failed to parse a texture_id from GetTexture request: " + (string)request["uri"]); |
114 | } | 123 | } |
115 | 124 | ||
116 | // m_log.DebugFormat( | 125 | // m_log.DebugFormat( |
117 | // "[GETTEXTURE]: For texture {0} sending back response {1}, data length {2}", | 126 | // "[GETTEXTURE]: For texture {0} sending back response {1}, data length {2}", |
118 | // textureID, httpResponse.StatusCode, httpResponse.ContentLength); | 127 | // textureID, httpResponse.StatusCode, httpResponse.ContentLength); |
119 | 128 | return ret; | |
120 | return null; | ||
121 | } | 129 | } |
122 | 130 | ||
123 | /// <summary> | 131 | /// <summary> |
124 | /// | 132 | /// |
125 | /// </summary> | 133 | /// </summary> |
126 | /// <param name="httpRequest"></param> | 134 | /// <param name="httpRequest"></param> |
127 | /// <param name="httpResponse"></param> | 135 | /// <param name="httpResponse"></param> |
128 | /// <param name="textureID"></param> | 136 | /// <param name="textureID"></param> |
129 | /// <param name="format"></param> | 137 | /// <param name="format"></param> |
130 | /// <returns>False for "caller try another codec"; true otherwise</returns> | 138 | /// <returns>False for "caller try another codec"; true otherwise</returns> |
131 | private bool FetchTexture(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, UUID textureID, string format) | 139 | private bool FetchTexture(Hashtable request, Hashtable response, UUID textureID, string format) |
132 | { | 140 | { |
133 | // m_log.DebugFormat("[GETTEXTURE]: {0} with requested format {1}", textureID, format); | 141 | // m_log.DebugFormat("[GETTEXTURE]: {0} with requested format {1}", textureID, format); |
134 | AssetBase texture; | 142 | AssetBase texture; |
@@ -137,86 +145,70 @@ namespace OpenSim.Capabilities.Handlers | |||
137 | if (format != DefaultFormat) | 145 | if (format != DefaultFormat) |
138 | fullID = fullID + "-" + format; | 146 | fullID = fullID + "-" + format; |
139 | 147 | ||
140 | if (!String.IsNullOrEmpty(m_RedirectURL)) | 148 | // try the cache |
149 | texture = m_assetService.GetCached(fullID); | ||
150 | |||
151 | if (texture == null) | ||
141 | { | 152 | { |
142 | // Only try to fetch locally cached textures. Misses are redirected | 153 | //m_log.DebugFormat("[GETTEXTURE]: texture was not in the cache"); |
143 | texture = m_assetService.GetCached(fullID); | 154 | |
155 | // Fetch locally or remotely. Misses return a 404 | ||
156 | texture = m_assetService.Get(textureID.ToString()); | ||
144 | 157 | ||
145 | if (texture != null) | 158 | if (texture != null) |
146 | { | 159 | { |
147 | if (texture.Type != (sbyte)AssetType.Texture) | 160 | if (texture.Type != (sbyte)AssetType.Texture) |
161 | return true; | ||
162 | |||
163 | if (format == DefaultFormat) | ||
148 | { | 164 | { |
149 | httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; | 165 | WriteTextureData(request, response, texture, format); |
166 | return true; | ||
167 | } | ||
168 | else | ||
169 | { | ||
170 | AssetBase newTexture = new AssetBase(texture.ID + "-" + format, texture.Name, (sbyte)AssetType.Texture, texture.Metadata.CreatorID); | ||
171 | newTexture.Data = ConvertTextureData(texture, format); | ||
172 | if (newTexture.Data.Length == 0) | ||
173 | return false; // !!! Caller try another codec, please! | ||
174 | |||
175 | newTexture.Flags = AssetFlags.Collectable; | ||
176 | newTexture.Temporary = true; | ||
177 | newTexture.Local = true; | ||
178 | m_assetService.Store(newTexture); | ||
179 | WriteTextureData(request, response, newTexture, format); | ||
150 | return true; | 180 | return true; |
151 | } | 181 | } |
152 | WriteTextureData(httpRequest, httpResponse, texture, format); | ||
153 | } | ||
154 | else | ||
155 | { | ||
156 | string textureUrl = m_RedirectURL + "?texture_id="+ textureID.ToString(); | ||
157 | m_log.Debug("[GETTEXTURE]: Redirecting texture request to " + textureUrl); | ||
158 | httpResponse.StatusCode = (int)OSHttpStatusCode.RedirectMovedPermanently; | ||
159 | httpResponse.RedirectLocation = textureUrl; | ||
160 | return true; | ||
161 | } | 182 | } |
162 | } | 183 | } |
163 | else // no redirect | 184 | else // it was on the cache |
164 | { | 185 | { |
165 | // try the cache | 186 | //m_log.DebugFormat("[GETTEXTURE]: texture was in the cache"); |
166 | texture = m_assetService.GetCached(fullID); | 187 | WriteTextureData(request, response, texture, format); |
188 | return true; | ||
189 | } | ||
167 | 190 | ||
168 | if (texture == null) | 191 | //response = new Hashtable(); |
169 | { | ||
170 | // m_log.DebugFormat("[GETTEXTURE]: texture was not in the cache"); | ||
171 | |||
172 | // Fetch locally or remotely. Misses return a 404 | ||
173 | texture = m_assetService.Get(textureID.ToString()); | ||
174 | 192 | ||
175 | if (texture != null) | ||
176 | { | ||
177 | if (texture.Type != (sbyte)AssetType.Texture) | ||
178 | { | ||
179 | httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; | ||
180 | return true; | ||
181 | } | ||
182 | if (format == DefaultFormat) | ||
183 | { | ||
184 | WriteTextureData(httpRequest, httpResponse, texture, format); | ||
185 | return true; | ||
186 | } | ||
187 | else | ||
188 | { | ||
189 | AssetBase newTexture = new AssetBase(texture.ID + "-" + format, texture.Name, (sbyte)AssetType.Texture, texture.Metadata.CreatorID); | ||
190 | newTexture.Data = ConvertTextureData(texture, format); | ||
191 | if (newTexture.Data.Length == 0) | ||
192 | return false; // !!! Caller try another codec, please! | ||
193 | |||
194 | newTexture.Flags = AssetFlags.Collectable; | ||
195 | newTexture.Temporary = true; | ||
196 | newTexture.Local = true; | ||
197 | m_assetService.Store(newTexture); | ||
198 | WriteTextureData(httpRequest, httpResponse, newTexture, format); | ||
199 | return true; | ||
200 | } | ||
201 | } | ||
202 | } | ||
203 | else // it was on the cache | ||
204 | { | ||
205 | // m_log.DebugFormat("[GETTEXTURE]: texture was in the cache"); | ||
206 | WriteTextureData(httpRequest, httpResponse, texture, format); | ||
207 | return true; | ||
208 | } | ||
209 | } | ||
210 | 193 | ||
194 | //WriteTextureData(request,response,null,format); | ||
211 | // not found | 195 | // not found |
212 | // m_log.Warn("[GETTEXTURE]: Texture " + textureID + " not found"); | 196 | //m_log.Warn("[GETTEXTURE]: Texture " + textureID + " not found"); |
213 | httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; | 197 | return false; |
214 | return true; | ||
215 | } | 198 | } |
216 | 199 | ||
217 | private void WriteTextureData(IOSHttpRequest request, IOSHttpResponse response, AssetBase texture, string format) | 200 | private void WriteTextureData(Hashtable request, Hashtable response, AssetBase texture, string format) |
218 | { | 201 | { |
219 | string range = request.Headers.GetOne("Range"); | 202 | Hashtable headers = new Hashtable(); |
203 | response["headers"] = headers; | ||
204 | |||
205 | string range = String.Empty; | ||
206 | |||
207 | if (((Hashtable)request["headers"])["range"] != null) | ||
208 | range = (string)((Hashtable)request["headers"])["range"]; | ||
209 | |||
210 | else if (((Hashtable)request["headers"])["Range"] != null) | ||
211 | range = (string)((Hashtable)request["headers"])["Range"]; | ||
220 | 212 | ||
221 | if (!String.IsNullOrEmpty(range)) // JP2's only | 213 | if (!String.IsNullOrEmpty(range)) // JP2's only |
222 | { | 214 | { |
@@ -244,10 +236,8 @@ namespace OpenSim.Capabilities.Handlers | |||
244 | // However, if we return PartialContent (or OK) instead, the viewer will display that resolution. | 236 | // However, if we return PartialContent (or OK) instead, the viewer will display that resolution. |
245 | 237 | ||
246 | // response.StatusCode = (int)System.Net.HttpStatusCode.RequestedRangeNotSatisfiable; | 238 | // response.StatusCode = (int)System.Net.HttpStatusCode.RequestedRangeNotSatisfiable; |
247 | // response.AddHeader("Content-Range", String.Format("bytes */{0}", texture.Data.Length)); | 239 | // viewers don't seem to handle RequestedRangeNotSatisfiable and keep retrying with same parameters |
248 | // response.StatusCode = (int)System.Net.HttpStatusCode.OK; | 240 | response["int_response_code"] = (int)System.Net.HttpStatusCode.NotFound; |
249 | response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent; | ||
250 | response.ContentType = texture.Metadata.ContentType; | ||
251 | } | 241 | } |
252 | else | 242 | else |
253 | { | 243 | { |
@@ -262,41 +252,46 @@ namespace OpenSim.Capabilities.Handlers | |||
262 | 252 | ||
263 | // m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID); | 253 | // m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID); |
264 | 254 | ||
265 | // Always return PartialContent, even if the range covered the entire data length | 255 | response["content-type"] = texture.Metadata.ContentType; |
266 | // We were accidentally sending back 404 before in this situation | 256 | |
267 | // https://issues.apache.org/bugzilla/show_bug.cgi?id=51878 supports sending 206 even if the | 257 | if (start == 0 && len == texture.Data.Length) // well redudante maybe |
268 | // entire range is requested, and viewer 3.2.2 (and very probably earlier) seems fine with this. | 258 | { |
269 | // | 259 | response["int_response_code"] = (int)System.Net.HttpStatusCode.OK; |
270 | // We also do not want to send back OK even if the whole range was satisfiable since this causes | 260 | response["bin_response_data"] = texture.Data; |
271 | // HTTP textures on at least Imprudence 1.4.0-beta2 to never display the final texture quality. | 261 | response["int_bytes"] = texture.Data.Length; |
272 | // if (end > maxEnd) | 262 | } |
273 | // response.StatusCode = (int)System.Net.HttpStatusCode.OK; | 263 | else |
274 | // else | 264 | { |
275 | response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent; | 265 | response["int_response_code"] = (int)System.Net.HttpStatusCode.PartialContent; |
276 | 266 | headers["Content-Range"] = String.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length); | |
277 | response.ContentLength = len; | 267 | |
278 | response.ContentType = texture.Metadata.ContentType; | 268 | byte[] d = new byte[len]; |
279 | response.AddHeader("Content-Range", String.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length)); | 269 | Array.Copy(texture.Data, start, d, 0, len); |
280 | 270 | response["bin_response_data"] = d; | |
281 | response.Body.Write(texture.Data, start, len); | 271 | response["int_bytes"] = len; |
272 | } | ||
273 | // response.Body.Write(texture.Data, start, len); | ||
282 | } | 274 | } |
283 | } | 275 | } |
284 | else | 276 | else |
285 | { | 277 | { |
286 | m_log.Warn("[GETTEXTURE]: Malformed Range header: " + range); | 278 | m_log.Warn("[GETTEXTURE]: Malformed Range header: " + range); |
287 | response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; | 279 | response["int_response_code"] = (int)System.Net.HttpStatusCode.BadRequest; |
288 | } | 280 | } |
289 | } | 281 | } |
290 | else // JP2's or other formats | 282 | else // JP2's or other formats |
291 | { | 283 | { |
292 | // Full content request | 284 | // Full content request |
293 | response.StatusCode = (int)System.Net.HttpStatusCode.OK; | 285 | response["int_response_code"] = (int)System.Net.HttpStatusCode.OK; |
294 | response.ContentLength = texture.Data.Length; | ||
295 | if (format == DefaultFormat) | 286 | if (format == DefaultFormat) |
296 | response.ContentType = texture.Metadata.ContentType; | 287 | response["content_type"] = texture.Metadata.ContentType; |
297 | else | 288 | else |
298 | response.ContentType = "image/" + format; | 289 | response["content_type"] = "image/" + format; |
299 | response.Body.Write(texture.Data, 0, texture.Data.Length); | 290 | |
291 | response["bin_response_data"] = texture.Data; | ||
292 | response["int_bytes"] = texture.Data.Length; | ||
293 | |||
294 | // response.Body.Write(texture.Data, 0, texture.Data.Length); | ||
300 | } | 295 | } |
301 | 296 | ||
302 | // if (response.StatusCode < 200 || response.StatusCode > 299) | 297 | // if (response.StatusCode < 200 || response.StatusCode > 299) |
@@ -359,36 +354,35 @@ namespace OpenSim.Capabilities.Handlers | |||
359 | byte[] data = new byte[0]; | 354 | byte[] data = new byte[0]; |
360 | 355 | ||
361 | MemoryStream imgstream = new MemoryStream(); | 356 | MemoryStream imgstream = new MemoryStream(); |
362 | Bitmap mTexture = new Bitmap(1, 1); | 357 | Bitmap mTexture = null; |
363 | ManagedImage managedImage; | 358 | ManagedImage managedImage = null; |
364 | Image image = (Image)mTexture; | 359 | Image image = null; |
365 | 360 | ||
366 | try | 361 | try |
367 | { | 362 | { |
368 | // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular data | 363 | // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular data |
369 | 364 | ||
370 | imgstream = new MemoryStream(); | ||
371 | |||
372 | // Decode image to System.Drawing.Image | 365 | // Decode image to System.Drawing.Image |
373 | if (OpenJPEG.DecodeToImage(texture.Data, out managedImage, out image)) | 366 | if (OpenJPEG.DecodeToImage(texture.Data, out managedImage, out image) && image != null) |
374 | { | 367 | { |
375 | // Save to bitmap | 368 | // Save to bitmap |
376 | mTexture = new Bitmap(image); | 369 | mTexture = new Bitmap(image); |
377 | 370 | ||
378 | EncoderParameters myEncoderParameters = new EncoderParameters(); | 371 | using(EncoderParameters myEncoderParameters = new EncoderParameters()) |
379 | myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L); | ||
380 | |||
381 | // Save bitmap to stream | ||
382 | ImageCodecInfo codec = GetEncoderInfo("image/" + format); | ||
383 | if (codec != null) | ||
384 | { | 372 | { |
385 | mTexture.Save(imgstream, codec, myEncoderParameters); | 373 | myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality,95L); |
374 | |||
375 | // Save bitmap to stream | ||
376 | ImageCodecInfo codec = GetEncoderInfo("image/" + format); | ||
377 | if (codec != null) | ||
378 | { | ||
379 | mTexture.Save(imgstream, codec, myEncoderParameters); | ||
386 | // Write the stream to a byte array for output | 380 | // Write the stream to a byte array for output |
387 | data = imgstream.ToArray(); | 381 | data = imgstream.ToArray(); |
382 | } | ||
383 | else | ||
384 | m_log.WarnFormat("[GETTEXTURE]: No such codec {0}", format); | ||
388 | } | 385 | } |
389 | else | ||
390 | m_log.WarnFormat("[GETTEXTURE]: No such codec {0}", format); | ||
391 | |||
392 | } | 386 | } |
393 | } | 387 | } |
394 | catch (Exception e) | 388 | catch (Exception e) |
@@ -405,11 +399,10 @@ namespace OpenSim.Capabilities.Handlers | |||
405 | if (image != null) | 399 | if (image != null) |
406 | image.Dispose(); | 400 | image.Dispose(); |
407 | 401 | ||
402 | if(managedImage != null) | ||
403 | managedImage.Clear(); | ||
408 | if (imgstream != null) | 404 | if (imgstream != null) |
409 | { | ||
410 | imgstream.Close(); | ||
411 | imgstream.Dispose(); | 405 | imgstream.Dispose(); |
412 | } | ||
413 | } | 406 | } |
414 | 407 | ||
415 | return data; | 408 | return data; |
@@ -428,4 +421,4 @@ namespace OpenSim.Capabilities.Handlers | |||
428 | return null; | 421 | return null; |
429 | } | 422 | } |
430 | } | 423 | } |
431 | } \ No newline at end of file | 424 | } |
diff --git a/OpenSim/Capabilities/Handlers/GetTexture/GetTextureRobustHandler.cs b/OpenSim/Capabilities/Handlers/GetTexture/GetTextureRobustHandler.cs new file mode 100644 index 0000000..0685c5e --- /dev/null +++ b/OpenSim/Capabilities/Handlers/GetTexture/GetTextureRobustHandler.cs | |||
@@ -0,0 +1,394 @@ | |||
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 | |||
28 | using System; | ||
29 | using System.Collections; | ||
30 | using System.Collections.Specialized; | ||
31 | using System.Drawing; | ||
32 | using System.Drawing.Imaging; | ||
33 | using System.Reflection; | ||
34 | using System.IO; | ||
35 | using System.Web; | ||
36 | using log4net; | ||
37 | using Nini.Config; | ||
38 | using OpenMetaverse; | ||
39 | using OpenMetaverse.StructuredData; | ||
40 | using OpenMetaverse.Imaging; | ||
41 | using OpenSim.Framework; | ||
42 | using OpenSim.Framework.Servers; | ||
43 | using OpenSim.Framework.Servers.HttpServer; | ||
44 | using OpenSim.Region.Framework.Interfaces; | ||
45 | using OpenSim.Services.Interfaces; | ||
46 | using Caps = OpenSim.Framework.Capabilities.Caps; | ||
47 | |||
48 | namespace OpenSim.Capabilities.Handlers | ||
49 | { | ||
50 | public class GetTextureRobustHandler : BaseStreamHandler | ||
51 | { | ||
52 | private static readonly ILog m_log = | ||
53 | LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); | ||
54 | private IAssetService m_assetService; | ||
55 | |||
56 | public const string DefaultFormat = "x-j2c"; | ||
57 | |||
58 | // TODO: Change this to a config option | ||
59 | private string m_RedirectURL = null; | ||
60 | |||
61 | public GetTextureRobustHandler(string path, IAssetService assService, string name, string description, string redirectURL) | ||
62 | : base("GET", path, name, description) | ||
63 | { | ||
64 | m_assetService = assService; | ||
65 | m_RedirectURL = redirectURL; | ||
66 | if (m_RedirectURL != null && !m_RedirectURL.EndsWith("/")) | ||
67 | m_RedirectURL += "/"; | ||
68 | } | ||
69 | |||
70 | protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) | ||
71 | { | ||
72 | // Try to parse the texture ID from the request URL | ||
73 | NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query); | ||
74 | string textureStr = query.GetOne("texture_id"); | ||
75 | string format = query.GetOne("format"); | ||
76 | |||
77 | //m_log.DebugFormat("[GETTEXTURE]: called {0}", textureStr); | ||
78 | |||
79 | if (m_assetService == null) | ||
80 | { | ||
81 | m_log.Error("[GETTEXTURE]: Cannot fetch texture " + textureStr + " without an asset service"); | ||
82 | httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; | ||
83 | return null; | ||
84 | } | ||
85 | |||
86 | UUID textureID; | ||
87 | if (!String.IsNullOrEmpty(textureStr) && UUID.TryParse(textureStr, out textureID)) | ||
88 | { | ||
89 | // m_log.DebugFormat("[GETTEXTURE]: Received request for texture id {0}", textureID); | ||
90 | |||
91 | string[] formats; | ||
92 | if (!string.IsNullOrEmpty(format)) | ||
93 | { | ||
94 | formats = new string[1] { format.ToLower() }; | ||
95 | } | ||
96 | else | ||
97 | { | ||
98 | formats = WebUtil.GetPreferredImageTypes(httpRequest.Headers.Get("Accept")); | ||
99 | if (formats.Length == 0) | ||
100 | formats = new string[1] { DefaultFormat }; // default | ||
101 | |||
102 | } | ||
103 | // OK, we have an array with preferred formats, possibly with only one entry | ||
104 | |||
105 | httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; | ||
106 | foreach (string f in formats) | ||
107 | { | ||
108 | if (FetchTexture(httpRequest, httpResponse, textureID, f)) | ||
109 | break; | ||
110 | } | ||
111 | } | ||
112 | else | ||
113 | { | ||
114 | m_log.Warn("[GETTEXTURE]: Failed to parse a texture_id from GetTexture request: " + httpRequest.Url); | ||
115 | } | ||
116 | |||
117 | // m_log.DebugFormat( | ||
118 | // "[GETTEXTURE]: For texture {0} sending back response {1}, data length {2}", | ||
119 | // textureID, httpResponse.StatusCode, httpResponse.ContentLength); | ||
120 | |||
121 | return null; | ||
122 | } | ||
123 | |||
124 | /// <summary> | ||
125 | /// | ||
126 | /// </summary> | ||
127 | /// <param name="httpRequest"></param> | ||
128 | /// <param name="httpResponse"></param> | ||
129 | /// <param name="textureID"></param> | ||
130 | /// <param name="format"></param> | ||
131 | /// <returns>False for "caller try another codec"; true otherwise</returns> | ||
132 | private bool FetchTexture(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, UUID textureID, string format) | ||
133 | { | ||
134 | // m_log.DebugFormat("[GETTEXTURE]: {0} with requested format {1}", textureID, format); | ||
135 | AssetBase texture; | ||
136 | |||
137 | if(!String.IsNullOrEmpty(m_RedirectURL)) | ||
138 | { | ||
139 | string textureUrl = m_RedirectURL + "?texture_id=" + textureID.ToString(); | ||
140 | m_log.Debug("[GETTEXTURE]: Redirecting texture request to " + textureUrl); | ||
141 | httpResponse.StatusCode = (int)OSHttpStatusCode.RedirectMovedPermanently; | ||
142 | httpResponse.RedirectLocation = textureUrl; | ||
143 | return true; | ||
144 | } | ||
145 | else // no redirect | ||
146 | { | ||
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 | |||
167 | newTexture.Flags = AssetFlags.Collectable; | ||
168 | newTexture.Temporary = true; | ||
169 | newTexture.Local = true; | ||
170 | WriteTextureData(httpRequest, httpResponse, newTexture, format); | ||
171 | return true; | ||
172 | } | ||
173 | } | ||
174 | } | ||
175 | |||
176 | // not found | ||
177 | // m_log.Warn("[GETTEXTURE]: Texture " + textureID + " not found"); | ||
178 | httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; | ||
179 | return true; | ||
180 | } | ||
181 | |||
182 | private void WriteTextureData(IOSHttpRequest request, IOSHttpResponse response, AssetBase texture, string format) | ||
183 | { | ||
184 | string range = request.Headers.GetOne("Range"); | ||
185 | |||
186 | if (!String.IsNullOrEmpty(range)) // JP2's only | ||
187 | { | ||
188 | // Range request | ||
189 | int start, end; | ||
190 | if (TryParseRange(range, out start, out end)) | ||
191 | { | ||
192 | // Before clamping start make sure we can satisfy it in order to avoid | ||
193 | // sending back the last byte instead of an error status | ||
194 | if (start >= texture.Data.Length) | ||
195 | { | ||
196 | // m_log.DebugFormat( | ||
197 | // "[GETTEXTURE]: Client requested range for texture {0} starting at {1} but texture has end of {2}", | ||
198 | // texture.ID, start, texture.Data.Length); | ||
199 | |||
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 | |||
211 | // response.StatusCode = (int)System.Net.HttpStatusCode.RequestedRangeNotSatisfiable; | ||
212 | // response.AddHeader("Content-Range", String.Format("bytes */{0}", texture.Data.Length)); | ||
213 | // response.StatusCode = (int)System.Net.HttpStatusCode.OK; | ||
214 | response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent; | ||
215 | response.ContentType = texture.Metadata.ContentType; | ||
216 | } | ||
217 | else | ||
218 | { | ||
219 | // Handle the case where no second range value was given. This is equivalent to requesting | ||
220 | // the rest of the entity. | ||
221 | if (end == -1) | ||
222 | end = int.MaxValue; | ||
223 | |||
224 | end = Utils.Clamp(end, 0, texture.Data.Length - 1); | ||
225 | start = Utils.Clamp(start, 0, end); | ||
226 | int len = end - start + 1; | ||
227 | |||
228 | // m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID); | ||
229 | |||
230 | // Always return PartialContent, even if the range covered the entire data length | ||
231 | // We were accidentally sending back 404 before in this situation | ||
232 | // https://issues.apache.org/bugzilla/show_bug.cgi?id=51878 supports sending 206 even if the | ||
233 | // entire range is requested, and viewer 3.2.2 (and very probably earlier) seems fine with this. | ||
234 | // | ||
235 | // We also do not want to send back OK even if the whole range was satisfiable since this causes | ||
236 | // HTTP textures on at least Imprudence 1.4.0-beta2 to never display the final texture quality. | ||
237 | // if (end > maxEnd) | ||
238 | // response.StatusCode = (int)System.Net.HttpStatusCode.OK; | ||
239 | // else | ||
240 | response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent; | ||
241 | |||
242 | response.ContentLength = len; | ||
243 | response.ContentType = texture.Metadata.ContentType; | ||
244 | response.AddHeader("Content-Range", String.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length)); | ||
245 | |||
246 | response.Body.Write(texture.Data, start, len); | ||
247 | } | ||
248 | } | ||
249 | else | ||
250 | { | ||
251 | m_log.Warn("[GETTEXTURE]: Malformed Range header: " + range); | ||
252 | response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; | ||
253 | } | ||
254 | } | ||
255 | else // JP2's or other formats | ||
256 | { | ||
257 | // Full content request | ||
258 | response.StatusCode = (int)System.Net.HttpStatusCode.OK; | ||
259 | response.ContentLength = texture.Data.Length; | ||
260 | if (format == DefaultFormat) | ||
261 | response.ContentType = texture.Metadata.ContentType; | ||
262 | else | ||
263 | response.ContentType = "image/" + format; | ||
264 | response.Body.Write(texture.Data, 0, texture.Data.Length); | ||
265 | } | ||
266 | |||
267 | // if (response.StatusCode < 200 || response.StatusCode > 299) | ||
268 | // m_log.WarnFormat( | ||
269 | // "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})", | ||
270 | // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length); | ||
271 | // else | ||
272 | // m_log.DebugFormat( | ||
273 | // "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})", | ||
274 | // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length); | ||
275 | } | ||
276 | |||
277 | /// <summary> | ||
278 | /// Parse a range header. | ||
279 | /// </summary> | ||
280 | /// <remarks> | ||
281 | /// As per http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html, | ||
282 | /// this obeys range headers with two values (e.g. 533-4165) and no second value (e.g. 533-). | ||
283 | /// Where there is no value, -1 is returned. | ||
284 | /// FIXME: Need to cover the case where only a second value is specified (e.g. -4165), probably by returning -1 | ||
285 | /// for start.</remarks> | ||
286 | /// <returns></returns> | ||
287 | /// <param name='header'></param> | ||
288 | /// <param name='start'>Start of the range. Undefined if this was not a number.</param> | ||
289 | /// <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> | ||
290 | private bool TryParseRange(string header, out int start, out int end) | ||
291 | { | ||
292 | start = end = 0; | ||
293 | |||
294 | if (header.StartsWith("bytes=")) | ||
295 | { | ||
296 | string[] rangeValues = header.Substring(6).Split('-'); | ||
297 | |||
298 | if (rangeValues.Length == 2) | ||
299 | { | ||
300 | if (!Int32.TryParse(rangeValues[0], out start)) | ||
301 | return false; | ||
302 | |||
303 | string rawEnd = rangeValues[1]; | ||
304 | |||
305 | if (rawEnd == "") | ||
306 | { | ||
307 | end = -1; | ||
308 | return true; | ||
309 | } | ||
310 | else if (Int32.TryParse(rawEnd, out end)) | ||
311 | { | ||
312 | return true; | ||
313 | } | ||
314 | } | ||
315 | } | ||
316 | |||
317 | start = end = 0; | ||
318 | return false; | ||
319 | } | ||
320 | |||
321 | private byte[] ConvertTextureData(AssetBase texture, string format) | ||
322 | { | ||
323 | m_log.DebugFormat("[GETTEXTURE]: Converting texture {0} to {1}", texture.ID, format); | ||
324 | byte[] data = new byte[0]; | ||
325 | |||
326 | MemoryStream imgstream = new MemoryStream(); | ||
327 | Bitmap mTexture = null; | ||
328 | ManagedImage managedImage = null; | ||
329 | Image image = null; | ||
330 | |||
331 | try | ||
332 | { | ||
333 | // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular data | ||
334 | // Decode image to System.Drawing.Image | ||
335 | if (OpenJPEG.DecodeToImage(texture.Data, out managedImage, out image) && image != null) | ||
336 | { | ||
337 | // Save to bitmap | ||
338 | mTexture = new Bitmap(image); | ||
339 | |||
340 | using(EncoderParameters myEncoderParameters = new EncoderParameters()) | ||
341 | { | ||
342 | myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality,95L); | ||
343 | |||
344 | // Save bitmap to stream | ||
345 | ImageCodecInfo codec = GetEncoderInfo("image/" + format); | ||
346 | if (codec != null) | ||
347 | { | ||
348 | mTexture.Save(imgstream, codec, myEncoderParameters); | ||
349 | // Write the stream to a byte array for output | ||
350 | data = imgstream.ToArray(); | ||
351 | } | ||
352 | else | ||
353 | m_log.WarnFormat("[GETTEXTURE]: No such codec {0}", format); | ||
354 | } | ||
355 | } | ||
356 | } | ||
357 | catch (Exception e) | ||
358 | { | ||
359 | m_log.WarnFormat("[GETTEXTURE]: Unable to convert texture {0} to {1}: {2}", texture.ID, format, e.Message); | ||
360 | } | ||
361 | finally | ||
362 | { | ||
363 | // Reclaim memory, these are unmanaged resources | ||
364 | // If we encountered an exception, one or more of these will be null | ||
365 | if (mTexture != null) | ||
366 | mTexture.Dispose(); | ||
367 | |||
368 | if (image != null) | ||
369 | image.Dispose(); | ||
370 | |||
371 | if(managedImage != null) | ||
372 | managedImage.Clear(); | ||
373 | |||
374 | if (imgstream != null) | ||
375 | imgstream.Dispose(); | ||
376 | } | ||
377 | |||
378 | return data; | ||
379 | } | ||
380 | |||
381 | // From msdn | ||
382 | private static ImageCodecInfo GetEncoderInfo(String mimeType) | ||
383 | { | ||
384 | ImageCodecInfo[] encoders; | ||
385 | encoders = ImageCodecInfo.GetImageEncoders(); | ||
386 | for (int j = 0; j < encoders.Length; ++j) | ||
387 | { | ||
388 | if (encoders[j].MimeType == mimeType) | ||
389 | return encoders[j]; | ||
390 | } | ||
391 | return null; | ||
392 | } | ||
393 | } | ||
394 | } | ||
diff --git a/OpenSim/Capabilities/Handlers/GetTexture/GetTextureServerConnector.cs b/OpenSim/Capabilities/Handlers/GetTexture/GetTextureServerConnector.cs index fa0b228..479cebb 100644 --- a/OpenSim/Capabilities/Handlers/GetTexture/GetTextureServerConnector.cs +++ b/OpenSim/Capabilities/Handlers/GetTexture/GetTextureServerConnector.cs | |||
@@ -33,6 +33,7 @@ using OpenSim.Framework.Servers.HttpServer; | |||
33 | using OpenSim.Server.Handlers.Base; | 33 | using OpenSim.Server.Handlers.Base; |
34 | using OpenMetaverse; | 34 | using OpenMetaverse; |
35 | 35 | ||
36 | |||
36 | namespace OpenSim.Capabilities.Handlers | 37 | namespace OpenSim.Capabilities.Handlers |
37 | { | 38 | { |
38 | public class GetTextureServerConnector : ServiceConnector | 39 | public class GetTextureServerConnector : ServiceConnector |
@@ -65,7 +66,8 @@ namespace OpenSim.Capabilities.Handlers | |||
65 | string rurl = serverConfig.GetString("GetTextureRedirectURL"); | 66 | string rurl = serverConfig.GetString("GetTextureRedirectURL"); |
66 | ; | 67 | ; |
67 | server.AddStreamHandler( | 68 | server.AddStreamHandler( |
68 | new GetTextureHandler("/CAPS/GetTexture/" /*+ UUID.Random() */, m_AssetService, "GetTexture", null, rurl)); | 69 | new GetTextureRobustHandler("/CAPS/GetTexture/", m_AssetService, "GetTexture", null, rurl)); |
69 | } | 70 | } |
70 | } | 71 | } |
71 | } \ No newline at end of file | 72 | } |
73 | |||
diff --git a/OpenSim/Capabilities/Handlers/GetTexture/Tests/GetTextureHandlerTests.cs b/OpenSim/Capabilities/Handlers/GetTexture/Tests/GetTextureHandlerTests.cs index e5d9618..61aa689 100644 --- a/OpenSim/Capabilities/Handlers/GetTexture/Tests/GetTextureHandlerTests.cs +++ b/OpenSim/Capabilities/Handlers/GetTexture/Tests/GetTextureHandlerTests.cs | |||
@@ -38,6 +38,7 @@ using OpenSim.Framework.Servers.HttpServer; | |||
38 | using OpenSim.Region.Framework.Scenes; | 38 | using OpenSim.Region.Framework.Scenes; |
39 | using OpenSim.Tests.Common; | 39 | using OpenSim.Tests.Common; |
40 | 40 | ||
41 | /* | ||
41 | namespace OpenSim.Capabilities.Handlers.GetTexture.Tests | 42 | namespace OpenSim.Capabilities.Handlers.GetTexture.Tests |
42 | { | 43 | { |
43 | [TestFixture] | 44 | [TestFixture] |
@@ -59,4 +60,5 @@ namespace OpenSim.Capabilities.Handlers.GetTexture.Tests | |||
59 | Assert.That(resp.StatusCode, Is.EqualTo((int)System.Net.HttpStatusCode.NotFound)); | 60 | Assert.That(resp.StatusCode, Is.EqualTo((int)System.Net.HttpStatusCode.NotFound)); |
60 | } | 61 | } |
61 | } | 62 | } |
62 | } \ No newline at end of file | 63 | } |
64 | */ | ||