J2KDecoderModule.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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.Generic;
  29. using System.IO;
  30. using System.Reflection;
  31. using System.Text;
  32. using System.Threading;
  33. using log4net;
  34. using Nini.Config;
  35. using OpenMetaverse;
  36. using OpenMetaverse.Imaging;
  37. using CSJ2K;
  38. using OpenSim.Framework;
  39. using OpenSim.Region.Framework.Interfaces;
  40. using OpenSim.Region.Framework.Scenes;
  41. using OpenSim.Services.Interfaces;
  42. namespace OpenSim.Region.CoreModules.Agent.TextureSender
  43. {
  44. public delegate void J2KDecodeDelegate(UUID assetID);
  45. public class J2KDecoderModule : IRegionModule, IJ2KDecoder
  46. {
  47. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  48. /// <summary>Temporarily holds deserialized layer data information in memory</summary>
  49. private readonly ExpiringCache<UUID, OpenJPEG.J2KLayerInfo[]> m_decodedCache = new ExpiringCache<UUID,OpenJPEG.J2KLayerInfo[]>();
  50. /// <summary>List of client methods to notify of results of decode</summary>
  51. private readonly Dictionary<UUID, List<DecodedCallback>> m_notifyList = new Dictionary<UUID, List<DecodedCallback>>();
  52. /// <summary>Cache that will store decoded JPEG2000 layer boundary data</summary>
  53. private IImprovedAssetCache m_cache;
  54. /// <summary>Reference to a scene (doesn't matter which one as long as it can load the cache module)</summary>
  55. private Scene m_scene;
  56. #region IRegionModule
  57. public string Name { get { return "J2KDecoderModule"; } }
  58. public bool IsSharedModule { get { return true; } }
  59. public J2KDecoderModule()
  60. {
  61. }
  62. public void Initialise(Scene scene, IConfigSource source)
  63. {
  64. if (m_scene == null)
  65. m_scene = scene;
  66. scene.RegisterModuleInterface<IJ2KDecoder>(this);
  67. }
  68. public void PostInitialise()
  69. {
  70. m_cache = m_scene.RequestModuleInterface<IImprovedAssetCache>();
  71. }
  72. public void Close()
  73. {
  74. }
  75. #endregion IRegionModule
  76. #region IJ2KDecoder
  77. public void BeginDecode(UUID assetID, byte[] j2kData, DecodedCallback callback)
  78. {
  79. OpenJPEG.J2KLayerInfo[] result;
  80. // If it's cached, return the cached results
  81. if (m_decodedCache.TryGetValue(assetID, out result))
  82. {
  83. callback(assetID, result);
  84. }
  85. else
  86. {
  87. // Not cached, we need to decode it.
  88. // Add to notify list and start decoding.
  89. // Next request for this asset while it's decoding will only be added to the notify list
  90. // once this is decoded, requests will be served from the cache and all clients in the notifylist will be updated
  91. bool decode = false;
  92. lock (m_notifyList)
  93. {
  94. if (m_notifyList.ContainsKey(assetID))
  95. {
  96. m_notifyList[assetID].Add(callback);
  97. }
  98. else
  99. {
  100. List<DecodedCallback> notifylist = new List<DecodedCallback>();
  101. notifylist.Add(callback);
  102. m_notifyList.Add(assetID, notifylist);
  103. decode = true;
  104. }
  105. }
  106. // Do Decode!
  107. if (decode)
  108. DoJ2KDecode(assetID, j2kData);
  109. }
  110. }
  111. /// <summary>
  112. /// Provides a synchronous decode so that caller can be assured that this executes before the next line
  113. /// </summary>
  114. /// <param name="assetID"></param>
  115. /// <param name="j2kData"></param>
  116. public void Decode(UUID assetID, byte[] j2kData)
  117. {
  118. DoJ2KDecode(assetID, j2kData);
  119. }
  120. #endregion IJ2KDecoder
  121. /// <summary>
  122. /// Decode Jpeg2000 Asset Data
  123. /// </summary>
  124. /// <param name="assetID">UUID of Asset</param>
  125. /// <param name="j2kData">JPEG2000 data</param>
  126. private void DoJ2KDecode(UUID assetID, byte[] j2kData)
  127. {
  128. // int DecodeTime = 0;
  129. // DecodeTime = Environment.TickCount;
  130. OpenJPEG.J2KLayerInfo[] layers;
  131. if (!TryLoadCacheForAsset(assetID, out layers))
  132. {
  133. try
  134. {
  135. List<int> layerStarts = CSJ2K.J2kImage.GetLayerBoundaries(new MemoryStream(j2kData));
  136. if (layerStarts != null && layerStarts.Count > 0)
  137. {
  138. layers = new OpenJPEG.J2KLayerInfo[layerStarts.Count];
  139. for (int i = 0; i < layerStarts.Count; i++)
  140. {
  141. OpenJPEG.J2KLayerInfo layer = new OpenJPEG.J2KLayerInfo();
  142. if (i == 0)
  143. layer.Start = 0;
  144. else
  145. layer.Start = layerStarts[i];
  146. if (i == layerStarts.Count - 1)
  147. layer.End = j2kData.Length;
  148. else
  149. layer.End = layerStarts[i + 1] - 1;
  150. layers[i] = layer;
  151. }
  152. }
  153. }
  154. catch (Exception ex)
  155. {
  156. m_log.Warn("[J2KDecoderModule]: CSJ2K threw an exception decoding texture " + assetID + ": " + ex.Message);
  157. }
  158. if (layers == null || layers.Length == 0)
  159. {
  160. m_log.Warn("[J2KDecoderModule]: Failed to decode layer data for texture " + assetID + ", guessing sane defaults");
  161. // Layer decoding completely failed. Guess at sane defaults for the layer boundaries
  162. layers = CreateDefaultLayers(j2kData.Length);
  163. }
  164. // Cache Decoded layers
  165. SaveFileCacheForAsset(assetID, layers);
  166. }
  167. // Notify Interested Parties
  168. lock (m_notifyList)
  169. {
  170. if (m_notifyList.ContainsKey(assetID))
  171. {
  172. foreach (DecodedCallback d in m_notifyList[assetID])
  173. {
  174. if (d != null)
  175. d.DynamicInvoke(assetID, layers);
  176. }
  177. m_notifyList.Remove(assetID);
  178. }
  179. }
  180. }
  181. private OpenJPEG.J2KLayerInfo[] CreateDefaultLayers(int j2kLength)
  182. {
  183. OpenJPEG.J2KLayerInfo[] layers = new OpenJPEG.J2KLayerInfo[5];
  184. for (int i = 0; i < layers.Length; i++)
  185. layers[i] = new OpenJPEG.J2KLayerInfo();
  186. // These default layer sizes are based on a small sampling of real-world texture data
  187. // with extra padding thrown in for good measure. This is a worst case fallback plan
  188. // and may not gracefully handle all real world data
  189. layers[0].Start = 0;
  190. layers[1].Start = (int)((float)j2kLength * 0.02f);
  191. layers[2].Start = (int)((float)j2kLength * 0.05f);
  192. layers[3].Start = (int)((float)j2kLength * 0.20f);
  193. layers[4].Start = (int)((float)j2kLength * 0.50f);
  194. layers[0].End = layers[1].Start - 1;
  195. layers[1].End = layers[2].Start - 1;
  196. layers[2].End = layers[3].Start - 1;
  197. layers[3].End = layers[4].Start - 1;
  198. layers[4].End = j2kLength;
  199. return layers;
  200. }
  201. private void SaveFileCacheForAsset(UUID AssetId, OpenJPEG.J2KLayerInfo[] Layers)
  202. {
  203. m_decodedCache.AddOrUpdate(AssetId, Layers, TimeSpan.FromMinutes(10));
  204. if (m_cache != null)
  205. {
  206. string assetID = "j2kCache_" + AssetId.ToString();
  207. AssetBase layerDecodeAsset = new AssetBase(assetID, assetID, (sbyte)AssetType.Notecard);
  208. layerDecodeAsset.Local = true;
  209. layerDecodeAsset.Temporary = true;
  210. #region Serialize Layer Data
  211. StringBuilder stringResult = new StringBuilder();
  212. string strEnd = "\n";
  213. for (int i = 0; i < Layers.Length; i++)
  214. {
  215. if (i == Layers.Length - 1)
  216. strEnd = String.Empty;
  217. stringResult.AppendFormat("{0}|{1}|{2}{3}", Layers[i].Start, Layers[i].End, Layers[i].End - Layers[i].Start, strEnd);
  218. }
  219. layerDecodeAsset.Data = Util.UTF8.GetBytes(stringResult.ToString());
  220. #endregion Serialize Layer Data
  221. m_cache.Cache(layerDecodeAsset);
  222. }
  223. }
  224. bool TryLoadCacheForAsset(UUID AssetId, out OpenJPEG.J2KLayerInfo[] Layers)
  225. {
  226. if (m_decodedCache.TryGetValue(AssetId, out Layers))
  227. {
  228. return true;
  229. }
  230. else if (m_cache != null)
  231. {
  232. string assetName = "j2kCache_" + AssetId.ToString();
  233. AssetBase layerDecodeAsset = m_cache.Get(assetName);
  234. if (layerDecodeAsset != null)
  235. {
  236. #region Deserialize Layer Data
  237. string readResult = Util.UTF8.GetString(layerDecodeAsset.Data);
  238. string[] lines = readResult.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
  239. if (lines.Length == 0)
  240. {
  241. m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (empty) " + assetName);
  242. m_cache.Expire(assetName);
  243. return false;
  244. }
  245. Layers = new OpenJPEG.J2KLayerInfo[lines.Length];
  246. for (int i = 0; i < lines.Length; i++)
  247. {
  248. string[] elements = lines[i].Split('|');
  249. if (elements.Length == 3)
  250. {
  251. int element1, element2;
  252. try
  253. {
  254. element1 = Convert.ToInt32(elements[0]);
  255. element2 = Convert.ToInt32(elements[1]);
  256. }
  257. catch (FormatException)
  258. {
  259. m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (format) " + assetName);
  260. m_cache.Expire(assetName);
  261. return false;
  262. }
  263. Layers[i] = new OpenJPEG.J2KLayerInfo();
  264. Layers[i].Start = element1;
  265. Layers[i].End = element2;
  266. }
  267. else
  268. {
  269. m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (layout) " + assetName);
  270. m_cache.Expire(assetName);
  271. return false;
  272. }
  273. }
  274. #endregion Deserialize Layer Data
  275. return true;
  276. }
  277. }
  278. return false;
  279. }
  280. }
  281. }