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