J2KDecoderModule.cs 15 KB

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