J2KDecoderModule.cs 14 KB

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