remove debug output
[ardour.git] / gtk2_ardour / editor_timefx.cc
1 /*
2     Copyright (C) 2000 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 <iostream>
21 #include <cstdlib>
22 #include <cmath>
23 #include <ctime>
24 #include <string>
25 #include <set>
26
27 #include "pbd/error.h"
28 #include "pbd/pthread_utils.h"
29 #include "pbd/memento_command.h"
30 #include "pbd/stateful_diff_command.h"
31
32 #include "ardour/audioregion.h"
33 #include "ardour/midi_stretch.h"
34 #include "ardour/pitch.h"
35 #include "ardour/region.h"
36 #include "ardour/session.h"
37 #include "ardour/stretch.h"
38
39 #include <gtkmm2ext/utils.h>
40
41 #include "audio_region_view.h"
42 #include "audio_time_axis.h"
43 #include "editor.h"
44 #include "region_selection.h"
45 #include "time_fx_dialog.h"
46
47 #ifdef USE_RUBBERBAND
48 #include <rubberband/RubberBandStretcher.h>
49 using namespace RubberBand;
50 #endif
51
52 #include "pbd/i18n.h"
53
54 using namespace std;
55 using namespace ARDOUR;
56 using namespace PBD;
57 using namespace Gtk;
58 using namespace Gtkmm2ext;
59
60 /** @return -1 in case of error, 1 if operation was cancelled by the user, 0 if everything went ok */
61 int
62 Editor::time_stretch (RegionSelection& regions, float fraction)
63 {
64         RegionList audio;
65         RegionList midi;
66         int aret;
67
68         begin_reversible_command (_("stretch/shrink"));
69
70         for (RegionSelection::iterator i = regions.begin(); i != regions.end(); ++i) {
71                 if  ((*i)->region()->data_type() == DataType::AUDIO) {
72                         audio.push_back ((*i)->region());
73                 } else if  ((*i)->region()->data_type() == DataType::MIDI) {
74                         midi.push_back ((*i)->region());
75                 }
76         }
77
78         if ((aret = time_fx (audio, fraction, false)) != 0) {
79                 commit_reversible_command ();
80                 return aret;
81         }
82
83         set<boost::shared_ptr<Playlist> > midi_playlists_affected;
84
85         for (RegionList::iterator i = midi.begin(); i != midi.end(); ++i) {
86                 boost::shared_ptr<Playlist> playlist = (*i)->playlist();
87
88                 if (playlist) {
89                         playlist->clear_changes ();
90                 }
91
92         }
93
94         ARDOUR::TimeFXRequest request;
95         request.time_fraction = fraction;
96
97         for (RegionList::iterator i = midi.begin(); i != midi.end(); ++i) {
98                 boost::shared_ptr<Playlist> playlist = (*i)->playlist();
99
100                 if (!playlist) {
101                         continue;
102                 }
103
104                 MidiStretch stretch (*_session, request);
105                 stretch.run (*i);
106
107                 playlist->replace_region (regions.front()->region(), stretch.results[0],
108                                           regions.front()->region()->position());
109                 midi_playlists_affected.insert (playlist);
110         }
111
112         for (set<boost::shared_ptr<Playlist> >::iterator p = midi_playlists_affected.begin(); p != midi_playlists_affected.end(); ++p) {
113                 _session->add_command (new StatefulDiffCommand (*p));
114         }
115
116         commit_reversible_command ();
117
118         return 0;
119 }
120
121 int
122 Editor::pitch_shift (RegionSelection& regions, float fraction)
123 {
124         RegionList rl;
125
126         for (RegionSelection::iterator i = regions.begin(); i != regions.end(); ++i) {
127                 rl.push_back ((*i)->region());
128         }
129
130         begin_reversible_command (_("pitch shift"));
131
132         int ret = time_fx (rl, fraction, true);
133
134         if (ret == 0) {
135                 commit_reversible_command ();
136         } else {
137                 abort_reversible_command ();
138         }
139
140         return ret;
141 }
142
143 /** @param val Percentage to time stretch by; ignored if pitch-shifting.
144  *  @param pitching true to pitch shift, false to time stretch.
145  *  @return -1 in case of error, 1 if operation was cancelled by the user, 0 if everything went ok */
146 int
147 Editor::time_fx (RegionList& regions, float val, bool pitching)
148 {
149         if (regions.empty()) {
150                 return 0;
151         }
152
153         const samplecnt_t oldlen = (samplecnt_t) (regions.front()->length());
154         const samplecnt_t newlen = (samplecnt_t) (regions.front()->length() * val);
155         const samplecnt_t pos = regions.front()->position ();
156
157         delete current_timefx;
158         current_timefx = new TimeFXDialog (*this, pitching, oldlen, newlen, pos);
159         current_timefx->regions = regions;
160
161         switch (current_timefx->run ()) {
162         case RESPONSE_ACCEPT:
163                 break;
164         default:
165                 current_timefx->hide ();
166                 return 1;
167         }
168
169         current_timefx->status = 0;
170         current_timefx->request.time_fraction = current_timefx->get_time_fraction ();
171         current_timefx->request.pitch_fraction = current_timefx->get_pitch_fraction ();
172
173         if (current_timefx->request.time_fraction == 1.0 &&
174             current_timefx->request.pitch_fraction == 1.0) {
175                 /* nothing to do */
176                 current_timefx->hide ();
177                 return 0;
178         }
179
180 #ifdef USE_RUBBERBAND
181         /* parse options */
182
183         RubberBandStretcher::Options options = 0;
184
185         bool realtime = false;
186         bool precise = false;
187         bool peaklock = true;
188         bool longwin = false;
189         bool shortwin = false;
190         bool preserve_formants = false;
191         string txt;
192
193         enum {
194                 NoTransients,
195                 BandLimitedTransients,
196                 Transients
197         } transients = Transients;
198
199         precise = current_timefx->precise_button.get_active();
200         preserve_formants = current_timefx->preserve_formants_button.get_active();
201
202         txt = current_timefx->stretch_opts_selector.get_active_text ();
203
204         for (int i = 0; i <= 6; i++) {
205                 if (txt == rb_opt_strings[i]) {
206                         rb_current_opt = i;
207                         break;
208                 }
209         }
210
211         int rb_mode = rb_current_opt;
212
213         if (pitching /*&& rb_current_opt == 6*/) {
214                 /* The timefx dialog does not show the "stretch_opts_selector"
215                  * when pitch-shifting.  So the most recently used option from
216                  * "Time Stretch" would be used (if any). That may even be
217                  * "resample without preserving pitch", which would be invalid.
218                  *
219                  * TODO: also show stretch_opts_selector when pitching (except the option
220                  * to not preserve pitch) and use separate  rb_current_opt when pitching.
221                  *
222                  * Actually overhaul this the dialog and processing opts below and use rubberband's
223                  * "Crispness" levels:
224                  *   -c 0   equivalent to --no-transients --no-lamination --window-long
225                  *   -c 1   equivalent to --detector-soft --no-lamination --window-long (for piano)
226                  *   -c 2   equivalent to --no-transients --no-lamination
227                  *   -c 3   equivalent to --no-transients
228                  *   -c 4   equivalent to --bl-transients
229                  *   -c 5   default processing options
230                  *   -c 6   equivalent to --no-lamination --window-short (may be good for drums)
231                  */
232                 rb_mode = 4;
233         }
234
235         switch (rb_mode) {
236                 case 0:
237                         transients = NoTransients; peaklock = false; longwin = true; shortwin = false;
238                         break;
239                 case 1:
240                         transients = NoTransients; peaklock = false; longwin = false; shortwin = false;
241                         break;
242                 case 2:
243                         transients = NoTransients; peaklock = true; longwin = false; shortwin = false;
244                         break;
245                 case 3:
246                         transients = BandLimitedTransients; peaklock = true; longwin = false; shortwin = false;
247                         break;
248                 case 5:
249                         transients = Transients; peaklock = false; longwin = false; shortwin = true;
250                         break;
251                 case 6:
252                         transients = NoTransients;
253                         precise = true;
254                         preserve_formants = false;
255                         current_timefx->request.pitch_fraction = 1.0 / current_timefx->request.time_fraction;
256                         shortwin = true;
257                         // peaklock = false;
258                         break;
259                 default:
260                         /* default/4 */
261                         transients = Transients; peaklock = true; longwin = false; shortwin = false;
262                         break;
263         };
264
265         if (realtime)          options |= RubberBandStretcher::OptionProcessRealTime;
266         if (precise)           options |= RubberBandStretcher::OptionStretchPrecise;
267         if (preserve_formants) options |= RubberBandStretcher::OptionFormantPreserved;
268         if (!peaklock)         options |= RubberBandStretcher::OptionPhaseIndependent;
269         if (longwin)           options |= RubberBandStretcher::OptionWindowLong;
270         if (shortwin)          options |= RubberBandStretcher::OptionWindowShort;
271
272         if (pitching)          options |= RubberBandStretcher::OptionPitchHighQuality;
273
274         switch (transients) {
275         case NoTransients:
276                 options |= RubberBandStretcher::OptionTransientsSmooth;
277                 break;
278         case BandLimitedTransients:
279                 options |= RubberBandStretcher::OptionTransientsMixed;
280                 break;
281         case Transients:
282                 options |= RubberBandStretcher::OptionTransientsCrisp;
283                 break;
284         }
285
286         current_timefx->request.opts = (int) options;
287 #else
288         current_timefx->request.quick_seek = current_timefx->quick_button.get_active();
289         current_timefx->request.antialias = !current_timefx->antialias_button.get_active();
290 #endif
291         current_timefx->request.done = false;
292         current_timefx->request.cancel = false;
293
294         /* re-connect the cancel button and delete events */
295
296         current_timefx->first_cancel.disconnect();
297         current_timefx->first_delete.disconnect();
298
299         current_timefx->first_cancel = current_timefx->cancel_button->signal_clicked().connect
300                 (sigc::mem_fun (current_timefx, &TimeFXDialog::cancel_in_progress));
301         current_timefx->first_delete = current_timefx->signal_delete_event().connect
302                 (sigc::mem_fun (current_timefx, &TimeFXDialog::delete_in_progress));
303
304         current_timefx->start_updates ();
305
306         if (pthread_create_and_store ("timefx", &current_timefx->request.thread, timefx_thread, current_timefx)) {
307                 current_timefx->hide ();
308                 error << _("timefx cannot be started - thread creation error") << endmsg;
309                 return -1;
310         }
311
312         pthread_detach (current_timefx->request.thread);
313
314         while (!current_timefx->request.done && !current_timefx->request.cancel) {
315                 gtk_main_iteration ();
316         }
317
318         pthread_join (current_timefx->request.thread, 0);
319
320         current_timefx->hide ();
321         return current_timefx->status;
322 }
323
324 void
325 Editor::do_timefx ()
326 {
327         boost::shared_ptr<Playlist> playlist;
328         boost::shared_ptr<Region>   new_region;
329         set<boost::shared_ptr<Playlist> > playlists_affected;
330
331         uint32_t const N = current_timefx->regions.size ();
332
333         for (RegionList::iterator i = current_timefx->regions.begin(); i != current_timefx->regions.end(); ++i) {
334                 boost::shared_ptr<Playlist> playlist = (*i)->playlist();
335
336                 if (playlist) {
337                         playlist->clear_changes ();
338                 }
339         }
340
341         for (RegionList::iterator i = current_timefx->regions.begin(); i != current_timefx->regions.end(); ++i) {
342
343                 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (*i);
344
345                 if (!region || (playlist = region->playlist()) == 0) {
346                         continue;
347                 }
348
349                 if (current_timefx->request.cancel) {
350                         /* we were cancelled */
351                         /* XXX what to do about playlists already affected ? */
352                         current_timefx->status = 1;
353                         return;
354                 }
355
356                 Filter* fx;
357
358                 if (current_timefx->pitching) {
359                         fx = new Pitch (*_session, current_timefx->request);
360                 } else {
361 #ifdef USE_RUBBERBAND
362                         fx = new RBStretch (*_session, current_timefx->request);
363 #else
364                         fx = new STStretch (*_session, current_timefx->request);
365 #endif
366                 }
367
368                 current_timefx->descend (1.0 / N);
369
370                 if (fx->run (region, current_timefx)) {
371                         current_timefx->status = -1;
372                         current_timefx->request.done = true;
373                         delete fx;
374                         return;
375                 }
376
377                 if (!fx->results.empty()) {
378                         new_region = fx->results.front();
379
380                         playlist->replace_region (region, new_region, region->position());
381                         playlists_affected.insert (playlist);
382                 }
383
384                 current_timefx->ascend ();
385                 delete fx;
386         }
387
388         for (set<boost::shared_ptr<Playlist> >::iterator p = playlists_affected.begin(); p != playlists_affected.end(); ++p) {
389                 _session->add_command (new StatefulDiffCommand (*p));
390         }
391
392         current_timefx->status = 0;
393         current_timefx->request.done = true;
394 }
395
396 void*
397 Editor::timefx_thread (void *arg)
398 {
399         SessionEvent::create_per_thread_pool ("timefx events", 64);
400
401         TimeFXDialog* tsd = static_cast<TimeFXDialog*>(arg);
402
403         pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, 0);
404
405         tsd->editor.do_timefx ();
406
407         /* GACK! HACK! sleep for a bit so that our request buffer for the GUI
408            event loop doesn't die before any changes we made are processed
409            by the GUI ...
410         */
411
412 #ifdef PLATFORM_WINDOWS
413         Glib::usleep(2 * G_USEC_PER_SEC);
414 #else
415         struct timespec t = { 2, 0 };
416         nanosleep (&t, 0);
417 #endif
418         return 0;
419 }