Improve the readability of Session::import_audiofile
[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 vector<string>
110 get_paths_for_new_sources (const string& import_file_path, const string& session_dir, 
111                 uint channels)
112 {
113         vector<string> new_paths;
114         const string basename = sys::basename (import_file_path);
115         SessionDirectory sdir(session_dir);
116
117         for (uint n = 0; n < channels; ++n) {
118
119                 std::string filename = get_non_existent_filename (basename, n, channels); 
120
121                 sys::path filepath = sdir.sound_path() / filename;
122
123                 new_paths.push_back (filepath.to_string());
124         }
125
126         return new_paths;
127 }
128
129 bool
130 create_mono_sources_for_writing (const vector<string>& new_paths, Session& sess,
131                 uint samplerate, vector<boost::shared_ptr<AudioFileSource> >& newfiles)
132 {
133         for (vector<string>::const_iterator i = new_paths.begin();
134                         i != new_paths.end(); ++i)
135         {
136                 boost::shared_ptr<Source> source;
137
138                 try
139                 {
140                         source = SourceFactory::createWritable (
141                                         DataType::AUDIO,
142                                         sess,
143                                         i->c_str(),
144                                         false, // destructive
145                                         samplerate
146                                         );
147                 }
148                 catch (const failed_constructor& err)
149                 {
150                         error << string_compose (_("Unable to create file %1 during import"), *i) << endmsg;
151                         return false;
152                 }
153
154                 newfiles.push_back(boost::dynamic_pointer_cast<AudioFileSource>(source));
155         }
156         return true;
157 }
158
159 Glib::ustring
160 compose_status_message (const string& path,
161                 uint file_samplerate,
162                 uint session_samplerate,
163                 uint current_file,
164                 uint total_files)
165 {
166         if (file_samplerate != session_samplerate) {
167                 return string_compose (_("converting %1\n(resample from %2KHz to %3KHz)\n(%4 of %5)"),
168                                 sys::path(path).leaf(),
169                                 file_samplerate/1000.0f,
170                                 session_samplerate/1000.0f,
171                                 current_file, total_files);
172         }
173
174         return  string_compose (_("converting %1\n(%2 of %3)"), 
175                         sys::path(path).leaf(),
176                         current_file, total_files);
177 }
178
179 void
180 write_audio_data_to_new_files (ImportableSource* source, Session::import_status& status,
181                 vector<boost::shared_ptr<AudioFileSource> >& newfiles)
182 {
183         const nframes_t nframes = ResampledImportableSource::blocksize;
184         uint channels = source->channels();
185
186         boost::scoped_array<float> data(new float[nframes * channels]);
187         vector<boost::shared_array<Sample> > channel_data;
188
189         for (uint n = 0; n < channels; ++n) {
190                 channel_data.push_back(boost::shared_array<Sample>(new Sample[nframes]));
191         }
192         
193         uint read_count = 0;
194         status.progress = 0.0f;
195
196         while (!status.cancel) {
197
198                 nframes_t nread, nfread;
199                 uint x;
200                 uint chn;
201
202                 if ((nread = source->read (data.get(), nframes)) == 0) {
203                         break;
204                 }
205                 nfread = nread / channels;
206
207                 /* de-interleave */
208
209                 for (chn = 0; chn < channels; ++chn) {
210
211                         nframes_t n;
212                         for (x = chn, n = 0; n < nfread; x += channels, ++n) {
213                                 channel_data[chn][n] = (Sample) data[x];
214                         }
215                 }
216
217                 /* flush to disk */
218
219                 for (chn = 0; chn < channels; ++chn) {
220                         newfiles[chn]->write (channel_data[chn].get(), nfread);
221                 }
222
223                 read_count += nread;
224                 status.progress = read_count / (source->ratio () * source->length() * channels);
225         }
226 }
227
228 void
229 remove_file_source (boost::shared_ptr<AudioFileSource> file_source)
230 {
231         sys::remove (std::string(file_source->path()));
232 }
233
234 int
235 Session::import_audiofile (import_status& status)
236 {
237         uint32_t cnt = 1;
238         typedef vector<boost::shared_ptr<AudioFileSource> > AudioSources;
239         AudioSources all_new_sources;
240
241         status.sources.clear ();
242         
243         for (vector<Glib::ustring>::iterator p = status.paths.begin();
244                         p != status.paths.end() && !status.cancel;
245                         ++p, ++cnt)
246         {
247                 std::auto_ptr<ImportableSource> source;
248
249                 try
250                 {
251                         source = open_importable_source (*p, frame_rate(), status.quality);
252                 }
253                 catch (const failed_constructor& err)
254                 {
255                         error << string_compose(_("Import: cannot open input sound file \"%1\""), (*p)) << endmsg;
256                         status.done = status.cancel = true;
257                         return -1;
258                 }
259
260                 vector<string> new_paths = get_paths_for_new_sources (*p,
261                                 get_best_session_directory_for_new_source (),
262                                 source->channels());
263
264                 AudioSources newfiles;
265
266                 status.cancel = !create_mono_sources_for_writing (new_paths, *this, frame_rate(), newfiles);
267
268                 // copy on cancel/failure so that any files that were created will be removed below
269                 std::copy (newfiles.begin(), newfiles.end(), std::back_inserter(all_new_sources));
270
271                 if (status.cancel) break;
272
273                 for (AudioSources::iterator i = newfiles.begin(); i != newfiles.end(); ++i) {
274                         (*i)->prepare_for_peakfile_writes ();
275                 }
276
277                 status.doing_what = compose_status_message (*p, source->samplerate(),
278                                 frame_rate(), cnt, status.paths.size());
279
280                 write_audio_data_to_new_files (source.get(), status, newfiles);
281         }
282         
283         int ret = -1;
284
285         if (!status.cancel) {
286                 struct tm* now;
287                 time_t xnow;
288                 time (&xnow);
289                 now = localtime (&xnow);
290                 status.freeze = true;
291
292                 /* flush the final length(s) to the header(s) */
293
294                 for (AudioSources::iterator x = all_new_sources.begin();
295                                 x != all_new_sources.end(); ++x)
296                 {
297                         (*x)->update_header(0, *now, xnow);
298                         (*x)->done_with_peakfile_writes ();
299                 }
300
301                 /* save state so that we don't lose these new Sources */
302
303                 save_state (_name);
304
305                 std::copy (all_new_sources.begin(), all_new_sources.end(),
306                                 std::back_inserter(status.sources));
307
308                 ret = 0;
309         } else {
310                 // this can throw...but it seems very unlikely
311                 std::for_each (all_new_sources.begin(), all_new_sources.end(), remove_file_source);
312         }
313
314         status.done = true;
315
316         return ret;
317 }