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