source: trunk/src_apollo/org/apollo/gui/WaveFormRenderProccessingUnit.java@ 355

Last change on this file since 355 was 355, checked in by bjn8, 16 years ago

Many fixes and usability improvements.

File size: 11.5 KB
Line 
1package org.apollo.gui;
2
3import java.awt.Graphics2D;
4import java.awt.image.BufferedImage;
5import java.util.LinkedList;
6
7import javax.sound.sampled.AudioFormat;
8
9import org.apollo.audio.ApolloSubjectChangedEvent;
10import org.apollo.mvc.AbstractSubject;
11import org.apollo.mvc.SubjectChangedEvent;
12
13public class WaveFormRenderProccessingUnit {
14
15 /** Limit the amount of render threads. */
16 private RenderThread[] renderThreads = new RenderThread[4];
17
18 private LinkedList<WaveFormRenderTask> taskQueue = new LinkedList<WaveFormRenderTask>();
19
20 private static WaveFormRenderProccessingUnit instance = new WaveFormRenderProccessingUnit(); // single design pattern
21
22 /**
23 * @return The singleton instance of the WaveFormRenderProccessingUnit
24 */
25 public static WaveFormRenderProccessingUnit getInstance() { // single design pattern
26 return instance;
27 }
28
29 private WaveFormRenderProccessingUnit() { // singleton design pattern
30 }
31
32 /**
33 * Queues a task for rendering as soon as possible (asynchronously).
34 *
35 * @param task
36 * The task to queue
37 *
38 * @throws NullPointerException
39 * If task is null.
40 *
41 * @throws IllegalArgumentException
42 * If task has been proccessed before (must not be re-used).
43 * Or if it is already queued for rendering.
44 */
45 public void queueTask(WaveFormRenderTask task) {
46 if (task == null) throw new NullPointerException("task");
47
48 // Ensure not re-using a WaveFormRenderTask
49 if (task.hasStarted()) throw new IllegalArgumentException("task");
50
51 // Add to the queue
52 synchronized (taskQueue) {
53
54 // Check that not already on the queue
55 if (taskQueue.contains(task)) {
56 throw new IllegalArgumentException("task");
57 }
58
59 taskQueue.add(task);
60
61
62 // If there is are dead thread, re-animate it to ensure
63 // the task begins as soon as possible.
64 for (int i = 0; i < renderThreads.length; i++) {
65
66 if (renderThreads[i] == null
67 || renderThreads[i].isFinishing()
68 || !renderThreads[i].isAlive()) {
69
70 renderThreads[i] = new RenderThread(i);
71 renderThreads[i].start();
72 break;
73 }
74
75 }
76
77 }
78
79
80 }
81
82 /**
83 * Cancels a task from rendering.
84 *
85 * @param task
86 * The task to cancel.
87 *
88 * @throws NullPointerException
89 * If task is null.
90 */
91 public void cancelTask(WaveFormRenderTask task) {
92 if (task == null) throw new NullPointerException("task");
93
94 task.keepRendering = false;
95 synchronized (taskQueue) {
96 taskQueue.remove(task);
97 }
98 }
99
100 /**
101 * Render of wave forms is done in a dedicated thread because some graphs may have
102 * to proccess / render a lot of samples depending on the zoom / size of the audio track.
103 *
104 * From a usability perspective, this means that the waveform can be computed accuratly
105 * because responce time is no longer an issue.
106 *
107 * @author Brook Novak
108 *
109 */
110 private class RenderThread extends Thread {
111
112 private WaveFormRenderTask currentTask;
113
114 private final static float AMPLITUDES_PER_PIXEL = 1.0f; // resolution: how many amplitudes per pixel to render
115 private final static int FRAME_RENDER_RATE = 2000; // The approximate amount of frames to render per pass
116
117 private boolean isFinishing = false;
118
119 public boolean isFinishing() {
120 return isFinishing;
121 }
122
123 /**
124 *
125 * @param audioBytes The reference to the audio bytes to render.
126 *
127 * @param frameLength in frames.
128 */
129 public RenderThread(int id) {
130 super("RenderThread" + id);
131 // Give renderering lowest priority
132 setPriority(Thread.MIN_PRIORITY);
133
134 }
135
136 @Override
137 public void run() {
138
139 while (true) {
140 // Grab a task from the queue
141 synchronized(taskQueue) {
142
143 if (taskQueue.isEmpty()) {
144 isFinishing = true;
145 return;
146 }
147 currentTask = taskQueue.remove();
148 }
149
150 // Perform rendering until the task has been cancelled
151 doRender();
152 }
153 }
154
155 private void doRender() {
156 assert(currentTask != null);
157 assert(!currentTask.hasStarted());
158
159 // Quick check
160 if (!currentTask.keepRendering) return;
161
162 currentTask.setState(WaveFormRenderTask.STATE_RENDERING);
163
164 Graphics2D g = null;
165
166 try {
167
168 int halfMaxHeight;
169 int bufferWidth;
170
171 // Create the graphics and prepare the buffer
172
173 synchronized(currentTask.imageBuffer) {
174
175 halfMaxHeight = currentTask.imageBuffer.getHeight() / 2;
176 bufferWidth = currentTask.imageBuffer.getWidth();
177
178 g = currentTask.imageBuffer.createGraphics();
179
180 g.setStroke(Strokes.SOLID_1);
181
182 // Clear the buffer with transparent pixels
183 g.setBackground(ApolloColorIndexedModels.KEY_COLOR);
184 g.clearRect(0, 0, bufferWidth, currentTask.imageBuffer.getHeight());
185
186 }
187
188 // Render waveforms in chunks - so that can cancel rendering and the
189 // widget can show progress incrementally
190 int lastXPosition = -1;
191 int lastYPosition = -1;
192
193 // Choose how many amplitudes to render in the graph. i.e. waveform resolution
194 int totalAmplitudes = Math.min((int)(bufferWidth * AMPLITUDES_PER_PIXEL), currentTask.frameLength); // get amount of amps to render
195 if (totalAmplitudes == 0) return;
196
197 int currentAmplitude = 0;
198
199 // Calculate the amount of frames to aggregate
200 int aggregationSize = currentTask.frameLength / totalAmplitudes;
201 assert(aggregationSize >= 1);
202
203 // Limit the amount of amplitudes to render (the small chunks) based on the
204 // aggregation size - since it correlation to proccess time.
205 int amplitudeCountPerPass = (FRAME_RENDER_RATE / aggregationSize);
206 if (amplitudeCountPerPass == 0) amplitudeCountPerPass = 1;
207
208 int renderStart;
209 int renderLength;
210
211 // render until finished or cancelled
212 while (currentTask.keepRendering && currentAmplitude < totalAmplitudes) {
213
214 renderStart = currentAmplitude * aggregationSize;
215
216 // At the last pass, render the last remaining bytes
217 renderLength = Math.min(
218 amplitudeCountPerPass * aggregationSize,
219 currentTask.frameLength - renderStart);
220
221 // At the last pass, be sure that the aggregate size does not exeed the render count
222 // so that last samples are not ignored
223 aggregationSize = Math.min(aggregationSize, renderLength);
224
225 // Perform the waveform rendering
226 float[] amps = currentTask.renderer.getSampleAmplitudes(
227 currentTask.audioBytes,
228 currentTask.startFrame + renderStart,
229 renderLength,
230 aggregationSize);
231
232 // Draw the rendered waveform to the buffer
233 synchronized(currentTask.imageBuffer) {
234
235 g.setColor(ApolloColorIndexedModels.WAVEFORM_COLOR);
236
237 if (aggregationSize == 1) {
238
239 for (float h : amps) {
240
241 int x = (int)(currentAmplitude * ((float)bufferWidth / (float)(totalAmplitudes - 1)));
242 int y = halfMaxHeight - (int)(h * halfMaxHeight);
243
244 if (currentAmplitude == 0) { // never draw line on first point
245
246 lastXPosition = 0;
247 lastYPosition = y;
248
249 } else {
250
251 g.drawLine(
252 lastXPosition,
253 lastYPosition,
254 x,
255 y);
256
257 lastXPosition = x;
258 lastYPosition = y;
259
260 }
261
262 currentAmplitude ++;
263 }
264
265 } else { // dual version - looks nicer and conceptually easy to see audio
266
267 for (int i = 0; i < amps.length; i+=2) {
268
269 float peak = amps[i];
270 float trough = amps[i + 1];
271
272 int x = (int)(currentAmplitude * ((float)bufferWidth / (float)(totalAmplitudes - 1)));
273 int ypeak = halfMaxHeight - (int)(peak * halfMaxHeight);
274 int ytrough = halfMaxHeight - (int)(trough * halfMaxHeight);
275
276 if (currentAmplitude == 0) { // never draw line on first point
277
278 lastXPosition = lastYPosition = 0;
279
280 } else {
281
282 g.drawLine(
283 x,
284 ypeak,
285 x,
286 ytrough);
287
288 lastXPosition = x;
289 lastYPosition = 0;
290
291 }
292
293 currentAmplitude ++;
294 }
295
296 }
297
298 }
299
300
301 } // next pass
302
303 // Lession learnt: do not request lots of requests to repaint
304 // later on the AWT Event queu otherwise it will get congested
305 // and will freeze up the interact for annoying periods of time.
306 currentTask.setState(WaveFormRenderTask.STATE_STOPPED);
307
308 } finally {
309
310 if (g != null) g.dispose();
311
312 // safety
313 if (!currentTask.isStopped())
314 currentTask.setState(WaveFormRenderTask.STATE_STOPPED);
315
316 currentTask = null;
317 }
318 }
319
320 }
321
322 /**
323 * A task descriptor for rendering wave forms via the WaveFormRenderProccessingUnit.
324 *
325 * Raises {@value ApolloSubjectChangedEvent#RENDER_TASK_INVALIDATION_RECOMENDATION}
326 * when the WaveFormRenderProccessingUnit recommends a refresh
327 * of the BufferedImage. This includes when the WaveFormRenderTask state changes
328 *
329 * The BufferedImage is always locked before handled by the render thread.
330 *
331 * Only can use these once... per render task. I.E. Do not re-use
332 *
333 * @author Brook Novak
334 *
335 */
336 public class WaveFormRenderTask extends AbstractSubject {
337
338 private boolean keepRendering = true; // a cancel flag
339
340 private int state = STATE_PENDING;
341
342 private static final int STATE_PENDING = 1;
343 private static final int STATE_RENDERING = 2;
344 private static final int STATE_STOPPED = 3;
345
346 private BufferedImage imageBuffer; // nullified when stopped.
347 private byte[] audioBytes; // nullified when stopped. - Arrays (not contents) are immutable so no need to worry about threading issues with indexes
348 private final int startFrame;
349 private final int frameLength; // in frames
350 private final WaveFormRenderer renderer;
351 private final boolean recommendInvalidations;
352
353 public WaveFormRenderTask(
354 BufferedImage imageBuffer,
355 byte[] audioBytes,
356 AudioFormat format,
357 int startFrame,
358 int frameLength,
359 boolean recommendInvalidations) {
360
361 assert(audioBytes != null);
362 assert(format != null);
363 assert(imageBuffer != null);
364 assert(((startFrame + frameLength) * format.getFrameSize()) <= audioBytes.length);
365
366 this.imageBuffer = imageBuffer;
367 this.audioBytes = audioBytes;
368 this.startFrame = startFrame;
369 this.frameLength = frameLength;
370 this.recommendInvalidations = recommendInvalidations;
371 renderer = new DualPeakTroughWaveFormRenderer(format);
372 }
373
374 private void setState(int newState) {
375 this.state = newState;
376
377 if (keepRendering) { // invalidate if cancel not requested
378 recommendInvalidation();
379 }
380
381 // Nullify expensive references when stopped so they can be freed by the garbage collector
382 if (state == STATE_STOPPED) {
383 audioBytes = null;
384 imageBuffer = null;
385 }
386
387 }
388
389 /**
390 *
391 * @return
392 * True if this is rendering .. thus being proccessed.
393 */
394 public boolean isRendering() {
395 return state == STATE_RENDERING;
396 }
397
398
399 /**
400 * <b>WARNING:</b> Think about the race conditions ... now cannot no when this may start therefore
401 * it is always safe to lock buffer if in pending state.
402 *
403 * @return
404 * True if this has not started to render
405 */
406 public boolean hasStarted() {
407 return state != STATE_PENDING;
408 }
409
410 /**
411 *
412 * @return
413 * True if has stopped
414 */
415 public boolean isStopped() {
416 return state == STATE_STOPPED;
417
418 }
419
420 private void recommendInvalidation() {
421 if (recommendInvalidations)
422 fireSubjectChangedLaterOnSwingThread(
423 new SubjectChangedEvent(ApolloSubjectChangedEvent.RENDER_TASK_INVALIDATION_RECOMENDATION));
424 }
425
426 }
427
428}
Note: See TracBrowser for help on using the repository browser.