J2KDecoderModule.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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 IAssetCache m_cache;
  57. private IAssetCache Cache
  58. {
  59. get
  60. {
  61. if (m_cache == null)
  62. m_cache = m_scene.RequestModuleInterface<IAssetCache>();
  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); }, null, "J2KDecoderModule.BeginDecode");
  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;
  201. using (MemoryStream ms = new MemoryStream(j2kData))
  202. {
  203. layerStarts = CSJ2K.J2kImage.GetLayerBoundaries(ms);
  204. }
  205. if (layerStarts != null && layerStarts.Count > 0)
  206. {
  207. layers = new OpenJPEG.J2KLayerInfo[layerStarts.Count];
  208. for (int i = 0; i < layerStarts.Count; i++)
  209. {
  210. OpenJPEG.J2KLayerInfo layer = new OpenJPEG.J2KLayerInfo();
  211. if (i == 0)
  212. layer.Start = 0;
  213. else
  214. layer.Start = layerStarts[i];
  215. if (i == layerStarts.Count - 1)
  216. layer.End = j2kData.Length;
  217. else
  218. layer.End = layerStarts[i + 1] - 1;
  219. layers[i] = layer;
  220. }
  221. }
  222. }
  223. catch (Exception ex)
  224. {
  225. m_log.Warn("[J2KDecoderModule]: CSJ2K threw an exception decoding texture " + assetID + ": " + ex.Message);
  226. decodedSuccessfully = false;
  227. }
  228. }
  229. else
  230. {
  231. if (!OpenJPEG.DecodeLayerBoundaries(j2kData, out layers, out components))
  232. {
  233. m_log.Warn("[J2KDecoderModule]: OpenJPEG failed to decode texture " + assetID);
  234. decodedSuccessfully = false;
  235. }
  236. }
  237. if (layers == null || layers.Length == 0)
  238. {
  239. m_log.Warn("[J2KDecoderModule]: Failed to decode layer data for texture " + assetID + ", guessing sane defaults");
  240. // Layer decoding completely failed. Guess at sane defaults for the layer boundaries
  241. layers = CreateDefaultLayers(j2kData.Length);
  242. decodedSuccessfully = false;
  243. }
  244. // Cache Decoded layers
  245. SaveFileCacheForAsset(assetID, layers);
  246. }
  247. // Notify Interested Parties
  248. lock (m_notifyList)
  249. {
  250. if (m_notifyList.ContainsKey(assetID))
  251. {
  252. foreach (DecodedCallback d in m_notifyList[assetID])
  253. {
  254. if (d != null)
  255. d.DynamicInvoke(assetID, layers);
  256. }
  257. m_notifyList.Remove(assetID);
  258. }
  259. }
  260. return decodedSuccessfully;
  261. }
  262. private OpenJPEG.J2KLayerInfo[] CreateDefaultLayers(int j2kLength)
  263. {
  264. OpenJPEG.J2KLayerInfo[] layers = new OpenJPEG.J2KLayerInfo[5];
  265. for (int i = 0; i < layers.Length; i++)
  266. layers[i] = new OpenJPEG.J2KLayerInfo();
  267. // These default layer sizes are based on a small sampling of real-world texture data
  268. // with extra padding thrown in for good measure. This is a worst case fallback plan
  269. // and may not gracefully handle all real world data
  270. layers[0].Start = 0;
  271. layers[1].Start = (int)((float)j2kLength * 0.02f);
  272. layers[2].Start = (int)((float)j2kLength * 0.05f);
  273. layers[3].Start = (int)((float)j2kLength * 0.20f);
  274. layers[4].Start = (int)((float)j2kLength * 0.50f);
  275. layers[0].End = layers[1].Start - 1;
  276. layers[1].End = layers[2].Start - 1;
  277. layers[2].End = layers[3].Start - 1;
  278. layers[3].End = layers[4].Start - 1;
  279. layers[4].End = j2kLength;
  280. return layers;
  281. }
  282. private void SaveFileCacheForAsset(UUID AssetId, OpenJPEG.J2KLayerInfo[] Layers)
  283. {
  284. m_decodedCache.AddOrUpdate(AssetId, Layers, TimeSpan.FromMinutes(10));
  285. if (Cache != null)
  286. {
  287. string assetID = "j2kCache_" + AssetId.ToString();
  288. AssetBase layerDecodeAsset = new AssetBase(assetID, assetID, (sbyte)AssetType.Notecard, m_CreatorID.ToString());
  289. layerDecodeAsset.Local = true;
  290. layerDecodeAsset.Temporary = true;
  291. #region Serialize Layer Data
  292. StringBuilder stringResult = new StringBuilder();
  293. string strEnd = "\n";
  294. for (int i = 0; i < Layers.Length; i++)
  295. {
  296. if (i == Layers.Length - 1)
  297. strEnd = String.Empty;
  298. stringResult.AppendFormat("{0}|{1}|{2}{3}", Layers[i].Start, Layers[i].End, Layers[i].End - Layers[i].Start, strEnd);
  299. }
  300. layerDecodeAsset.Data = Util.UTF8.GetBytes(stringResult.ToString());
  301. #endregion Serialize Layer Data
  302. Cache.Cache(layerDecodeAsset);
  303. }
  304. }
  305. bool TryLoadCacheForAsset(UUID AssetId, out OpenJPEG.J2KLayerInfo[] Layers)
  306. {
  307. if (m_decodedCache.TryGetValue(AssetId, out Layers))
  308. {
  309. return true;
  310. }
  311. else if (Cache != null)
  312. {
  313. string assetName = "j2kCache_" + AssetId.ToString();
  314. AssetBase layerDecodeAsset;
  315. Cache.Get(assetName, out layerDecodeAsset);
  316. if (layerDecodeAsset != null)
  317. {
  318. #region Deserialize Layer Data
  319. string readResult = Util.UTF8.GetString(layerDecodeAsset.Data);
  320. string[] lines = readResult.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
  321. if (lines.Length == 0)
  322. {
  323. m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (empty) " + assetName);
  324. Cache.Expire(assetName);
  325. return false;
  326. }
  327. Layers = new OpenJPEG.J2KLayerInfo[lines.Length];
  328. for (int i = 0; i < lines.Length; i++)
  329. {
  330. string[] elements = lines[i].Split('|');
  331. if (elements.Length == 3)
  332. {
  333. int element1, element2;
  334. try
  335. {
  336. element1 = Convert.ToInt32(elements[0]);
  337. element2 = Convert.ToInt32(elements[1]);
  338. }
  339. catch (FormatException)
  340. {
  341. m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (format) " + assetName);
  342. Cache.Expire(assetName);
  343. return false;
  344. }
  345. Layers[i] = new OpenJPEG.J2KLayerInfo();
  346. Layers[i].Start = element1;
  347. Layers[i].End = element2;
  348. }
  349. else
  350. {
  351. m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (layout) " + assetName);
  352. Cache.Expire(assetName);
  353. return false;
  354. }
  355. }
  356. #endregion Deserialize Layer Data
  357. return true;
  358. }
  359. }
  360. return false;
  361. }
  362. }
  363. }