J2KDecoderModule.cs 16 KB

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