File: TimeRulerLayer.cpp

package info (click to toggle)
sonic-visualiser 5.2.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 24,744 kB
  • sloc: cpp: 158,888; ansic: 11,920; sh: 1,785; makefile: 517; xml: 64; perl: 31
file content (449 lines) | stat: -rw-r--r-- 13,269 bytes parent folder | download | duplicates (2)
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*-  vi:set ts=8 sts=4 sw=4: */

/*
    Sonic Visualiser
    An audio file viewer and annotation editor.
    Centre for Digital Music, Queen Mary, University of London.
    This file copyright 2006 Chris Cannam.
   
    This program 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.  See the file
    COPYING included with this distribution for more information.
*/

#include "TimeRulerLayer.h"

#include "LayerFactory.h"

#include "data/model/Model.h"
#include "base/RealTime.h"
#include "base/Preferences.h"
#include "view/View.h"

#include "ColourDatabase.h"
#include "PaintAssistant.h"

#include <QPainter>

#include <iostream>
#include <cmath>
#include <stdexcept>

//#define DEBUG_TIME_RULER_LAYER 1


namespace sv {

TimeRulerLayer::TimeRulerLayer() :
    SingleColourLayer(),
    m_labelHeight(LabelTop)
{
    
}

void
TimeRulerLayer::setModel(ModelId model)
{
    if (m_model == model) return;
    m_model = model;
    emit modelReplaced();
}

bool
TimeRulerLayer::snapToFeatureFrame(LayerGeometryProvider *v, sv_frame_t &frame,
                                   int &resolution, SnapType snap, int) const
{
    auto model = ModelById::get(m_model);
    if (!model) {
        resolution = 1;
        return false;
    }

    bool q;
    int64_t tickUSec = getMajorTickUSec(v, q);
    RealTime rtick = RealTime::fromMicroseconds(tickUSec);
    sv_samplerate_t rate = model->getSampleRate();
    
    RealTime rt = RealTime::frame2RealTime(frame, rate);
    double ratio = rt / rtick;

    int rounded = int(ratio);
    RealTime rdrt = rtick * rounded;

    sv_frame_t left = RealTime::realTime2Frame(rdrt, rate);
    resolution = int(RealTime::realTime2Frame(rtick, rate));
    sv_frame_t right = left + resolution;

//    SVDEBUG << "TimeRulerLayer::snapToFeatureFrame: type "
//              << int(snap) << ", frame " << frame << " (time "
//              << rt << ", tick " << rtick << ", rounded " << rdrt << ") ";

    switch (snap) {

    case SnapLeft:
        frame = left;
        break;

    case SnapRight:
        frame = right;
        break;

    case SnapNeighbouring:
    {
        int dl = -1, dr = -1;
        int x = v->getXForFrame(frame);

        if (left > v->getStartFrame() &&
            left < v->getEndFrame()) {
            dl = abs(v->getXForFrame(left) - x);
        }

        if (right > v->getStartFrame() &&
            right < v->getEndFrame()) {
            dr = abs(v->getXForFrame(right) - x);
        }

        int fuzz = ViewManager::scalePixelSize(2);

        if (dl >= 0 && dr >= 0) {
            if (dl < dr) {
                if (dl <= fuzz) {
                    frame = left;
                }
            } else {
                if (dr < fuzz) {
                    frame = right;
                }
            }
        } else if (dl >= 0) {
            if (dl <= fuzz) {
                frame = left;
            }
        } else if (dr >= 0) {
            if (dr <= fuzz) {
                frame = right;
            }
        }
    }
    }

//    SVDEBUG << " -> " << frame << " (resolution = " << resolution << ")" << endl;

    return true;
}

int64_t
TimeRulerLayer::getMajorTickUSec(LayerGeometryProvider *v,
                                 bool &quarterTicks) const
{
    // return value is in microseconds
    auto model = ModelById::get(m_model);
    if (!model || !v) return 1000 * 1000;

    sv_samplerate_t sampleRate = model->getSampleRate();
    if (!sampleRate) return 1000 * 1000;

    sv_frame_t startFrame = v->getStartFrame();
    sv_frame_t endFrame = v->getEndFrame();
    if (endFrame == startFrame) {
        endFrame = startFrame + 1;
    }

    int exampleWidth = QFontMetrics(QFont()).horizontalAdvance("10:42.987654");
    int minPixelSpacing = v->getXForViewX(exampleWidth);

    RealTime rtStart = RealTime::frame2RealTime(startFrame, sampleRate);
    RealTime rtEnd = RealTime::frame2RealTime(endFrame, sampleRate);

    int count = v->getPaintWidth() / minPixelSpacing;
    if (count < 1) count = 1;
    RealTime rtGap = (rtEnd - rtStart) / count;

#ifdef DEBUG_TIME_RULER_LAYER
    SVCERR << "zoomLevel = " << v->getRoundedZoomLevel()
           << ", startFrame = " << startFrame << ", endFrame = " << endFrame
           << ", rtStart = " << rtStart << ", rtEnd = " << rtEnd
           << ", paint width = " << v->getPaintWidth()
           << ", minPixelSpacing = " << minPixelSpacing
           << ", count = " << count << ", rtGap = " << rtGap << endl;
#endif

    int64_t incus;
    quarterTicks = false;

    if (rtGap.sec > 0) {
        incus = 1000 * 1000;
        int s = rtGap.sec;
        if (s > 0) { incus *= 5; s /= 5; }
        if (s > 0) { incus *= 2; s /= 2; }
        if (s > 0) { incus *= 6; s /= 6; quarterTicks = true; }
        if (s > 0) { incus *= 5; s /= 5; quarterTicks = false; }
        if (s > 0) { incus *= 2; s /= 2; }
        if (s > 0) { incus *= 6; s /= 6; quarterTicks = true; }
        while (s > 0) {
            incus *= 10;
            s /= 10;
            quarterTicks = false;
        }
    } else if (rtGap.msec() > 0) {
        incus = 1000;
        int ms = rtGap.msec();
        if (ms > 0) { incus *= 10; ms /= 10; }
        if (ms > 0) { incus *= 10; ms /= 10; }
        if (ms > 0) { incus *= 5; ms /= 5; }
        if (ms > 0) { incus *= 2; ms /= 2; }
    } else {
        incus = 1;
        int us = rtGap.usec();
        if (us > 0) { incus *= 10; us /= 10; }
        if (us > 0) { incus *= 10; us /= 10; }
        if (us > 0) { incus *= 5; us /= 5; }
        if (us > 0) { incus *= 2; us /= 2; }
    }

#ifdef DEBUG_TIME_RULER_LAYER
    SVCERR << "getMajorTickUSec: returning incus = " << incus << endl;
#endif

    return incus;
}

int
TimeRulerLayer::getXForUSec(LayerGeometryProvider *v, double us) const
{
    auto model = ModelById::get(m_model);
    sv_samplerate_t sampleRate = model->getSampleRate();
    double dframe = (us * sampleRate) / 1000000.0;
    double eps = 1e-7;
    sv_frame_t frame = sv_frame_t(floor(dframe + eps));
    int x;

    ZoomLevel zoom = v->getRoundedZoomLevel();

    if (zoom.zone == ZoomLevel::FramesPerPixel) {
            
        frame /= zoom.level;
        frame *= zoom.level; // so frame corresponds to an exact pixel
        
        x = v->getXForFrame(frame);
        
    } else {

        double off = dframe - double(frame);
        int x0 = v->getXForFrame(frame);
        int x1 = v->getXForFrame(frame + 1);
        
        x = int(x0 + off * (x1 - x0));
    }

#ifdef DEBUG_TIME_RULER_LAYER
    cerr << "Considering frame = " << frame << ", x = " << x << endl;
#endif
        
    return x;
}

void
TimeRulerLayer::paint(LayerGeometryProvider *v, QPainter &paint, QRect rect) const
{
#ifdef DEBUG_TIME_RULER_LAYER
    SVCERR << "TimeRulerLayer::paint (" << rect.x() << "," << rect.y()
           << ") [" << rect.width() << "x" << rect.height() << "]" << endl;
#endif
    
    auto model = ModelById::get(m_model);
    if (!model || !model->isOK()) return;

    sv_samplerate_t sampleRate = model->getSampleRate();
    if (!sampleRate) return;

    sv_frame_t startFrame = v->getFrameForX(rect.x() - 50);

#ifdef DEBUG_TIME_RULER_LAYER
    SVCERR << "start frame = " << startFrame << endl;
#endif

    bool quarter = false;
    int64_t incus = getMajorTickUSec(v, quarter);
    int64_t us = int64_t(floor(1000.0 * 1000.0 * (double(startFrame) /
                                                  double(sampleRate))));
    us = (us / incus) * incus - incus;

#ifdef DEBUG_TIME_RULER_LAYER
    SVCERR << "start us = " << us << " at step " << incus << endl;
#endif

    Preferences *prefs = Preferences::getInstance();
    auto origTimeTextMode = prefs->getTimeToTextMode();
    if (incus < 1000) {
        // Temporarily switch to usec display mode (if we aren't using
        // it already)
        prefs->setTimeToTextModeUnsaved(Preferences::TimeToTextUs);
    }
    
    // Calculate the number of ticks per increment -- approximate
    // values for x and frame counts here will do, no rounding issue.
    // We always use the exact incus in our calculations for where to
    // draw the actual ticks or lines.

    int minPixelSpacing = v->getXForViewX(50);
    sv_frame_t incFrame = lrint((double(incus) * sampleRate) / 1000000);
    int incX = int(round(v->getRoundedZoomLevel().framesToPixels(double(incFrame))));
    int ticks = 10;
    if (incX < minPixelSpacing * 2) {
        ticks = quarter ? 4 : 5;
    }

    QColor greyColour = getPartialShades(v)[1];

    paint.save();

    // Do not label time zero - we now overlay an opaque area over
    // time < 0 which would cut it in half
    int minlabel = 1; // us
    
    while (1) {

        // frame is used to determine where to draw the lines, so it
        // needs to correspond to an exact pixel (so that we don't get
        // a different pixel when scrolling a small amount and
        // re-drawing with a different start frame).

        double dus = double(us);

        int x = getXForUSec(v, dus);

        if (x >= rect.x() + rect.width() + 50) {
#ifdef DEBUG_TIME_RULER_LAYER
            SVCERR << "X well out of range, ending here" << endl;
#endif
            break;
        }

        if (x >= rect.x() - 50 && us >= minlabel) {

            RealTime rt = RealTime::fromMicroseconds(us);

#ifdef DEBUG_TIME_RULER_LAYER
            SVCERR << "X in range, drawing line here for time " << rt.toText() << " (usec = " << us << ")" << endl;
#endif

            QString text(QString::fromStdString(rt.toText()));
            
            QFontMetrics metrics = paint.fontMetrics();
            int tw = metrics.horizontalAdvance(text);

            if (tw < 50 &&
                (x < rect.x() - tw/2 ||
                 x >= rect.x() + rect.width() + tw/2)) {
#ifdef DEBUG_TIME_RULER_LAYER
                SVCERR << "hm, maybe X isn't in range after all (x = " << x << ", tw = " << tw << ", rect.x() = " << rect.x() << ", rect.width() = " << rect.width() << ")" << endl;
#endif
            }

            paint.setPen(greyColour);
            paint.drawLine(x, 0, x, v->getPaintHeight());

            paint.setPen(getBaseQColor());
            paint.drawLine(x, 0, x, 5);
            paint.drawLine(x, v->getPaintHeight() - 6, x, v->getPaintHeight() - 1);

            int y;
            switch (m_labelHeight) {
            default:
            case LabelTop:
                y = 6 + metrics.ascent();
                break;
            case LabelMiddle:
                y = v->getPaintHeight() / 2 - metrics.height() / 2 + metrics.ascent();
                break;
            case LabelBottom:
                y = v->getPaintHeight() - metrics.height() + metrics.ascent() - 6;
            }

            if (v->getViewManager() && v->getViewManager()->getOverlayMode() !=
                ViewManager::NoOverlays) {

                if (v->getView()->getLayer(0) == this) {
                    // backmost layer, don't worry about outlining the text
                    paint.drawText(x+2 - tw/2, y, text);
                } else {
                    PaintAssistant::drawVisibleText(v, paint, x+2 - tw/2, y, text, PaintAssistant::OutlinedText);
                }
            }
        }

        paint.setPen(greyColour);

        for (int i = 1; i < ticks; ++i) {

            dus = double(us) + (i * double(incus)) / ticks;

            x = getXForUSec(v, dus);

            if (x < rect.x() || x >= rect.x() + rect.width()) {
#ifdef DEBUG_TIME_RULER_LAYER
//                SVCERR << "tick " << i << ": X out of range, going on to next tick" << endl;
#endif
                continue;
            }

#ifdef DEBUG_TIME_RULER_LAYER
            SVCERR << "tick " << i << " in range, drawing at " << x << endl;
#endif

            int sz = 5;
            if (ticks == 10) {
                if ((i % 2) == 1) {
                    if (i == 5) {
                        paint.drawLine(x, 0, x, v->getPaintHeight());
                    } else sz = 3;
                } else {
                    sz = 7;
                }
            }
            paint.drawLine(x, 0, x, sz);
            paint.drawLine(x, v->getPaintHeight() - sz - 1, x, v->getPaintHeight() - 1);
        }

        us += incus;
    }
    
    prefs->setTimeToTextModeUnsaved(origTimeTextMode);

    paint.restore();
}

int
TimeRulerLayer::getDefaultColourHint(bool darkbg, bool &impose)
{
    impose = true;
    return ColourDatabase::getInstance()->getColourIndex
        (QString(darkbg ? "White" : "Black"));
}

QString TimeRulerLayer::getLayerPresentationName() const
{
    LayerFactory *factory = LayerFactory::getInstance();
    QString layerName = factory->getLayerPresentationName
        (factory->getLayerType(this));
    return layerName;
}

void
TimeRulerLayer::toXml(QTextStream &stream,
                      QString indent, QString extraAttributes) const
{
    SingleColourLayer::toXml(stream, indent, extraAttributes);
}

void
TimeRulerLayer::setProperties(const LayerAttributes &attributes)
{
    SingleColourLayer::setProperties(attributes);
}

} // end namespace sv