Merging from trunk
[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     $Id$
19 */
20
21 #include <cstdio>
22 #include <cstdlib>
23 #include <string>
24 #include <climits>
25 #include <cerrno>
26 #include <unistd.h>
27 #include <sys/stat.h>
28 #include <time.h>
29
30 #include <sndfile.h>
31 #include <samplerate.h>
32
33 #include <glibmm.h>
34
35 #include <pbd/basename.h>
36
37 #include <ardour/ardour.h>
38 #include <ardour/session.h>
39 #include <ardour/audio_diskstream.h>
40 #include <ardour/sndfilesource.h>
41 #include <ardour/sndfile_helpers.h>
42 #include <ardour/audioregion.h>
43
44 #include "i18n.h"
45
46 using namespace ARDOUR;
47 using namespace PBD;
48
49 #define BLOCKSIZE 4096U
50
51 int
52 Session::import_audiofile (import_status& status)
53 {
54         SNDFILE *in;
55         AudioFileSource **newfiles = 0;
56         AudioRegion::SourceList sources;
57         SF_INFO info;
58         float *data = 0;
59         Sample **channel_data = 0;
60         char * workbuf = 0;
61         long nfiles = 0;
62         long n;
63         string basepath;
64         string sounds_dir;
65         jack_nframes_t so_far;
66         char buf[PATH_MAX+1];
67         int ret = -1;
68         vector<string> new_paths;
69         struct tm* now;
70         string tmp_convert_file;
71         
72         status.new_regions.clear ();
73
74         if ((in = sf_open (status.pathname.c_str(), SFM_READ, &info)) == 0) {
75                 error << string_compose(_("Import: cannot open input sound file \"%1\""), status.pathname) << endmsg;
76                 return -1;
77         } else {
78                 if ((uint32_t) info.samplerate != frame_rate()) {
79                         sf_close(in);
80                         status.doing_what = _("resampling audio");
81                         // resample to session frame_rate
82                         if (sample_rate_convert(status, status.pathname, tmp_convert_file)) {
83                                 if ((in = sf_open (tmp_convert_file.c_str(), SFM_READ, &info)) == 0) {
84                                         error << string_compose(_("Import: cannot open converted sound file \"%1\""), tmp_convert_file) << endmsg;
85                                         return -1;
86                                 }
87                         } else if (!status.cancel){
88                                 // error
89                                 error << string_compose(_("Import: error while resampling sound file \"%1\""), status.pathname) << endmsg;
90                                 return -1;
91                         } else {
92                                 // canceled
93                                 goto out;
94                         }
95                 }
96         }
97
98         newfiles = new AudioFileSource *[info.channels];
99         for (n = 0; n < info.channels; ++n) {
100                 newfiles[n] = 0;
101         }
102         
103         sounds_dir = discover_best_sound_dir ();
104         basepath = PBD::basename_nosuffix (status.pathname);
105
106         for (n = 0; n < info.channels; ++n) {
107
108                 bool goodfile = false;
109
110                 do {
111                         if (info.channels == 2) {
112                                 if (n == 0) {
113                                         snprintf (buf, sizeof(buf), "%s%s-L.wav", sounds_dir.c_str(), basepath.c_str());
114                                 } else {
115                                         snprintf (buf, sizeof(buf), "%s%s-R.wav", sounds_dir.c_str(), basepath.c_str());
116                                 }
117                         } else if (info.channels > 1) {
118                                 snprintf (buf, sizeof(buf), "%s%s-c%lu.wav", sounds_dir.c_str(), basepath.c_str(), n+1);
119                         } else {
120                                 snprintf (buf, sizeof(buf), "%s%s.wav", sounds_dir.c_str(), basepath.c_str());
121                         }
122
123                         if (::access (buf, F_OK) == 0) {
124
125                                 /* if the file already exists, we must come up with
126                                  *  a new name for it.  for now we just keep appending
127                                  *  _ to basepath
128                                  */
129                                 
130                                 basepath += "_";
131
132                         } else {
133
134                                 goodfile = true;
135                         }
136
137                 } while ( !goodfile);
138
139                         
140                 try { 
141                         newfiles[n] = new SndFileSource (buf, 
142                                                          Config->get_native_file_data_format(),
143                                                          Config->get_native_file_header_format(),
144                                                          frame_rate ());
145                 }
146
147                 catch (failed_constructor& err) {
148                         error << string_compose(_("Session::import_audiofile: cannot open new file source for channel %1"), n+1) << endmsg;
149                         goto out;
150                 }
151
152                 new_paths.push_back (buf);
153                 nfiles++;
154         }
155         
156         
157         data = new float[BLOCKSIZE * info.channels];
158         channel_data = new Sample * [ info.channels ];
159         workbuf = new char[BLOCKSIZE * 4];
160         
161         for (n = 0; n < info.channels; ++n) {
162                 channel_data[n] = new Sample[BLOCKSIZE];
163         }
164
165         so_far = 0;
166
167         status.doing_what = _("converting audio");
168         status.progress = 0.0;
169
170         while (!status.cancel) {
171
172                 long nread;
173                 long x;
174                 long chn;
175
176                 if ((nread = sf_readf_float (in, data, BLOCKSIZE)) == 0) {
177                         break;
178                 }
179
180                 /* de-interleave */
181                                 
182                 for (chn = 0; chn < info.channels; ++chn) {
183                         for (x = chn, n = 0; n < nread; x += info.channels, ++n) {
184                                 channel_data[chn][n] = (Sample) data[x];
185                         }
186                 }
187
188                 /* flush to disk */
189
190                 for (chn = 0; chn < info.channels; ++chn) {
191                         newfiles[chn]->write (channel_data[chn], nread, workbuf);
192                 }
193
194                 so_far += nread;
195                 status.progress = so_far / (float) (info.frames * info.channels);
196         }
197
198         if (status.multichan) {
199                 status.doing_what = _("building region");
200         } else {
201                 status.doing_what = _("building regions");
202         }
203
204         status.freeze = true;
205
206         time_t xnow;
207         time (&xnow);
208         now = localtime (&xnow);
209
210         if (status.cancel) {
211                 goto out;
212         }
213
214         if (status.multichan) {
215                 /* all sources are used in a single multichannel region */
216                 for (n = 0; n < nfiles && !status.cancel; ++n) {
217                         /* flush the final length to the header */
218                         newfiles[n]->update_header(0, *now, xnow);
219                         sources.push_back(newfiles[n]);
220                 }
221
222                 AudioRegion *r = new AudioRegion (sources, 0, newfiles[0]->length(), region_name_from_path (Glib::path_get_basename (basepath)),
223                                         0, AudioRegion::Flag (AudioRegion::DefaultFlags | AudioRegion::WholeFile));
224                 
225                 status.new_regions.push_back (r);
226
227         } else {
228                 for (n = 0; n < nfiles && !status.cancel; ++n) {
229
230                         /* flush the final length to the header */
231
232                         newfiles[n]->update_header(0, *now, xnow);
233
234                         /* The sources had zero-length when created, which means that the Session
235                            did not bother to create whole-file AudioRegions for them. Do it now.
236                         */
237                 
238                         AudioRegion *r = new AudioRegion (*newfiles[n], 0, newfiles[n]->length(), region_name_from_path (Glib::path_get_basename (newfiles[n]->name())),
239                                                 0, AudioRegion::Flag (AudioRegion::DefaultFlags | AudioRegion::WholeFile | AudioRegion::Import));
240
241                         status.new_regions.push_back (r);
242                 }
243         }
244         
245         /* save state so that we don't lose these new Sources */
246
247         if (!status.cancel) {
248                 save_state (_name);
249         }
250
251         ret = 0;
252
253   out:
254
255         if (data) {
256                 delete [] data;
257         }
258         if (workbuf) {
259                 delete [] workbuf;
260         }
261         
262         if (channel_data) {
263                 for (n = 0; n < info.channels; ++n) {
264                         delete [] channel_data[n];
265                 }
266                 delete [] channel_data;
267         }
268
269         if (status.cancel) {
270                 for (vector<AudioRegion *>::iterator i = status.new_regions.begin(); i != status.new_regions.end(); ++i) {
271                         delete *i;
272                 }
273
274                 for (vector<string>::iterator i = new_paths.begin(); i != new_paths.end(); ++i) {
275                         unlink ((*i).c_str());
276                 }
277         }
278
279         if (newfiles) {
280                 delete [] newfiles;
281         }
282
283         if (tmp_convert_file.length()) {
284                 unlink(tmp_convert_file.c_str());
285         }
286         
287         sf_close (in);
288         status.done = true;
289         return ret;
290 }
291
292 string
293 Session::build_tmp_convert_name(string infile)
294 {
295         string tmp_name(_path + "/." + Glib::path_get_basename (infile.c_str()) + "XXXXXX");
296         char* tmp = new char[tmp_name.length() + 1];
297         tmp_name.copy(tmp, string::npos);
298         tmp[tmp_name.length()] = 0;
299         mkstemp(tmp);
300         string outfile = tmp;
301         delete [] tmp;
302         
303         return outfile;
304 }
305
306 bool
307 Session::sample_rate_convert (import_status& status, string infile, string& outfile)
308 {       
309         float input [BLOCKSIZE] ;
310         float output [BLOCKSIZE] ;
311
312         SF_INFO         sf_info;
313         SRC_STATE*      src_state ;
314         SRC_DATA        src_data ;
315         int                     err ;
316         sf_count_t      output_count = 0 ;
317         sf_count_t  input_count = 0;
318
319         SNDFILE* in = sf_open(infile.c_str(), SFM_READ, &sf_info);
320         sf_count_t total_input_frames = sf_info.frames;
321         
322         outfile = build_tmp_convert_name(infile);
323         SNDFILE* out = sf_open(outfile.c_str(), SFM_RDWR, &sf_info);
324         if(!out) {
325                 error << string_compose(_("Import: could not open temp file: %1"), outfile) << endmsg;
326                 return false;
327         }
328         
329         sf_seek (in, 0, SEEK_SET) ;
330         sf_seek (out, 0, SEEK_SET) ;
331
332         /* Initialize the sample rate converter. */
333         if ((src_state = src_new (SRC_SINC_BEST_QUALITY, sf_info.channels, &err)) == 0) {       
334                 error << string_compose(_("Import: src_new() failed : %1"), src_strerror (err)) << endmsg ;
335                 return false ;
336         }
337
338         src_data.end_of_input = 0 ; /* Set this later. */
339
340         /* Start with zero to force load in while loop. */
341         src_data.input_frames = 0 ;
342         src_data.data_in = input ;
343
344         src_data.src_ratio = (1.0 * frame_rate()) / sf_info.samplerate ;
345
346         src_data.data_out = output ;
347         src_data.output_frames = BLOCKSIZE / sf_info.channels ;
348
349         while (!status.cancel) {
350                 /* If the input buffer is empty, refill it. */
351                 if (src_data.input_frames == 0) {       
352                         src_data.input_frames = sf_readf_float (in, input, BLOCKSIZE / sf_info.channels) ;
353                         src_data.data_in = input ;
354
355                         /* The last read will not be a full buffer, so snd_of_input. */
356                         if (src_data.input_frames < (int)BLOCKSIZE / sf_info.channels) {
357                                 src_data.end_of_input = SF_TRUE ;
358                         }
359                 } 
360
361                 if ((err = src_process (src_state, &src_data))) {
362                         error << string_compose(_("Import: %1"), src_strerror (err)) << endmsg ;
363                         return false ;
364                 } 
365
366                 /* Terminate if at end */
367                 if (src_data.end_of_input && src_data.output_frames_gen == 0) {
368                         break ;
369                 }
370
371                 /* Write output. */
372                 sf_writef_float (out, output, src_data.output_frames_gen) ;
373                 output_count += src_data.output_frames_gen ;
374                 input_count += src_data.input_frames_used;
375
376                 src_data.data_in += src_data.input_frames_used * sf_info.channels ;
377                 src_data.input_frames -= src_data.input_frames_used ;
378                 
379                 status.progress = (float) input_count / total_input_frames;
380         }
381
382         src_state = src_delete (src_state) ;
383         sf_close(in);
384         sf_close(out);
385
386         status.done = true;
387
388         if (status.cancel) {
389                 return false;
390         } else {
391                 return true ;
392         }
393 }