aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/ClientStack/LindenUDP/LLImageManager.cs
blob: d641b6cf468953440d46c61a513a3a346ef42065 (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
/*
 * 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.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
using log4net;

namespace OpenSim.Region.ClientStack.LindenUDP
{
    public class LLImageManager
    {
        private sealed class J2KImageComparer : IComparer<J2KImage>
        {
            public int Compare(J2KImage x, J2KImage y)
            {
                return x.Priority.CompareTo(y.Priority);
            }
        }

        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private bool m_shuttingdown = false;
        private long m_lastloopprocessed = 0;
        private AssetBase m_missingImage = null;

        private LLClientView m_client; //Client we're assigned to
        private IAssetService m_assetCache; //Asset Cache
        private IJ2KDecoder m_j2kDecodeModule; //Our J2K module
        private C5.IntervalHeap<J2KImage> m_priorityQueue = new C5.IntervalHeap<J2KImage>(10, new J2KImageComparer());

        public LLImageManager(LLClientView client, IAssetService pAssetCache, IJ2KDecoder pJ2kDecodeModule)
        {
            m_client = client;
            m_assetCache = pAssetCache;
            if (pAssetCache != null)
                m_missingImage = pAssetCache.Get("5748decc-f629-461c-9a36-a35a221fe21f");
            else
                m_log.Error("[ClientView] - couldn't set missing image asset, falling back to missing image packet. This is known to crash the client");

            m_j2kDecodeModule = pJ2kDecodeModule;
        }

        public LLClientView Client
        {
            get { return m_client; }
        }

        public AssetBase MissingImage
        {
            get { return m_missingImage; }
        }

        public void EnqueueReq(TextureRequestArgs newRequest)
        {
            //newRequest is the properties of our new texture fetch request.
            //Basically, here is where we queue up "new" requests..
            // .. or modify existing requests to suit.

            //Make sure we're not shutting down..
            if (!m_shuttingdown)
            {
                J2KImage imgrequest;

                // Do a linear search for this texture download
                lock (m_priorityQueue)
                    m_priorityQueue.Find(delegate(J2KImage img) { return img.TextureID == newRequest.RequestedAssetID; }, out imgrequest);

                if (imgrequest != null)
                {
                    if (newRequest.DiscardLevel == -1 && newRequest.Priority == 0f)
                    {
                        //m_log.Debug("[TEX]: (CAN) ID=" + newRequest.RequestedAssetID);

                        try 
                        {
                            lock (m_priorityQueue)
                                m_priorityQueue.Delete(imgrequest.PriorityQueueHandle); 
                        }
                        catch (Exception) { }
                    }
                    else
                    {
                        //m_log.DebugFormat("[TEX]: (UPD) ID={0}: D={1}, S={2}, P={3}",
                        //    newRequest.RequestedAssetID, newRequest.DiscardLevel, newRequest.PacketNumber, newRequest.Priority);

                        //Check the packet sequence to make sure this isn't older than 
                        //one we've already received
                        if (newRequest.requestSequence > imgrequest.LastSequence)
                        {
                            //Update the sequence number of the last RequestImage packet
                            imgrequest.LastSequence = newRequest.requestSequence;

                            //Update the requested discard level
                            imgrequest.DiscardLevel = newRequest.DiscardLevel;

                            //Update the requested packet number
                            imgrequest.StartPacket = newRequest.PacketNumber;

                            //Update the requested priority
                            imgrequest.Priority = newRequest.Priority;
                            try 
                            { 
                                lock (m_priorityQueue)
                                    m_priorityQueue.Replace(imgrequest.PriorityQueueHandle, imgrequest); 
                            }
                            catch (Exception) 
                            { 
                                imgrequest.PriorityQueueHandle = null; 
                                lock (m_priorityQueue)
                                    m_priorityQueue.Add(ref imgrequest.PriorityQueueHandle, imgrequest); 
                            }

                            //Run an update
                            imgrequest.RunUpdate();
                        }
                    }
                }
                else
                {
                    if (newRequest.DiscardLevel == -1 && newRequest.Priority == 0f)
                    {
                        //m_log.DebugFormat("[TEX]: (IGN) ID={0}: D={1}, S={2}, P={3}",
                        //    newRequest.RequestedAssetID, newRequest.DiscardLevel, newRequest.PacketNumber, newRequest.Priority);
                    }
                    else
                    {
                        //m_log.DebugFormat("[TEX]: (NEW) ID={0}: D={1}, S={2}, P={3}",
                        //    newRequest.RequestedAssetID, newRequest.DiscardLevel, newRequest.PacketNumber, newRequest.Priority);

                        imgrequest = new J2KImage(this);

                        //Assign our decoder module
                        imgrequest.J2KDecoder = m_j2kDecodeModule;

                        //Assign our asset cache module
                        imgrequest.AssetService = m_assetCache;

                        //Assign the requested discard level
                        imgrequest.DiscardLevel = newRequest.DiscardLevel;

                        //Assign the requested packet number
                        imgrequest.StartPacket = newRequest.PacketNumber;

                        //Assign the requested priority
                        imgrequest.Priority = newRequest.Priority;

                        //Assign the asset uuid
                        imgrequest.TextureID = newRequest.RequestedAssetID;

                        //Assign the requested priority
                        imgrequest.Priority = newRequest.Priority;

                        //Add this download to the priority queue
                        lock (m_priorityQueue)
                            m_priorityQueue.Add(ref imgrequest.PriorityQueueHandle, imgrequest);

                        //Run an update
                        imgrequest.RunUpdate();
                    }
                }
            }
        }

        public bool ProcessImageQueue(int count, int maxpack)
        {
            lock (this)
            {
                //count is the number of textures we want to process in one go.
                //As part of this class re-write, that number will probably rise
                //since we're processing in a more efficient manner.

                // this can happen during Close()
                if (m_client == null)
                    return false;

                int numCollected = 0;

                //Calculate our threshold
                int threshold;
                if (m_lastloopprocessed == 0)
                {
                    if (m_client.PacketHandler == null || m_client.PacketHandler.PacketQueue == null || m_client.PacketHandler.PacketQueue.TextureThrottle == null)
                        return false;
                    //This is decent for a semi fast machine, but we'll calculate it more accurately based on time below
                    threshold = m_client.PacketHandler.PacketQueue.TextureThrottle.Current / 6300;
                    m_lastloopprocessed = DateTime.Now.Ticks;
                }
                else
                {
                    double throttleseconds = ((double)DateTime.Now.Ticks - (double)m_lastloopprocessed) / (double)TimeSpan.TicksPerSecond;
                    throttleseconds = throttleseconds * m_client.PacketHandler.PacketQueue.TextureThrottle.Current;

                    //Average of 1000 bytes per packet
                    throttleseconds = throttleseconds / 1000;

                    //Safe-zone multiplier of 2.0
                    threshold = (int)(throttleseconds * 2.0);
                    m_lastloopprocessed = DateTime.Now.Ticks;

                }

                if (m_client.PacketHandler == null)
                    return false;

                if (m_client.PacketHandler.PacketQueue == null)
                    return false;

                if (threshold < 10)
                    threshold = 10;

                //Uncomment this to see what the texture stack is doing
                //m_log.Debug("Queue: " + m_client.PacketHandler.PacketQueue.getQueueCount(ThrottleOutPacketType.Texture).ToString() + " Threshold: " + threshold.ToString() + " outstanding: " + m_outstandingtextures.ToString());
                if (true) //m_client.PacketHandler.PacketQueue.GetQueueCount(ThrottleOutPacketType.Texture) < threshold)
                {
                    while (m_priorityQueue.Count > 0)
                    {
                        J2KImage imagereq = null;
                        lock (m_priorityQueue)
                            imagereq = m_priorityQueue.FindMax();

                        if (imagereq.IsDecoded == true)
                        {
                            // we need to test this here now that we are dropping assets
                            if (!imagereq.HasAsset)
                            {
                                m_log.WarnFormat("[LLIMAGE MANAGER]: Re-requesting the image asset {0}", imagereq.TextureID);
                                imagereq.RunUpdate();
                                continue;
                            }

                            ++numCollected;

                            //SendPackets will send up to ten packets per cycle
                            if (imagereq.SendPackets(m_client, maxpack))
                            {
                                // Send complete. Destroy any knowledge of this transfer
                                try 
                                { 
                                    lock (m_priorityQueue)
                                        m_priorityQueue.Delete(imagereq.PriorityQueueHandle); 
                                }
                                catch (Exception) { }
                            }
                        }

                        if (numCollected == count)
                            break;
                    }
                }

                return m_priorityQueue.Count > 0;
            }
        }

        //Faux destructor
        public void Close()
        {

            m_shuttingdown = true;
            m_j2kDecodeModule = null;
            m_assetCache = null;
            m_client = null;
        }


    }
}