limited history depth (no GUI yet); more work on import dialog and semantics
[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 <sys/types.h>
21 #include <sys/stat.h>
22 #include <errno.h>
23 #include <unistd.h>
24
25 #include <sndfile.h>
26
27 #include <pbd/pthread_utils.h>
28 #include <pbd/basename.h>
29 #include <pbd/shortpath.h>
30
31 #include <gtkmm2ext/choice.h>
32 #include <gtkmm2ext/window_title.h>
33
34 #include <ardour/session.h>
35 #include <ardour/audioplaylist.h>
36 #include <ardour/audioregion.h>
37 #include <ardour/audio_diskstream.h>
38 #include <ardour/utils.h>
39 #include <ardour/audio_track.h>
40 #include <ardour/audioplaylist.h>
41 #include <ardour/audiofilesource.h>
42 #include <ardour/region_factory.h>
43 #include <ardour/source_factory.h>
44 #include <pbd/memento_command.h>
45
46 #include "ardour_ui.h"
47 #include "editor.h"
48 #include "sfdb_ui.h"
49 #include "editing.h"
50 #include "audio_time_axis.h"
51 #include "utils.h"
52
53 #include "i18n.h"
54
55 using namespace std;
56 using namespace ARDOUR;
57 using namespace PBD;
58 using namespace sigc;
59 using namespace Gtk;
60 using namespace Gtkmm2ext;
61 using namespace Editing;
62 using Glib::ustring;
63
64 /* Functions supporting the incorporation of external (non-captured) audio material into ardour */
65
66 void
67 Editor::add_external_audio_action (ImportMode mode)
68 {
69 }
70
71 void
72 Editor::external_audio_dialog ()
73 {
74         vector<Glib::ustring> paths;
75
76         if (session == 0) {
77                 MessageDialog msg (0, _("You can't import or embed an audiofile until you have a session loaded."));
78                 msg.run ();
79                 return;
80         }
81
82         SoundFileBrowser browser (*this, _("Add existing audio"), session, selection->tracks.size());
83
84         browser.show_all ();
85
86         int response = browser.run ();
87
88                 switch (response) {
89         case RESPONSE_OK:
90                 break;
91         default:
92                 // cancel from the browser - we are done
93                 return;
94         }
95         
96         browser.hide ();
97
98         /* lets do it */
99         
100         paths = browser.get_paths ();
101
102         ImportPosition pos = browser.get_position ();
103         ImportMode mode = browser.get_mode ();
104         ImportChannel chns = browser.get_channel_disposition ();
105         nframes64_t where;
106
107         switch (pos) {
108         case ImportAtEditCursor:
109                 where = edit_cursor->current_frame;
110                 break;
111         case ImportAtTimestamp:
112                 where = -1;
113                 break;
114         case ImportAtPlayhead:
115                 where = playhead_cursor->current_frame;
116                 break;
117         case ImportAtStart:
118                 where = session->current_start_frame();
119                 break;
120         }
121
122         if (browser.import.get_active()) {
123                 do_import (paths, chns, mode, where);
124         } else {
125                 do_embed (paths, chns, mode, where);
126         }
127 }
128
129 void
130 Editor::do_import (vector<ustring> paths, ImportChannel chns, ImportMode mode, nframes64_t& pos)
131 {
132         switch (chns) {
133         case Editing::ImportDistinctChannels:
134                 import_status.multichan = false;
135                 break;
136
137         default:
138                 import_status.multichan = true;
139                 break;
140
141         }
142
143         if (interthread_progress_window == 0) {
144                 build_interthread_progress_window ();
145         }
146
147         vector<ustring> to_import;
148
149         for (vector<ustring>::iterator a = paths.begin(); a != paths.end(); ++a) {
150
151                 to_import.clear ();
152                 to_import.push_back (*a);
153
154                 import_sndfile (to_import, mode, pos);
155         }
156
157         interthread_progress_window->hide_all ();
158 }
159
160 bool
161 Editor::idle_do_embed (vector<ustring> paths, ImportChannel chns, ImportMode mode, nframes64_t& pos)
162 {
163         _do_embed (paths, chns, mode, pos);
164         return false;
165 }
166
167 void
168 Editor::do_embed (vector<ustring> paths, ImportChannel chns, ImportMode mode, nframes64_t& pos)
169 {
170 #ifdef GTKOSX
171         Glib::signal_idle().connect (bind (mem_fun (*this, &Editor::idle_do_embed), paths, chns, mode, pos));
172 #else
173         _do_embed (paths, chns, mode, pos);
174 #endif
175 }
176
177 void
178 Editor::_do_embed (vector<ustring> paths, ImportChannel chns, ImportMode mode, nframes64_t& pos)
179 {
180         bool multiple_files = paths.size() > 1;
181         bool check_sample_rate = true;
182         bool ok = false;
183         vector<ustring> to_embed;
184         
185
186         switch (chns) {
187         case Editing::ImportDistinctFiles:
188         case Editing::ImportDistinctChannels:
189                 for (vector<ustring>::iterator a = paths.begin(); a != paths.end(); ++a) {
190
191                         to_embed.clear ();
192                         to_embed.push_back (*a);
193
194                         if (embed_sndfile (to_embed, chns, multiple_files, check_sample_rate, mode, pos) < -1) {
195                                 goto out;
196                         }
197                 }
198                 break;
199
200         case Editing::ImportSerializeFiles:
201         case Editing::ImportMergeFiles:
202                 if (embed_sndfile (paths, chns, multiple_files, check_sample_rate, mode, pos) < -1) {
203                         goto out;
204                 }
205                 break;
206         }
207
208         ok = true;
209         
210   out:  
211         if (ok) {
212                 session->save_state ("");
213         }
214 }
215
216 int
217 Editor::import_sndfile (vector<ustring> paths, ImportMode mode, nframes64_t& pos)
218 {
219         WindowTitle title = string_compose (_("importing %1"), paths.front());
220
221         interthread_progress_window->set_title (title.get_string());
222         interthread_progress_window->set_position (Gtk::WIN_POS_MOUSE);
223         interthread_progress_window->show_all ();
224         interthread_progress_bar.set_fraction (0.0f);
225         interthread_cancel_label.set_text (_("Cancel Import"));
226         current_interthread_info = &import_status;
227
228         import_status.paths = paths;
229         import_status.done = false;
230         import_status.cancel = false;
231         import_status.freeze = false;
232         import_status.done = 0.0;
233         
234         interthread_progress_connection = Glib::signal_timeout().connect 
235                 (bind (mem_fun(*this, &Editor::import_progress_timeout), (gpointer) 0), 100);
236         
237         track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
238         ARDOUR_UI::instance()->flush_pending ();
239
240         /* start import thread for this spec. this will ultimately call Session::import_audiofile()
241            and if successful will add the file(s) as a region to the session region list.
242         */
243         
244         pthread_create_and_store ("import", &import_status.thread, 0, _import_thread, this);
245         pthread_detach (import_status.thread);
246         
247         while (!(import_status.done || import_status.cancel)) {
248                 gtk_main_iteration ();
249         }
250
251         interthread_progress_window->hide ();
252         
253         import_status.done = true;
254         interthread_progress_connection.disconnect ();
255         
256         /* import thread finished - see if we should build a new track */
257
258         boost::shared_ptr<AudioTrack> track;
259         
260         if (!import_status.new_regions.empty()) {
261                 boost::shared_ptr<AudioRegion> region (import_status.new_regions.front());
262                 finish_bringing_in_audio (region, region->n_channels(), region->n_channels(), pos, mode, track, 0);
263         }
264
265         track_canvas.get_window()->set_cursor (*current_canvas_cursor);
266         return 0;
267 }
268
269 int
270 Editor::embed_sndfile (vector<Glib::ustring> paths, Editing::ImportChannel chns, bool multiple_files, bool& check_sample_rate, ImportMode mode, nframes64_t& pos)
271 {
272         boost::shared_ptr<AudioTrack> track;
273         boost::shared_ptr<AudioFileSource> source;
274         SourceList sources;
275         boost::shared_ptr<AudioRegion> region;
276         string linked_path;
277         SoundFileInfo finfo;
278         ustring region_name;
279         uint32_t input_chan = 0;
280         uint32_t output_chan = 0;
281         int ret = 0;
282
283         track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
284         ARDOUR_UI::instance()->flush_pending ();
285
286         for (vector<Glib::ustring>::iterator p = paths.begin(); p != paths.end(); ++p) {
287
288                 ustring path = *p;
289
290                 /* lets see if we can link it into the session */
291                 
292                 linked_path = session->sound_dir();
293                 linked_path += '/';
294                 linked_path += Glib::path_get_basename (path);
295                 
296                 if (link (path.c_str(), linked_path.c_str()) == 0) {
297
298                         /* there are many reasons why link(2) might have failed.
299                            but if it succeeds, we now have a link in the
300                            session sound dir that will protect against
301                            unlinking of the original path. nice.
302                         */
303                         
304                         path = linked_path;
305
306                 } else {
307
308                         /* one possible reason is that its already linked */
309
310                         if (errno == EEXIST) {
311                                 struct stat sb;
312
313                                 if (stat (linked_path.c_str(), &sb) == 0) {
314                                         if (sb.st_nlink > 1) { // its a hard link, assume its the one we want
315                                                 path = linked_path;
316                                         }
317                                 }
318                         }
319                 }
320                 
321                 /* note that we temporarily truncated _id at the colon */
322                 
323                 string error_msg;
324
325                 if (!AudioFileSource::get_soundfile_info (path, finfo, error_msg)) {
326                         error << string_compose(_("Editor: cannot open file \"%1\", (%2)"), path, error_msg ) << endmsg;
327                         goto out;
328                 }
329                 
330                 if (check_sample_rate  && (finfo.samplerate != (int) session->frame_rate())) {
331                         vector<string> choices;
332                         
333                         if (multiple_files) {
334                                 choices.push_back (_("Cancel entire import"));
335                                 choices.push_back (_("Don't embed it"));
336                                 choices.push_back (_("Embed all without questions"));
337                         
338                                 Gtkmm2ext::Choice rate_choice (
339                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), 
340                                                         short_path (path, 40)),
341                                         choices, false);
342                                 
343                                 int resx = rate_choice.run ();
344                                 
345                                 switch (resx) {
346                                 case 0: /* stop a multi-file import */
347                                         ret = -2;
348                                         goto out;
349                                 case 1: /* don't embed this one */
350                                         ret = -1;
351                                         goto out;
352                                 case 2: /* do it, and the rest without asking */
353                                         check_sample_rate = false;
354                                         break;
355                                 case 3: /* do it */
356                                         break;
357                                 default:
358                                         ret = -2;
359                                         goto out;
360                                 }
361                         } else {
362                                 choices.push_back (_("Cancel"));
363                                 choices.push_back (_("Embed it anyway"));
364                         
365                                 Gtkmm2ext::Choice rate_choice (
366                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), path),
367                                         choices, false);
368                                 
369                                 int resx = rate_choice.run ();
370                                 
371                                 switch (resx) {
372                                 case 0: /* don't import */
373                                         ret = -1;
374                                         goto out;
375                                 case 1: /* do it */
376                                         break;
377                                 default:
378                                         ret = -2;
379                                         goto out;
380                                 }
381                         }
382                 }
383                 
384                 track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
385                 // ARDOUR_UI::instance()->flush_pending ();
386         
387                 /* make the proper number of channels in the region */
388                 
389                 input_chan += finfo.channels;
390
391                 for (int n = 0; n < finfo.channels; ++n)
392                 {
393                         try {
394
395                                 /* check if we have this thing embedded already */
396
397                                 boost::shared_ptr<Source> s;
398
399                                 if ((s = session->source_by_path_and_channel (path, n)) == 0) {
400                                         source = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createReadable 
401                                                                                                (*session, path,  n,
402                                                                                                 (mode == ImportAsTapeTrack ? 
403                                                                                                  AudioFileSource::Destructive : 
404                                                                                                  AudioFileSource::Flag (0))));
405                                 } else {
406                                         source = boost::dynamic_pointer_cast<AudioFileSource> (s);
407                                 }
408
409                                 sources.push_back(source);
410                         } 
411                         
412                         catch (failed_constructor& err) {
413                                 error << string_compose(_("could not open %1"), path) << endmsg;
414                                 goto out;
415                         }
416                         
417                         ARDOUR_UI::instance()->flush_pending ();
418                 }
419         }
420
421         if (sources.empty()) {
422                 goto out;
423         }
424
425
426         if (pos == -1) { // "use timestamp"
427                 if (sources[0]->natural_position() != 0) {
428                         pos = sources[0]->natural_position();
429                 } else {
430                         // XXX is this the best alternative ?
431                         pos = edit_cursor->current_frame;
432                 }
433         }
434
435         if (chns == Editing::ImportMergeFiles) {
436
437                 /* take all the sources we have and package them up as a region */
438
439                 region_name = region_name_from_path (paths.front(), (sources.size() > 1));
440                 
441                 region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (sources, 0, sources[0]->length(), region_name, 0,
442                                                                                           Region::Flag (Region::DefaultFlags|Region::WholeFile|Region::External)));
443
444                 if (Config->get_output_auto_connect() & AutoConnectMaster) {
445                         output_chan = (session->master_out() ? session->master_out()->n_inputs() : input_chan);
446                 } else {
447                         output_chan = input_chan;
448                 }
449                 
450                 finish_bringing_in_audio (region, input_chan, output_chan, pos, mode, track, 0);
451                 
452         } else { // SerializeFiles, DistinctFiles, DistinctChannels
453
454                 /* take each source and create a region for each one */
455
456                 SourceList just_one;
457                 SourceList::iterator x;
458                 vector<Glib::ustring>::iterator p = paths.begin();
459                 vector<Glib::ustring>::iterator next_path;
460                 int nth;
461
462                 for (nth = 0, x = sources.begin(); x != sources.end(); ++x, ++nth) {
463
464                         just_one.clear ();
465                         just_one.push_back (*x);
466
467                         region_name = region_name_from_path ((*p), false);
468                         
469                         region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (just_one, 0, (*x)->length(), region_name, 0,
470                                                                                                   Region::Flag (Region::DefaultFlags|Region::WholeFile|Region::External)));
471
472                         if (Config->get_output_auto_connect() & AutoConnectMaster) {
473                                 output_chan = (session->master_out() ? session->master_out()->n_inputs() : input_chan);
474                         } else {
475                                 output_chan = input_chan;
476                         }
477                 
478                         finish_bringing_in_audio (region, 1, output_chan, pos, mode, track, nth);
479
480                         if (chns == ImportSerializeFiles) {
481                                 pos += region->length();
482                         }
483
484                         if (chns == ImportDistinctChannels || chns == ImportDistinctFiles) {
485                                 /* make a new track for the next region */
486                                 track.reset ();
487                         }
488
489                         /* don't run out of paths */
490                         
491                         next_path = p;
492                         next_path++;
493
494                         if (next_path != paths.end()) {
495                                 p = next_path;
496                         }
497                 }
498         }
499
500         
501   out:
502         track_canvas.get_window()->set_cursor (*current_canvas_cursor);
503         return ret;
504 }
505
506 int
507 Editor::finish_bringing_in_audio (boost::shared_ptr<AudioRegion> region, uint32_t in_chans, uint32_t out_chans, nframes64_t& pos, 
508                                   ImportMode mode, boost::shared_ptr<AudioTrack>& existing_track, int nth)
509 {
510         boost::shared_ptr<AudioTrack> track;
511
512         switch (mode) {
513         case ImportAsRegion:
514                 /* relax, its been done */
515                 break;
516                 
517         case ImportToTrack:
518         {
519                 if (selection->tracks.empty()) {
520                         return -1;
521                 }
522
523                 AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*>(selection->tracks.front());
524
525                 if (!atv) {
526                         return -1;
527                 }
528
529                 track = atv->audio_track();
530                 
531                 boost::shared_ptr<Playlist> playlist = track->diskstream()->playlist();
532                 boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
533                 begin_reversible_command (_("insert sndfile"));
534                 XMLNode &before = playlist->get_state();
535                 playlist->add_region (copy, pos);
536                 session->add_command (new MementoCommand<Playlist>(*playlist, &before, &playlist->get_state()));
537                 commit_reversible_command ();
538                 break;
539         }
540
541         case ImportAsTrack:
542         { 
543                 if (!existing_track) {
544                         list<boost::shared_ptr<AudioTrack> > at (session->new_audio_track (in_chans, out_chans, Normal, 1));
545                         if (at.empty()) {
546                                 return -1;
547                         }
548                         existing_track = at.front();
549                         existing_track->set_name (basename_nosuffix (region->name()), this);
550                 }
551                 boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
552                 existing_track->diskstream()->playlist()->add_region (copy, pos);
553                 break;
554         }
555
556
557         case ImportAsTapeTrack:
558         {
559                 list<boost::shared_ptr<AudioTrack> > at (session->new_audio_track (in_chans, out_chans, Destructive));
560                 if (!at.empty()) {
561                         boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
562                         at.front()->set_name (basename_nosuffix (copy->name()), this);
563                         at.front()->diskstream()->playlist()->add_region (copy, pos);
564                 }
565                 break;
566         }
567         }
568
569         return 0;
570 }
571
572 void *
573 Editor::_import_thread (void *arg)
574 {
575         PBD::ThreadCreated (pthread_self(), X_("Import"));
576
577         Editor *ed = (Editor *) arg;
578         return ed->import_thread ();
579 }
580
581 void *
582 Editor::import_thread ()
583 {
584         session->import_audiofile (import_status);
585         pthread_exit_pbd (0);
586         /*NOTREACHED*/
587         return 0;
588 }
589
590 gint
591 Editor::import_progress_timeout (void *arg)
592 {
593         interthread_progress_label.set_text (import_status.doing_what);
594
595         if (import_status.freeze) {
596                 interthread_cancel_button.set_sensitive(false);
597         } else {
598                 interthread_cancel_button.set_sensitive(true);
599         }
600
601         if (import_status.doing_what == "building peak files") {
602                 interthread_progress_bar.pulse ();
603                 return FALSE;
604         } else {
605                 interthread_progress_bar.set_fraction (import_status.progress);
606         }
607
608         return !(import_status.done || import_status.cancel);
609 }
610