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