Check for cancel at the top of the main loop in Session::import_audiofile rather...
[ardour.git] / libs / ardour / import.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 <cstdio>
21 #include <cstdlib>
22 #include <string>
23 #include <climits>
24 #include <cerrno>
25 #include <unistd.h>
26 #include <sys/stat.h>
27 #include <time.h>
28
29 #include <sndfile.h>
30 #include <samplerate.h>
31
32 #include <glibmm.h>
33
34 #include <boost/scoped_array.hpp>
35 #include <boost/shared_array.hpp>
36
37 #include <pbd/convert.h>
38
39 #include <ardour/ardour.h>
40 #include <ardour/session.h>
41 #include <ardour/session_directory.h>
42 #include <ardour/audio_diskstream.h>
43 #include <ardour/sndfilesource.h>
44 #include <ardour/sndfile_helpers.h>
45 #include <ardour/audioregion.h>
46 #include <ardour/region_factory.h>
47 #include <ardour/source_factory.h>
48 #include <ardour/resampled_source.h>
49
50 #include "i18n.h"
51
52 using namespace ARDOUR;
53 using namespace PBD;
54
55 std::auto_ptr<ImportableSource>
56 open_importable_source (const string& path, nframes_t samplerate,
57                 ARDOUR::SrcQuality quality)
58 {
59         std::auto_ptr<ImportableSource> source(new ImportableSource(path));
60
61         if (source->samplerate() == samplerate) {
62                 return source;
63         }
64
65         return std::auto_ptr<ImportableSource>(
66                         new ResampledImportableSource(path, samplerate, quality)
67                         );
68 }
69
70 std::string
71 get_non_existent_filename (const std::string& basename, uint channel, uint channels)
72 {
73         char buf[PATH_MAX+1];
74         bool goodfile = false;
75         string base(basename);
76
77         do {
78                 if (channels == 2) {
79                         if (channel == 0) {
80                                 snprintf (buf, sizeof(buf), "%s-L.wav", base.c_str());
81                         } else {
82                                 snprintf (buf, sizeof(buf), "%s-R.wav", base.c_str());
83                         }
84                 } else if (channels > 1) {
85                         snprintf (buf, sizeof(buf), "%s-c%d.wav", base.c_str(), channel+1);
86                 } else {
87                         snprintf (buf, sizeof(buf), "%s.wav", base.c_str());
88                 }
89
90                 if (sys::exists (buf)) {
91
92                         /* if the file already exists, we must come up with
93                          *  a new name for it.  for now we just keep appending
94                          *  _ to basename
95                          */
96
97                         base += "_";
98
99                 } else {
100
101                         goodfile = true;
102                 }
103
104         } while ( !goodfile);
105
106         return buf;
107 }
108
109 void
110 write_audio_data_to_new_files (ImportableSource* source, Session::import_status& status,
111                 vector<boost::shared_ptr<AudioFileSource> >& newfiles)
112 {
113         const nframes_t nframes = ResampledImportableSource::blocksize;
114         uint channels = source->channels();
115
116         boost::scoped_array<float> data(new float[nframes * channels]);
117         vector<boost::shared_array<Sample> > channel_data;
118
119         for (uint n = 0; n < channels; ++n) {
120                 channel_data.push_back(boost::shared_array<Sample>(new Sample[nframes]));
121         }
122         
123         uint read_count = 0;
124         status.progress = 0.0f;
125
126         while (!status.cancel) {
127
128                 nframes_t nread, nfread;
129                 uint x;
130                 uint chn;
131
132                 if ((nread = source->read (data.get(), nframes)) == 0) {
133                         break;
134                 }
135                 nfread = nread / channels;
136
137                 /* de-interleave */
138
139                 for (chn = 0; chn < channels; ++chn) {
140
141                         nframes_t n;
142                         for (x = chn, n = 0; n < nfread; x += channels, ++n) {
143                                 channel_data[chn][n] = (Sample) data[x];
144                         }
145                 }
146
147                 /* flush to disk */
148
149                 for (chn = 0; chn < channels; ++chn) {
150                         newfiles[chn]->write (channel_data[chn].get(), nfread);
151                 }
152
153                 read_count += nread;
154                 status.progress = read_count / (source->ratio () * source->length() * channels);
155         }
156 }
157
158 int
159 Session::import_audiofile (import_status& status)
160 {
161         int ret = -1;
162         vector<string> new_paths;
163         uint32_t cnt = 1;
164
165         status.sources.clear ();
166         
167         for (vector<Glib::ustring>::iterator p = status.paths.begin();
168                         p != status.paths.end() && !status.cancel;
169                         ++p, ++cnt)
170         {
171                 std::auto_ptr<ImportableSource> source;
172
173                 try
174                 {
175                         source = open_importable_source (*p, frame_rate(), status.quality);
176                 }
177                 catch (const failed_constructor& err)
178                 {
179                         error << string_compose(_("Import: cannot open input sound file \"%1\""), (*p)) << endmsg;
180                         status.done = status.cancel = true;
181                         return -1;
182                 }
183
184                 vector<boost::shared_ptr<AudioFileSource> > newfiles;
185
186                 for (uint n = 0; n < source->channels(); ++n) {
187                         newfiles.push_back (boost::shared_ptr<AudioFileSource>());
188                 }
189
190                 SessionDirectory sdir(get_best_session_directory_for_new_source ());
191         
192                 const string basename = sys::basename (string(*p));
193
194                 for (uint n = 0; n < source->channels(); ++n) {
195
196                         std::string filename = get_non_existent_filename (basename, n, source->channels()); 
197
198                         sys::path filepath = sdir.sound_path() / filename;
199
200                         try { 
201                                 newfiles[n] = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createWritable (DataType::AUDIO, *this, filepath.to_string().c_str(), false, frame_rate()));
202                         }
203
204                         catch (failed_constructor& err) {
205                                 error << string_compose(_("Session::import_audiofile: cannot open new file source for channel %1"), n+1) << endmsg;
206                                 goto out;
207                         }
208
209                         new_paths.push_back (filepath.to_string());
210                         newfiles[n]->prepare_for_peakfile_writes ();
211                 }
212
213                 if ((nframes_t) source->samplerate() != frame_rate()) {
214                         status.doing_what = string_compose (_("converting %1\n(resample from %2KHz to %3KHz)\n(%4 of %5)"),
215                                                             sys::path(*p).leaf(),
216                                                             source->samplerate()/1000.0f,
217                                                             frame_rate()/1000.0f,
218                                                             cnt, status.paths.size());
219                                                             
220                 } else {
221                         status.doing_what = string_compose (_("converting %1\n(%2 of %3)"), 
222                                                             sys::path(*p).leaf(),
223                                                             cnt, status.paths.size());
224
225                 }
226
227                 write_audio_data_to_new_files (source.get(), status, newfiles);
228
229                 if (status.cancel) {
230                         goto out;
231                 }
232         
233                 std::copy (newfiles.begin(), newfiles.end(), std::back_inserter(status.sources));
234         }
235         
236         if (!status.cancel) {
237                 struct tm* now;
238                 time_t xnow;
239                 time (&xnow);
240                 now = localtime (&xnow);
241                 status.freeze = true;
242
243                 /* flush the final length(s) to the header(s) */
244
245                 for (SourceList::iterator x = status.sources.begin(); x != status.sources.end(); ++x) {
246                         boost::dynamic_pointer_cast<AudioFileSource>(*x)->update_header(0, *now, xnow);
247                         boost::dynamic_pointer_cast<AudioSource>(*x)->done_with_peakfile_writes ();
248                 }
249
250                 /* save state so that we don't lose these new Sources */
251
252                 save_state (_name);
253                 ret = 0;
254         }
255
256   out:
257
258         if (status.cancel) {
259
260                 status.sources.clear ();
261
262                 for (vector<string>::iterator i = new_paths.begin(); i != new_paths.end(); ++i) {
263                         sys::remove (*i);
264                 }
265         }
266
267         status.done = true;
268
269         return ret;
270 }