J2KDecoderModule.cs 14 KB

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