summaryrefslogtreecommitdiffstats
path: root/java/com/tigervnc/rfb/DecodeManager.java
blob: c1557460d00f00cf30fce777127b8bbe73411f7a (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
382
383
384
385
386
/* Copyright 2015 Pierre Ossman for Cendio AB
 * Copyright 2016 Brian P. Hinz
 * 
 * This is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
 * USA.
 */

package com.tigervnc.rfb;

import java.lang.Runtime;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;

import com.tigervnc.rdr.*;
import com.tigervnc.rdr.Exception;

import static com.tigervnc.rfb.Decoder.DecoderFlags.*;

public class DecodeManager {

  static LogWriter vlog = new LogWriter("DecodeManager");

  public DecodeManager(CConnection conn) {
    int cpuCount;

    this.conn = conn; threadException = null;
    decoders = new Decoder[Encodings.encodingMax+1];

    queueMutex = new ReentrantLock();
    producerCond = queueMutex.newCondition();
    consumerCond = queueMutex.newCondition();

    cpuCount = Runtime.getRuntime().availableProcessors();
    if (cpuCount == 0) {
      vlog.error("Unable to determine the number of CPU cores on this system");
      cpuCount = 1;
    } else {
      vlog.info("Detected "+cpuCount+" CPU core(s)");
      // No point creating more threads than this, they'll just end up
      // wasting CPU fighting for locks
      if (cpuCount > 4)
        cpuCount = 4;
      // The overhead of threading is small, but not small enough to
      // ignore on single CPU systems
      if (cpuCount == 1)
        vlog.info("Decoding data on main thread");
      else
        vlog.info("Creating "+cpuCount+" decoder thread(s)");
    }

    freeBuffers = new ArrayDeque<MemOutStream>(cpuCount*2);
    workQueue = new ArrayDeque<QueueEntry>(cpuCount);
    threads = new ArrayList<DecodeThread>(cpuCount);
    while (cpuCount-- > 0) {
      // Twice as many possible entries in the queue as there
      // are worker threads to make sure they don't stall
      try {
      freeBuffers.addLast(new MemOutStream());
      freeBuffers.addLast(new MemOutStream());

      threads.add(new DecodeThread(this));
      } catch (IllegalStateException e) { }
    }

  }

  public void decodeRect(Rect r, int encoding,
                         ModifiablePixelBuffer pb)
  {
    Decoder decoder;
    MemOutStream bufferStream;

    QueueEntry entry;

    assert(pb != null);

    if (!Decoder.supported(encoding)) {
      vlog.error("Unknown encoding " + encoding);
      throw new Exception("Unknown encoding");
    }

    if (decoders[encoding] == null) {
      decoders[encoding] = Decoder.createDecoder(encoding);
      if (decoders[encoding] == null) {
        vlog.error("Unknown encoding " + encoding);
        throw new Exception("Unknown encoding");
      }
    }

    decoder = decoders[encoding];

    // Fast path for single CPU machines to avoid the context
    // switching overhead
    if (threads.size() == 1) {
      bufferStream = freeBuffers.getFirst();
      bufferStream.clear();
      decoder.readRect(r, conn.getInStream(), conn.cp, bufferStream);
      decoder.decodeRect(r, (Object)bufferStream.data(), bufferStream.length(),
                         conn.cp, pb);
      return;
    }

    // Wait for an available memory buffer
    queueMutex.lock();

    while (freeBuffers.isEmpty())
      try {
      producerCond.await();
      } catch (InterruptedException e) { }

    // Don't pop the buffer in case we throw an exception
    // whilst reading
    bufferStream = freeBuffers.getFirst();

    queueMutex.unlock();

    // First check if any thread has encountered a problem
    throwThreadException();

    // Read the rect
    bufferStream.clear();
    decoder.readRect(r, conn.getInStream(), conn.cp, bufferStream);

    // Then try to put it on the queue
    entry = new QueueEntry();

    entry.active = false;
    entry.rect = r;
    entry.encoding = encoding;
    entry.decoder = decoder;
    entry.cp = conn.cp;
    entry.pb = pb;
    entry.bufferStream = bufferStream;
    entry.affectedRegion = new Region(r);

    decoder.getAffectedRegion(r, bufferStream.data(),
                              bufferStream.length(), conn.cp,
                              entry.affectedRegion);

    queueMutex.lock();

    // The workers add buffers to the end so it's safe to assume
    // the front is still the same buffer
    freeBuffers.removeFirst();

    workQueue.addLast(entry);

    // We only put a single entry on the queue so waking a single
    // thread is sufficient
    consumerCond.signal();

    queueMutex.unlock();
  }

  public void flush()
  {
    queueMutex.lock();

    while (!workQueue.isEmpty())
      try {
      producerCond.await();
      } catch (InterruptedException e) { }

    queueMutex.unlock();

    throwThreadException();
  }

  private void setThreadException(Exception e)
  {
    //os::AutoMutex a(queueMutex);
    queueMutex.lock();

    if (threadException != null)
      return;

    threadException =
      new Exception("Exception on worker thread: "+e.getMessage());
  }

  private void throwThreadException()
  {
    //os::AutoMutex a(queueMutex);
    queueMutex.lock();

    if (threadException == null)
      return;

    Exception e = new Exception(threadException.getMessage());

    threadException = null;

    throw e;
  }

  private class QueueEntry {

    public QueueEntry() {
    }
    public boolean active;
    public Rect rect;
    public int encoding;
    public Decoder decoder;
    public ConnParams cp;
    public ModifiablePixelBuffer pb;
    public MemOutStream bufferStream;
    public Region affectedRegion;
  }

  private class DecodeThread implements Runnable {

    public DecodeThread(DecodeManager manager)
    {
      this.manager = manager;

      stopRequested = false;

      (thread = new Thread(this)).start();
    }

    public void stop()
    {
      //os::AutoMutex a(manager.queueMutex);
      manager.queueMutex.lock();

      if (!thread.isAlive())
        return;

      stopRequested = true;

      // We can't wake just this thread, so wake everyone
      manager.consumerCond.signalAll();
    }

    public void run()
    {
      manager.queueMutex.lock();

      while (!stopRequested) {
        QueueEntry entry;

        // Look for an available entry in the work queue
        entry = findEntry();
        if (entry == null) {
          // Wait and try again
          try {
            manager.consumerCond.await();
          } catch (InterruptedException e) { }
          continue;
        }

        // This is ours now
        entry.active = true;

        manager.queueMutex.unlock();

        // Do the actual decoding
        try {
          entry.decoder.decodeRect(entry.rect, entry.bufferStream.data(),
                                   entry.bufferStream.length(),
                                   entry.cp, entry.pb);
        } catch (com.tigervnc.rdr.Exception e) {
          manager.setThreadException(e);
        } catch(java.lang.Exception e) {
          assert(false);
        }

        manager.queueMutex.lock();

        // Remove the entry from the queue and give back the memory buffer
        manager.freeBuffers.addLast(entry.bufferStream);
        manager.workQueue.remove(entry);
        entry = null;

        // Wake the main thread in case it is waiting for a memory buffer
        manager.producerCond.signal();
        // This rect might have been blocking multiple other rects, so
        // wake up every worker thread
        if (manager.workQueue.size() > 1)
          manager.consumerCond.signalAll();
      }

      manager.queueMutex.unlock();
    }

    protected QueueEntry findEntry()
    {
      Iterator<QueueEntry> iter;
      Region lockedRegion = new Region();

      if (manager.workQueue.isEmpty())
        return null;

      if (!manager.workQueue.peek().active)
        return manager.workQueue.peek();

      next:for (iter = manager.workQueue.iterator(); iter.hasNext();) {
        QueueEntry entry;

        Iterator<QueueEntry> iter2;

        entry = iter.next();

        // Another thread working on this?
        if (entry.active) {
          lockedRegion.assign_union(entry.affectedRegion);
          continue next;
        }

        // If this is an ordered decoder then make sure this is the first
        // rectangle in the queue for that decoder
        if ((entry.decoder.flags & DecoderOrdered) != 0) {
          for (iter2 = manager.workQueue.iterator(); iter2.hasNext() && iter2 != iter;) {
            if (entry.encoding == (iter2.next()).encoding) {
              lockedRegion.assign_union(entry.affectedRegion);
              continue next;
            }
          }
        }

        // For a partially ordered decoder we must ask the decoder for each
        // pair of rectangles.
        if ((entry.decoder.flags & DecoderPartiallyOrdered) != 0) {
          for (iter2 = manager.workQueue.iterator(); iter2.hasNext() && iter2 != iter;) {
            QueueEntry entry2 = iter2.next();
            if (entry.encoding != entry2.encoding)
              continue;
            if (entry.decoder.doRectsConflict(entry.rect,
                                              entry.bufferStream.data(),
                                              entry.bufferStream.length(),
                                              entry2.rect,
                                              entry2.bufferStream.data(),
                                              entry2.bufferStream.length(),
                                              entry.cp))
              lockedRegion.assign_union(entry.affectedRegion);
              continue next;
          }
        }

        // Check overlap with earlier rectangles
        if (!lockedRegion.intersect(entry.affectedRegion).is_empty()) {
          lockedRegion.assign_union(entry.affectedRegion);
          continue next;
        }

        return entry;

      }

      return null;
    }

    private DecodeManager manager;
    private boolean stopRequested;

    private Thread thread;

  }

  private CConnection conn;
  private Decoder[] decoders;

  private ArrayDeque<MemOutStream> freeBuffers;
  private ArrayDeque<QueueEntry> workQueue;

  private ReentrantLock queueMutex;
  private Condition producerCond;
  private Condition consumerCond;

  private List<DecodeThread> threads;
  private com.tigervnc.rdr.Exception threadException;

}