*** NEW CODING POLICY ***
[ardour.git] / libs / ardour / quantize.cc
1 /*
2     Copyright (C) 2004 Paul Davis 
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include "pbd/basename.h"
21
22 #include "ardour/types.h"
23 #include "ardour/quantize.h"
24 #include "ardour/session.h"
25 #include "ardour/smf_source.h"
26 #include "ardour/midi_region.h"
27 #include "ardour/tempo.h"
28
29 #include "i18n.h"
30
31 using namespace std;
32 using namespace ARDOUR;
33
34
35 /** Quantize notes, valid for MIDI regions only.
36  *
37  * Q is the quantize value in beats, ie 1.0 = quantize to beats,
38  * 0.25 = quantize to beats/4, etc.
39  */
40 Quantize::Quantize (Session& s, double q)
41         : Filter (s)
42         , _q(q)
43 {
44 }
45
46 Quantize::~Quantize ()
47 {
48 }
49
50 int
51 Quantize::run (boost::shared_ptr<Region> r)
52 {
53         boost::shared_ptr<MidiRegion> region = boost::dynamic_pointer_cast<MidiRegion>(r);
54         if (!region)
55                 return -1;
56
57         // FIXME: how to make a whole file region if it isn't?
58         //assert(region->whole_file());
59
60         boost::shared_ptr<MidiSource> src = region->midi_source(0);
61         src->load_model();
62
63         boost::shared_ptr<MidiModel> model = src->model();
64         
65         for (Evoral::Sequence<MidiModel::TimeType>::Notes::iterator i = model->notes().begin();
66                         i != model->notes().end(); ++i) {
67                 const double new_time = lrint((*i)->time() / _q) * _q;
68                 double new_dur = lrint((*i)->length() / _q) * _q;
69                 if (new_dur == 0.0)
70                         new_dur = _q;
71                 
72                 (*i)->set_time(new_time);
73                 (*i)->set_length(new_dur);
74         }
75
76         model->set_edited(true);
77
78         return 0;
79 }