fix rect redraw problem(s); make zoom range rect visible again at the right time...
[ardour.git] / gtk2_ardour / editor_audio_import.cc
1 /*
2     Copyright (C) 2000-2006 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 <pbd/pthread_utils.h>
21 #include <pbd/basename.h>
22
23 #include <gtkmm2ext/choice.h>
24 #include <gtkmm2ext/window_title.h>
25
26 #include <ardour/session.h>
27 #include <ardour/audioplaylist.h>
28 #include <ardour/audioregion.h>
29 #include <ardour/audio_diskstream.h>
30 #include <ardour/utils.h>
31 #include <ardour/audio_track.h>
32 #include <ardour/audioplaylist.h>
33 #include <ardour/audiofilesource.h>
34 #include <ardour/region_factory.h>
35 #include <ardour/source_factory.h>
36 #include <pbd/memento_command.h>
37
38 #include "ardour_ui.h"
39 #include "editor.h"
40 #include "sfdb_ui.h"
41 #include "editing.h"
42 #include "audio_time_axis.h"
43 #include "utils.h"
44
45 #include "i18n.h"
46
47 using namespace std;
48 using namespace ARDOUR;
49 using namespace PBD;
50 using namespace sigc;
51 using namespace Gtk;
52 using namespace Gtkmm2ext;
53 using namespace Editing;
54 using Glib::ustring;
55
56 /* Functions supporting the incorporation of external (non-captured) audio material into ardour */
57
58 void
59 Editor::add_external_audio_action (ImportMode mode)
60 {
61         nframes_t& pos = edit_cursor->current_frame;
62         AudioTrack* track = 0;
63
64         if (!selection->tracks.empty()) {
65                 AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*>(selection->tracks.front());
66                 if (atv) {
67                         track = atv->audio_track();
68                 }
69         }
70
71         bring_in_external_audio (mode, track, pos, false);
72 }
73
74 void
75 Editor::bring_in_external_audio (ImportMode mode, AudioTrack* track, nframes_t& pos, bool prompt)
76 {
77         if (session == 0) {
78                 MessageDialog msg (0, _("You can't import or embed an audiofile until you have a session loaded."));
79                 msg.run ();
80                 return;
81         }
82
83         SoundFileOmega sfdb (_("Add existing audio to session"), session);
84         sfdb.set_mode (mode);
85
86         switch (sfdb.run()) {
87         case SoundFileOmega::ResponseImport:
88                 do_import (sfdb.get_paths(), sfdb.get_split(), sfdb.get_mode(), track, pos, prompt);
89                 break;
90                 
91         case SoundFileOmega::ResponseEmbed:
92                 do_embed (sfdb.get_paths(), sfdb.get_split(), sfdb.get_mode(), track, pos, prompt);
93                 break;
94
95         default:
96                 break;
97         }
98 }
99
100 void
101 Editor::do_import (vector<ustring> paths, bool split, ImportMode mode, AudioTrack* track, nframes_t& pos, bool prompt)
102 {
103         /* SFDB sets "multichan" to true to indicate "split channels"
104            so reverse the setting to match the way libardour
105            interprets it.
106         */
107         
108         import_status.multichan = !split;
109
110         if (interthread_progress_window == 0) {
111                 build_interthread_progress_window ();
112         }
113
114         vector<ustring> to_import;
115
116         for (vector<ustring>::iterator a = paths.begin(); a != paths.end(); ++a) {
117
118                 to_import.clear ();
119                 to_import.push_back (*a);
120
121                 import_sndfile (to_import, mode, track, pos);
122         }
123
124         interthread_progress_window->hide_all ();
125 }
126
127 void
128 Editor::do_embed (vector<ustring> paths, bool split, ImportMode mode, AudioTrack* track, nframes_t& pos, bool prompt)
129 {
130         bool multiple_files = paths.size() > 1;
131         bool check_sample_rate = true;
132         vector<ustring>::iterator a;
133
134         for (a = paths.begin(); a != paths.end(); ) {
135
136                 cerr << "Considering embed of " << (*a) << endl;
137         
138                 Glib::ustring path = *a;
139                 Glib::ustring pair_base;
140                 vector<ustring> to_embed;
141
142                 to_embed.push_back (path);
143                 a = paths.erase (a);
144
145                 if (path_is_paired (path, pair_base)) {
146
147                         ustring::size_type len = pair_base.length();
148
149                         for (vector<Glib::ustring>::iterator b = paths.begin(); b != paths.end(); ) {
150
151                                 if (((*b).substr (0, len) == pair_base) && ((*b).length() == path.length())) {
152
153                                         to_embed.push_back (*b);
154                                                 
155                                         /* don't process this one again */
156
157                                         b = paths.erase (b);
158                                         break;
159
160                                 } else {
161                                         ++b;
162                                 }
163                         }
164                 }
165
166                 if (to_embed.size() > 1) {
167
168                         vector<string> choices;
169
170                         choices.push_back (string_compose (_("Import as a %1 region"),
171                                                            to_embed.size() > 2 ? _("multichannel") : _("stereo")));
172                         choices.push_back (_("Import as multiple regions"));
173                         
174                         Choice chooser (string_compose (_("Paired files detected (%1, %2 ...).\nDo you want to:"),
175                                                                    to_embed[0],
176                                                                    to_embed[1]),
177                                                    choices);
178                         
179                         if (chooser.run () == 0) {
180                                 
181                                 /* keep them paired */
182
183                                 if (embed_sndfile (to_embed, split, multiple_files, check_sample_rate, mode, track, pos, prompt) < -1) {
184                                         break;
185                                 }
186
187                         } else {
188
189                                 /* one thing per file */
190
191                                 vector<ustring> foo;
192
193                                 for (vector<ustring>::iterator x = to_embed.begin(); x != to_embed.end(); ++x) {
194
195                                         foo.clear ();
196                                         foo.push_back (*x);
197
198                                         if (embed_sndfile (foo, split, multiple_files, check_sample_rate, mode, track, pos, prompt) < -1) {
199                                                 break;
200                                         }
201                                 }
202                         }
203
204                 } else {
205                         
206                         if (embed_sndfile (to_embed, split, multiple_files, check_sample_rate, mode, track, pos, prompt) < -1) {
207                                 break;
208                         }
209                 }
210         }
211         
212         if (a == paths.end()) {
213                 session->save_state ("");
214         }
215 }
216
217 int
218 Editor::import_sndfile (vector<ustring> paths, ImportMode mode, AudioTrack* track, nframes_t& pos)
219 {
220         WindowTitle title = string_compose (_("importing %1"), paths.front());
221
222         interthread_progress_window->set_title (title.get_string());
223         interthread_progress_window->set_position (Gtk::WIN_POS_MOUSE);
224         interthread_progress_window->show_all ();
225         interthread_progress_bar.set_fraction (0.0f);
226         interthread_cancel_label.set_text (_("Cancel Import"));
227         current_interthread_info = &import_status;
228
229         import_status.paths = paths;
230         import_status.done = false;
231         import_status.cancel = false;
232         import_status.freeze = false;
233         import_status.done = 0.0;
234         
235         interthread_progress_connection = Glib::signal_timeout().connect 
236                 (bind (mem_fun(*this, &Editor::import_progress_timeout), (gpointer) 0), 100);
237         
238         track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
239         ARDOUR_UI::instance()->flush_pending ();
240
241         /* start import thread for this spec. this will ultimately call Session::import_audiofile()
242            and if successful will add the file(s) as a region to the session region list.
243         */
244         
245         pthread_create_and_store ("import", &import_status.thread, 0, _import_thread, this);
246         pthread_detach (import_status.thread);
247         
248         while (!(import_status.done || import_status.cancel)) {
249                 gtk_main_iteration ();
250         }
251
252         interthread_progress_window->hide ();
253         
254         import_status.done = true;
255         interthread_progress_connection.disconnect ();
256         
257         /* import thread finished - see if we should build a new track */
258         
259         if (!import_status.new_regions.empty()) {
260                 boost::shared_ptr<AudioRegion> region (import_status.new_regions.front());
261                 finish_bringing_in_audio (region, region->n_channels(), region->n_channels(), track, pos, mode);
262         }
263
264         track_canvas.get_window()->set_cursor (*current_canvas_cursor);
265         return 0;
266 }
267
268 int
269 Editor::embed_sndfile (vector<Glib::ustring> paths, bool split, bool multiple_files, bool& check_sample_rate, ImportMode mode, 
270                        AudioTrack* track, nframes_t& pos, bool prompt)
271 {
272         boost::shared_ptr<AudioFileSource> source;
273         SourceList sources;
274         boost::shared_ptr<AudioRegion> region;
275         string linked_path;
276         SoundFileInfo finfo;
277         ustring region_name;
278         uint32_t input_chan = 0;
279         uint32_t output_chan = 0;
280         int ret = 0;
281
282         track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
283         ARDOUR_UI::instance()->flush_pending ();
284
285         for (vector<Glib::ustring>::iterator p = paths.begin(); p != paths.end(); ++p) {
286
287                 ustring path = *p;
288
289                 /* lets see if we can link it into the session */
290                 
291                 linked_path = session->sound_dir();
292                 linked_path += '/';
293                 linked_path += Glib::path_get_basename (path);
294                 
295                 if (link (path.c_str(), linked_path.c_str()) == 0) {
296                         
297                         /* there are many reasons why link(2) might have failed.
298                            but if it succeeds, we now have a link in the
299                            session sound dir that will protect against
300                            unlinking of the original path. nice.
301                         */
302                         
303                         path = linked_path;
304                 }
305                 
306                 /* note that we temporarily truncated _id at the colon */
307                 
308                 string error_msg;
309                 
310                 if (!AudioFileSource::get_soundfile_info (path, finfo, error_msg)) {
311                         error << string_compose(_("Editor: cannot open file \"%1\", (%2)"), selection, error_msg ) << endmsg;
312                         goto out;
313                 }
314                 
315                 if (check_sample_rate  && (finfo.samplerate != (int) session->frame_rate())) {
316                         vector<string> choices;
317                         
318                         if (multiple_files) {
319                                 choices.push_back (_("Cancel entire import"));
320                                 choices.push_back (_("Don't embed it"));
321                                 choices.push_back (_("Embed all without questions"));
322                         
323                                 Gtkmm2ext::Choice rate_choice (
324                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), 
325                                                         short_path (path, 40)),
326                                         choices, false);
327                                 
328                                 int resx = rate_choice.run ();
329                                 
330                                 switch (resx) {
331                                 case 0: /* stop a multi-file import */
332                                 case 1: /* don't import this one */
333                                         ret = -1;
334                                         goto out;
335                                 case 2: /* do it, and the rest without asking */
336                                         check_sample_rate = false;
337                                         break;
338                                 case 3: /* do it */
339                                         break;
340                                 default:
341                                         ret = -2;
342                                         goto out;
343                                 }
344                         } else {
345                                 choices.push_back (_("Cancel"));
346                                 choices.push_back (_("Embed it anyway"));
347                         
348                                 Gtkmm2ext::Choice rate_choice (
349                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), path),
350                                         choices, false);
351                                 
352                                 int resx = rate_choice.run ();
353                                 
354                                 switch (resx) {
355                                 case 0: /* don't import */
356                                         ret = -1;
357                                         goto out;
358                                 case 1: /* do it */
359                                         break;
360                                 default:
361                                         ret = -2;
362                                         goto out;
363                                 }
364                         }
365                 }
366                 
367                 track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
368                 ARDOUR_UI::instance()->flush_pending ();
369         
370                 /* make the proper number of channels in the region */
371                 
372                 input_chan += finfo.channels;
373
374                 for (int n = 0; n < finfo.channels; ++n)
375                 {
376                         try {
377
378                                 /* check if we have this thing embedded already */
379
380                                 boost::shared_ptr<Source> s;
381
382                                 if ((s = session->source_by_path_and_channel (path, n)) == 0) {
383                                         cerr << "source doesn't exist yet\n";
384                                         source = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createReadable 
385                                                                                                (*session, path,  n,
386                                                                                                 (mode == ImportAsTapeTrack ? 
387                                                                                                  AudioFileSource::Destructive : 
388                                                                                                  AudioFileSource::Flag (0))));
389                                 } else {
390                                         source = boost::dynamic_pointer_cast<AudioFileSource> (s);
391                                 }
392
393                                 sources.push_back(source);
394                         } 
395                         
396                         catch (failed_constructor& err) {
397                                 error << string_compose(_("could not open %1"), path) << endmsg;
398                                 goto out;
399                         }
400                         
401                         ARDOUR_UI::instance()->flush_pending ();
402                 }
403         }
404
405         if (sources.empty()) {
406                 goto out;
407         }
408
409         if (sources[0]->natural_position() != 0) {
410                 pos = sources[0]->natural_position();
411         } 
412
413         region_name = region_name_from_path (paths.front(), (sources.size() > 1));
414         
415         region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (sources, 0, sources[0]->length(), region_name, 0,
416                                                                                   Region::Flag (Region::DefaultFlags|Region::WholeFile|Region::External)));
417
418         if (Config->get_output_auto_connect() & AutoConnectMaster) {
419                 output_chan = (session->master_out() ? session->master_out()->n_inputs() : input_chan);
420         } else {
421                 output_chan = input_chan;
422         }
423
424         finish_bringing_in_audio (region, input_chan, output_chan, track, pos, mode);
425         
426   out:
427         track_canvas.get_window()->set_cursor (*current_canvas_cursor);
428         return ret;
429 }
430
431 int
432 Editor::finish_bringing_in_audio (boost::shared_ptr<AudioRegion> region, uint32_t in_chans, uint32_t out_chans, AudioTrack* track, nframes_t& pos, ImportMode mode)
433 {
434         switch (mode) {
435         case ImportAsRegion:
436                 /* relax, its been done */
437                 break;
438                 
439         case ImportToTrack:
440                 if (track) {
441                         boost::shared_ptr<Playlist> playlist = track->diskstream()->playlist();
442                         
443                         boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
444                         begin_reversible_command (_("insert sndfile"));
445                         XMLNode &before = playlist->get_state();
446                         playlist->add_region (copy, pos);
447                         session->add_command (new MementoCommand<Playlist>(*playlist, &before, &playlist->get_state()));
448                         commit_reversible_command ();
449
450                         pos += region->length();
451                 }
452                 break;
453                 
454         case ImportAsTrack:
455         { 
456                 list<boost::shared_ptr<AudioTrack> > at (session->new_audio_track (in_chans, out_chans, Normal, 1));
457                 if (!at.empty()) {
458                         boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
459                         at.front()->diskstream()->playlist()->add_region (copy, pos);
460                 }
461                 break;
462         }
463
464         case ImportAsTapeTrack:
465         {
466                 list<boost::shared_ptr<AudioTrack> > at (session->new_audio_track (in_chans, out_chans, Destructive));
467                 if (!at.empty()) {
468                         boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
469                         at.front()->diskstream()->playlist()->add_region (copy, pos);
470                 }
471                 break;
472         }
473         }
474
475         return 0;
476 }
477
478 void *
479 Editor::_import_thread (void *arg)
480 {
481         PBD::ThreadCreated (pthread_self(), X_("Import"));
482
483         Editor *ed = (Editor *) arg;
484         return ed->import_thread ();
485 }
486
487 void *
488 Editor::import_thread ()
489 {
490         session->import_audiofile (import_status);
491         pthread_exit_pbd (0);
492         /*NOTREACHED*/
493         return 0;
494 }
495
496 gint
497 Editor::import_progress_timeout (void *arg)
498 {
499         interthread_progress_label.set_text (import_status.doing_what);
500
501         if (import_status.freeze) {
502                 interthread_cancel_button.set_sensitive(false);
503         } else {
504                 interthread_cancel_button.set_sensitive(true);
505         }
506
507         if (import_status.doing_what == "building peak files") {
508                 interthread_progress_bar.pulse ();
509                 return FALSE;
510         } else {
511                 interthread_progress_bar.set_fraction (import_status.progress);
512         }
513
514         return !(import_status.done || import_status.cancel);
515 }
516