aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/ClientStack/LindenUDP/J2KImage.cs
blob: 9ded390767124ed59b03e3c0c27635482a4c6741 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/*
 * Copyright (c) Contributors, http://opensimulator.org/
 * See CONTRIBUTORS.TXT for a full list of copyright holders.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSimulator Project nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
using log4net;
using System.Reflection;

namespace OpenSim.Region.ClientStack.LindenUDP
{
    /// <summary>
    /// Stores information about a current texture download and a reference to the texture asset
    /// </summary>
    public class J2KImage
    {
        private const int IMAGE_PACKET_SIZE = 1000;
        private const int FIRST_PACKET_SIZE = 600;

        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public uint LastSequence;
        public float Priority;
        public uint StartPacket;
        public sbyte DiscardLevel;
        public UUID TextureID;
        public IJ2KDecoder J2KDecoder;
        public IAssetService AssetService;
        public OpenJPEG.J2KLayerInfo[] Layers;
        public bool IsDecoded;
        public bool HasAsset;
        public C5.IPriorityQueueHandle<J2KImage> PriorityQueueHandle;

        private uint m_currentPacket;
        private bool m_decodeRequested;
        private bool m_assetRequested;
        private bool m_sentInfo;
        private uint m_stopPacket;
        private byte[] m_asset;
        private LLImageManager m_imageManager;

        public J2KImage(LLImageManager imageManager)
        {
            m_imageManager = imageManager;
        }

        /// <summary>
        /// Sends packets for this texture to a client until packetsToSend is 
        /// hit or the transfer completes
        /// </summary>
        /// <param name="client">Reference to the client that the packets are destined for</param>
        /// <param name="packetsToSend">Maximum number of packets to send during this call</param>
        /// <param name="packetsSent">Number of packets sent during this call</param>
        /// <returns>True if the transfer completes at the current discard level, otherwise false</returns>
        public bool SendPackets(LLClientView client, int packetsToSend, out int packetsSent)
        {
            packetsSent = 0;

            if (m_currentPacket <= m_stopPacket)
            {
                bool sendMore = true;

                if (!m_sentInfo || (m_currentPacket == 0))
                {
                    sendMore = !SendFirstPacket(client);

                    m_sentInfo = true;
                    ++m_currentPacket;
                    ++packetsSent;
                }
                if (m_currentPacket < 2)
                {
                    m_currentPacket = 2;
                }
                
                while (sendMore && packetsSent < packetsToSend && m_currentPacket <= m_stopPacket)
                {
                    sendMore = SendPacket(client);
                    ++m_currentPacket;
                    ++packetsSent;
                }
            }

            return (m_currentPacket > m_stopPacket);
        }

        public void RunUpdate()
        {
            //This is where we decide what we need to update
            //and assign the real discardLevel and packetNumber
            //assuming of course that the connected client might be bonkers

            if (!HasAsset)
            {
                if (!m_assetRequested)
                {
                    m_assetRequested = true;
                    AssetService.Get(TextureID.ToString(), this, AssetReceived);
                }
            }
            else
            {
                if (!IsDecoded)
                {
                    //We need to decode the requested image first
                    if (!m_decodeRequested)
                    {
                        //Request decode
                        m_decodeRequested = true;
                        // Do we have a jpeg decoder?
                        if (J2KDecoder != null)
                        {
                            if (m_asset == null)
                            {
                                J2KDecodedCallback(TextureID, new OpenJPEG.J2KLayerInfo[0]);
                            }
                            else
                            {
                                // Send it off to the jpeg decoder
                                J2KDecoder.BeginDecode(TextureID, m_asset, J2KDecodedCallback);
                            }

                        }
                        else
                        {
                            J2KDecodedCallback(TextureID, new OpenJPEG.J2KLayerInfo[0]);
                        }
                    }
                }
                else
                {
                    // Check for missing image asset data
                    if (m_asset == null)
                    {
                        m_log.Warn("[J2KIMAGE]: RunUpdate() called with missing asset data (no missing image texture?). Canceling texture transfer");
                        m_currentPacket = m_stopPacket;
                        return;
                    }
                    
                    if (DiscardLevel >= 0 || m_stopPacket == 0)
                    {
                        // This shouldn't happen, but if it does, we really can't proceed
                        if (Layers == null)
                        {
                            m_log.Warn("[J2KIMAGE]: RunUpdate() called with missing Layers. Canceling texture transfer");
                            m_currentPacket = m_stopPacket;
                            return;
                        }

                        int maxDiscardLevel = Math.Max(0, Layers.Length - 1);

                        // Treat initial texture downloads with a DiscardLevel of -1 a request for the highest DiscardLevel
                        if (DiscardLevel < 0 && m_stopPacket == 0)
                            DiscardLevel = (sbyte)maxDiscardLevel;

                        // Clamp at the highest discard level
                        DiscardLevel = (sbyte)Math.Min(DiscardLevel, maxDiscardLevel);

                        //Calculate the m_stopPacket
                        if (Layers.Length > 0)
                        {
                            m_stopPacket = (uint)GetPacketForBytePosition(Layers[(Layers.Length - 1) - DiscardLevel].End);
                            //I don't know why, but the viewer seems to expect the final packet if the file
                            //is just one packet bigger.
                            if (TexturePacketCount() == m_stopPacket + 1)
                            {
                                m_stopPacket = TexturePacketCount();
                            }
                        }
                        else
                        {
                            m_stopPacket = TexturePacketCount();
                        }

                        m_currentPacket = StartPacket;
                    }
                }
            }
        }

        private bool SendFirstPacket(LLClientView client)
        {
            if (client == null)
                return false;

            if (m_asset == null)
            {
                m_log.Warn("[J2KIMAGE]: Sending ImageNotInDatabase for texture " + TextureID);
                client.SendImageNotFound(TextureID);
                return true;
            }
            else if (m_asset.Length <= FIRST_PACKET_SIZE)
            {
                // We have less then one packet's worth of data
                client.SendImageFirstPart(1, TextureID, (uint)m_asset.Length, m_asset, 2);
                m_stopPacket = 0;
                return true;
            }
            else
            {
                // This is going to be a multi-packet texture download
                byte[] firstImageData = new byte[FIRST_PACKET_SIZE];

                try { Buffer.BlockCopy(m_asset, 0, firstImageData, 0, FIRST_PACKET_SIZE); }
                catch (Exception)
                {
                    m_log.ErrorFormat("[J2KIMAGE]: Texture block copy for the first packet failed. textureid={0}, assetlength={1}", TextureID, m_asset.Length);
                    return true;
                }

                client.SendImageFirstPart(TexturePacketCount(), TextureID, (uint)m_asset.Length, firstImageData, (byte)ImageCodec.J2C);
            }
            return false;
        }

        private bool SendPacket(LLClientView client)
        {
            if (client == null)
                return false;

            bool complete = false;
            int imagePacketSize = ((int)m_currentPacket == (TexturePacketCount())) ? LastPacketSize() : IMAGE_PACKET_SIZE;

            try
            {
                if ((CurrentBytePosition() + IMAGE_PACKET_SIZE) > m_asset.Length)
                {
                    imagePacketSize = LastPacketSize();
                    complete = true;
                    if ((CurrentBytePosition() + imagePacketSize) > m_asset.Length)
                    {
                        imagePacketSize = m_asset.Length - CurrentBytePosition();
                        complete = true;
                    }
                }

                // It's concievable that the client might request packet one
                // from a one packet image, which is really packet 0,
                // which would leave us with a negative imagePacketSize..
                if (imagePacketSize > 0)
                {
                    byte[] imageData = new byte[imagePacketSize];
                    int currentPosition = CurrentBytePosition();

                    try { Buffer.BlockCopy(m_asset, currentPosition, imageData, 0, imagePacketSize); }
                    catch (Exception e)
                    {
                        m_log.ErrorFormat("[J2KIMAGE]: Texture block copy for the first packet failed. textureid={0}, assetlength={1}, currentposition={2}, imagepacketsize={3}, exception={4}",
                            TextureID, m_asset.Length, currentPosition, imagePacketSize, e.Message);
                        return false;
                    }

                    //Send the packet
                    client.SendImageNextPart((ushort)(m_currentPacket - 1), TextureID, imageData);
                }

                return !complete;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private ushort TexturePacketCount()
        {
            if (!IsDecoded)
                return 0;

            if (m_asset == null)
                return 0;

            if (m_asset.Length <= FIRST_PACKET_SIZE)
                return 1;

            return (ushort)(((m_asset.Length - FIRST_PACKET_SIZE + IMAGE_PACKET_SIZE - 1) / IMAGE_PACKET_SIZE) + 1);
        }

        private int GetPacketForBytePosition(int bytePosition)
        {
            return ((bytePosition - FIRST_PACKET_SIZE + IMAGE_PACKET_SIZE - 1) / IMAGE_PACKET_SIZE) + 1;
        }

        private int LastPacketSize()
        {
            if (m_currentPacket == 1)
                return m_asset.Length;
            int lastsize = (m_asset.Length - FIRST_PACKET_SIZE) % IMAGE_PACKET_SIZE;
            //If the last packet size is zero, it's really cImagePacketSize, it sits on the boundary
            if (lastsize == 0)
            {
                lastsize = IMAGE_PACKET_SIZE;
            }
            return lastsize;
        }

        private int CurrentBytePosition()
        {
            if (m_currentPacket == 0)
                return 0;
            if (m_currentPacket == 1)
                return FIRST_PACKET_SIZE;

            int result = FIRST_PACKET_SIZE + ((int)m_currentPacket - 2) * IMAGE_PACKET_SIZE;
            if (result < 0)
            {
                result = FIRST_PACKET_SIZE;
            }
            return result;
        }

        private void J2KDecodedCallback(UUID AssetId, OpenJPEG.J2KLayerInfo[] layers)
        {
            Layers = layers;
            IsDecoded = true;
            RunUpdate();
        }

        private void AssetDataCallback(UUID AssetID, AssetBase asset)
        {
            HasAsset = true;

            if (asset == null || asset.Data == null)
            {
                if (m_imageManager.MissingImage != null)
                {
                    m_asset = m_imageManager.MissingImage.Data;
                }
                else
                {
                    m_asset = null;
                    IsDecoded = true;
                }
            }
            else
            {
                m_asset = asset.Data;
            }

            RunUpdate();
        }

        private void AssetReceived(string id, Object sender, AssetBase asset)
        {
            UUID assetID = UUID.Zero;
            if (asset != null)
                assetID = asset.FullID;

            AssetDataCallback(assetID, asset);

        }
    }
}