Merged with trunk R1612.
[ardour.git] / libs / ardour / session_timefx.cc
1 /*
2     Copyright (C) 2003 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 <cerrno>
21 #include <stdexcept>
22
23 #include <pbd/basename.h>
24
25 #include <soundtouch/SoundTouch.h>
26
27 #include <ardour/session.h>
28 #include <ardour/audioregion.h>
29 #include <ardour/sndfilesource.h>
30 #include <ardour/region_factory.h>
31 #include <ardour/source_factory.h>
32
33 #include "i18n.h"
34
35 using namespace std;
36 using namespace ARDOUR;
37 using namespace PBD;
38 using namespace soundtouch;
39
40 boost::shared_ptr<AudioRegion>
41 Session::tempoize_region (TimeStretchRequest& tsr)
42 {
43         SourceList sources;
44         SourceList::iterator it;
45         boost::shared_ptr<AudioRegion> r;
46         SoundTouch st;
47         string region_name;
48         string ident = X_("-TIMEFX-");
49         float percentage;
50         nframes_t total_frames;
51         nframes_t done;
52         int c;
53         char buf[64];
54         string::size_type len;
55
56         /* the soundtouch code wants a *tempo* change percentage, which is 
57            of opposite sign to the length change.  
58         */
59
60         percentage = -tsr.fraction;
61
62         st.setSampleRate (frame_rate());
63         st.setChannels (1);
64         st.setTempoChange (percentage);
65         st.setPitchSemiTones (0);
66         st.setRateChange (0);
67         
68         st.setSetting(SETTING_USE_QUICKSEEK, tsr.quick_seek);
69         st.setSetting(SETTING_USE_AA_FILTER, tsr.antialias);
70
71         vector<string> names = tsr.region->master_source_names();
72
73         tsr.progress = 0.0f;
74         total_frames = tsr.region->length() * tsr.region->n_channels();
75         done = 0;
76
77         for (uint32_t i = 0; i < tsr.region->n_channels(); ++i) {
78
79                 string rstr;
80                 string::size_type existing_ident;
81                 
82                 if ((existing_ident = names[i].find (ident)) != string::npos) {
83                         rstr = names[i].substr (0, existing_ident);
84                 } else {
85                         rstr = names[i];
86                 }
87
88                 string path = path_from_region_name (PBD::basename_nosuffix (rstr), ident);
89                 
90                 if (path.length() == 0) {
91                         error << string_compose (_("tempoize: error creating name for new audio file based on %1"), tsr.region->name()) 
92                               << endmsg;
93                         goto out;
94                 }
95
96                 try {
97                         sources.push_back (boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createWritable (DataType::AUDIO, *this, path, false, frame_rate())));
98
99                 } catch (failed_constructor& err) {
100                         error << string_compose (_("tempoize: error creating new audio file %1 (%2)"), path, strerror (errno)) << endmsg;
101                         goto out;
102                 }
103
104         }
105         
106         try {
107                 const nframes_t bufsize = 16384;
108
109                 for (uint32_t i = 0; i < sources.size(); ++i) {
110                         gain_t gain_buffer[bufsize];
111                         Sample buffer[bufsize];
112                         nframes_t pos = 0;
113                         nframes_t this_read = 0;
114
115                         boost::shared_ptr<AudioSource> asrc = boost::dynamic_pointer_cast<AudioSource>(sources[i]);
116                         if (!asrc) {
117                                 cerr << "FIXME: TimeFX for non-audio" << endl;
118                                 continue;
119                         }
120
121                         st.clear();
122                         while (tsr.running && pos < tsr.region->length()) {
123                                 nframes_t this_time;
124                         
125                                 this_time = min (bufsize, tsr.region->length() - pos);
126
127                                 /* read from the master (original) sources for the region, 
128                                    not the ones currently in use, in case it's already been 
129                                    subject to timefx.  */
130
131                                 if ((this_read = tsr.region->master_read_at (buffer, buffer, gain_buffer, pos + tsr.region->position(), this_time)) != this_time) {
132                                         error << string_compose (_("tempoize: error reading data from %1"), sources[i]->name()) << endmsg;
133                                         goto out;
134                                 }
135                         
136                                 pos += this_read;
137                                 done += this_read;
138
139                                 tsr.progress = (float) done / total_frames;
140                                 
141                                 st.putSamples (buffer, this_read);
142                         
143                                 while ((this_read = st.receiveSamples (buffer, bufsize)) > 0 && tsr.running) {
144                                         if (asrc->write (buffer, this_read) != this_read) {
145                                                 error << string_compose (_("error writing tempo-adjusted data to %1"), sources[i]->name()) << endmsg;
146                                                 goto out;
147                                         }
148                                 }
149                         }
150                 
151                         if (tsr.running) {
152                                 st.flush ();
153                         }
154                 
155                         while (tsr.running && (this_read = st.receiveSamples (buffer, bufsize)) > 0) {
156                                 if (asrc->write (buffer, this_read) != this_read) {
157                                         error << string_compose (_("error writing tempo-adjusted data to %1"), sources[i]->name()) << endmsg;
158                                         goto out;
159                                 }
160                         }
161                 }
162         } catch (runtime_error& err) {
163                 error << _("timefx code failure. please notify ardour-developers.") << endmsg;
164                 error << err.what() << endmsg;
165                 goto out;
166         }
167
168         time_t now;
169         struct tm* xnow;
170         time (&now);
171         xnow = localtime (&now);
172
173         for (it = sources.begin(); it != sources.end(); ++it) {
174                 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*it);
175                 if (afs) {
176                         afs->update_header (tsr.region->position(), *xnow, now);
177                 }
178         }
179
180         len = tsr.region->name().length();
181
182         while (--len) {
183                 if (!isdigit (tsr.region->name()[len])) {
184                         break;
185                 }
186         }
187
188         if (len == 0) {
189                 
190                 region_name = tsr.region->name() + ".t000";
191
192         } else {
193
194                 if (tsr.region->name()[len] == 't') {
195                         c = atoi (tsr.region->name().substr(len+1));
196
197                         snprintf (buf, sizeof (buf), "t%03d", ++c);
198                         region_name = tsr.region->name().substr (0, len) + buf;
199
200                 } else {
201                         
202                         /* not sure what this is, just tack the suffix on to it */
203
204                         region_name = tsr.region->name() + ".t000";
205                 }
206                         
207         }
208
209         r = (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (sources, 0, sources.front()->length(), region_name,
210                                                                               0, AudioRegion::Flag (AudioRegion::DefaultFlags | AudioRegion::WholeFile))));
211              
212   out:
213
214         if (sources.size()) {
215
216                 /* if we failed to complete for any reason, mark the new file 
217                    for deletion.
218                 */
219
220                 if ((!r || !tsr.running)) {
221                         for (it = sources.begin(); it != sources.end(); ++it) {
222                                 (*it)->mark_for_remove ();
223                         }
224                 }
225
226                 sources.clear ();
227         }
228         
229         /* if the process was cancelled, delete the region */
230
231         if (!tsr.running) {
232                 r.reset ();
233         }
234         
235         return r;
236 }