Merge libs/ardour and gtk2_ardour with 2.0-ongoing R2837.
[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/basename.h>
38 #include <pbd/convert.h>
39
40 #include <ardour/ardour.h>
41 #include <ardour/session.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 static std::auto_ptr<ImportableSource>
56 open_importable_source (const string& path, nframes_t samplerate, ARDOUR::SrcQuality quality)
57 {
58         std::auto_ptr<ImportableSource> source(new ImportableSource(path));
59
60         if (source->samplerate() == samplerate) {
61                 return source;
62         }
63         
64         return std::auto_ptr<ImportableSource>(new ResampledImportableSource(path, samplerate, quality));
65 }
66
67 static std::string
68 get_non_existent_filename (const std::string& basename, uint channel, uint channels)
69 {
70         char buf[PATH_MAX+1];
71         bool goodfile = false;
72         string base(basename);
73
74         do {
75                 if (channels == 2) {
76                         if (channel == 0) {
77                                 snprintf (buf, sizeof(buf), "%s-L.wav", base.c_str());
78                         } else {
79                                 snprintf (buf, sizeof(buf), "%s-R.wav", base.c_str());
80                         }
81                 } else if (channels > 1) {
82                         snprintf (buf, sizeof(buf), "%s-c%d.wav", base.c_str(), channel+1);
83                 } else {
84                         snprintf (buf, sizeof(buf), "%s.wav", base.c_str());
85                 }
86                 
87                 if (Glib::file_test (buf, Glib::FILE_TEST_EXISTS)) {
88
89                         /* if the file already exists, we must come up with
90                          *  a new name for it.  for now we just keep appending
91                          *  _ to basename
92                          */
93
94                         base += "_";
95
96                 } else {
97
98                         goodfile = true;
99                 }
100
101         } while ( !goodfile);
102
103         return buf;
104 }
105
106 static vector<string>
107 get_paths_for_new_sources (const string& import_file_path, const string& session_dir, uint channels)
108 {
109         vector<string> new_paths;
110         const string basename = basename_nosuffix (import_file_path);
111
112         for (uint n = 0; n < channels; ++n) {
113
114                 std::string filepath;
115
116                 filepath = session_dir;
117                 filepath += '/';
118                 filepath += get_non_existent_filename (basename, n, channels); 
119
120                 new_paths.push_back (filepath);
121         }
122
123         return new_paths;
124 }
125
126 static bool
127 create_mono_sources_for_writing (const vector<string>& new_paths, Session& sess,
128                 uint samplerate, vector<boost::shared_ptr<AudioFileSource> >& newfiles)
129 {
130         for (vector<string>::const_iterator i = new_paths.begin();
131                         i != new_paths.end(); ++i)
132         {
133                 boost::shared_ptr<Source> source;
134
135                 try
136                 {
137                         source = SourceFactory::createWritable (
138                                 DataType::AUDIO,
139                                 sess,
140                                 i->c_str(),
141                                 false, // destructive
142                                 samplerate
143                                 );
144                 }
145                 catch (const failed_constructor& err)
146                 {
147                         error << string_compose (_("Unable to create file %1 during import"), *i) << endmsg;
148                         return false;
149                 }
150
151                 newfiles.push_back(boost::dynamic_pointer_cast<AudioFileSource>(source));
152         }
153         return true;
154 }
155
156 static Glib::ustring
157 compose_status_message (const string& path,
158                         uint file_samplerate,
159                         uint session_samplerate,
160                         uint current_file,
161                         uint total_files)
162 {
163         if (file_samplerate != session_samplerate) {
164                 return string_compose (_("converting %1\n(resample from %2KHz to %3KHz)\n(%4 of %5)"),
165                                        Glib::path_get_basename (path),
166                                        file_samplerate/1000.0f,
167                                        session_samplerate/1000.0f,
168                                        current_file, total_files);
169         }
170
171         return  string_compose (_("converting %1\n(%2 of %3)"), 
172                                 Glib::path_get_basename (path),
173                                 current_file, total_files);
174 }
175
176 static void
177 write_audio_data_to_new_files (ImportableSource* source, Session::import_status& status,
178                                vector<boost::shared_ptr<AudioFileSource> >& newfiles)
179 {
180         const nframes_t nframes = ResampledImportableSource::blocksize;
181         uint channels = source->channels();
182
183         boost::scoped_array<float> data(new float[nframes * channels]);
184         vector<boost::shared_array<Sample> > channel_data;
185
186         for (uint n = 0; n < channels; ++n) {
187                 channel_data.push_back(boost::shared_array<Sample>(new Sample[nframes]));
188         }
189         
190         uint read_count = 0;
191         status.progress = 0.0f;
192
193         while (!status.cancel) {
194
195                 nframes_t nread, nfread;
196                 uint x;
197                 uint chn;
198
199                 if ((nread = source->read (data.get(), nframes)) == 0) {
200                         break;
201                 }
202                 nfread = nread / channels;
203
204                 /* de-interleave */
205
206                 for (chn = 0; chn < channels; ++chn) {
207
208                         nframes_t n;
209                         for (x = chn, n = 0; n < nfread; x += channels, ++n) {
210                                 channel_data[chn][n] = (Sample) data[x];
211                         }
212                 }
213
214                 /* flush to disk */
215
216                 for (chn = 0; chn < channels; ++chn) {
217                         newfiles[chn]->write (channel_data[chn].get(), nfread);
218                 }
219
220                 read_count += nread;
221                 status.progress = read_count / (source->ratio () * source->length() * channels);
222         }
223 }
224
225 static void
226 remove_file_source (boost::shared_ptr<AudioFileSource> file_source)
227 {
228         ::unlink (file_source->path().c_str());
229 }
230
231 void
232 Session::import_audiofiles (import_status& status)
233 {
234         uint32_t cnt = 1;
235         typedef vector<boost::shared_ptr<AudioFileSource> > AudioSources;
236         AudioSources all_new_sources;
237
238         status.sources.clear ();
239         
240         for (vector<Glib::ustring>::iterator p = status.paths.begin();
241                         p != status.paths.end() && !status.cancel;
242                         ++p, ++cnt)
243         {
244                 std::auto_ptr<ImportableSource> source;
245
246                 try
247                 {
248                         source = open_importable_source (*p, frame_rate(), status.quality);
249                 }
250                 catch (const failed_constructor& err)
251                 {
252                         error << string_compose(_("Import: cannot open input sound file \"%1\""), (*p)) << endmsg;
253                         status.done = status.cancel = true;
254                         return;
255                 }
256
257                 vector<string> new_paths = get_paths_for_new_sources (*p,
258                                 get_best_session_directory_for_new_source (),
259                                 source->channels());
260                 
261                 AudioSources newfiles;
262
263                 status.cancel = !create_mono_sources_for_writing (new_paths, *this, frame_rate(), newfiles);
264
265                 // copy on cancel/failure so that any files that were created will be removed below
266                 std::copy (newfiles.begin(), newfiles.end(), std::back_inserter(all_new_sources));
267
268                 if (status.cancel) break;
269
270                 for (AudioSources::iterator i = newfiles.begin(); i != newfiles.end(); ++i) {
271                         (*i)->prepare_for_peakfile_writes ();
272                 }
273
274                 status.doing_what = compose_status_message (*p, source->samplerate(),
275                                 frame_rate(), cnt, status.paths.size());
276
277                 write_audio_data_to_new_files (source.get(), status, newfiles);
278         }
279
280         if (!status.cancel) {
281                 struct tm* now;
282                 time_t xnow;
283                 time (&xnow);
284                 now = localtime (&xnow);
285                 status.freeze = true;
286
287                 /* flush the final length(s) to the header(s) */
288
289                 for (AudioSources::iterator x = all_new_sources.begin();
290                                 x != all_new_sources.end(); ++x)
291                 {
292                         (*x)->update_header(0, *now, xnow);
293                         (*x)->done_with_peakfile_writes ();
294                 }
295
296                 /* save state so that we don't lose these new Sources */
297
298                 save_state (_name);
299
300                 std::copy (all_new_sources.begin(), all_new_sources.end(),
301                                 std::back_inserter(status.sources));
302         } else {
303                 // this can throw...but it seems very unlikely
304                 std::for_each (all_new_sources.begin(), all_new_sources.end(), remove_file_source);
305         }
306
307         status.done = true;
308 }
309