Channel-aware note recording in MidiModel (i.e. multi-channel note input doesn't...
[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 <sys/time.h>
23 #include <errno.h>
24 #include <unistd.h>
25
26 #include <sndfile.h>
27
28 #include <pbd/pthread_utils.h>
29 #include <pbd/basename.h>
30 #include <pbd/shortpath.h>
31
32 #include <gtkmm2ext/choice.h>
33 #include <gtkmm2ext/window_title.h>
34
35 #include <ardour/session.h>
36 #include <ardour/session_directory.h>
37 #include <ardour/audioplaylist.h>
38 #include <ardour/audioregion.h>
39 #include <ardour/audio_diskstream.h>
40 #include <ardour/midi_track.h>
41 #include <ardour/midi_region.h>
42 #include <ardour/utils.h>
43 #include <ardour/audio_track.h>
44 #include <ardour/audioplaylist.h>
45 #include <ardour/audiofilesource.h>
46 #include <ardour/region_factory.h>
47 #include <ardour/source_factory.h>
48 #include <ardour/session.h>
49 #include <pbd/memento_command.h>
50
51 #include "ardour_ui.h"
52 #include "editor.h"
53 #include "sfdb_ui.h"
54 #include "editing.h"
55 #include "audio_time_axis.h"
56 #include "midi_time_axis.h"
57 #include "utils.h"
58
59 #include "i18n.h"
60
61 using namespace std;
62 using namespace ARDOUR;
63 using namespace PBD;
64 using namespace sigc;
65 using namespace Gtk;
66 using namespace Gtkmm2ext;
67 using namespace Editing;
68 using Glib::ustring;
69
70 /* Functions supporting the incorporation of external (non-captured) audio material into ardour */
71
72 void
73 Editor::add_external_audio_action (ImportMode mode_hint)
74 {
75         if (session == 0) {
76                 MessageDialog msg (0, _("You can't import or embed a file until you have a session loaded."));
77                 msg.run ();
78                 return;
79         }
80         
81         if (sfbrowser == 0) {
82                 sfbrowser = new SoundFileOmega (*this, _("Add existing media"), session, 0, true, mode_hint);
83         } else {
84                 sfbrowser->set_mode (mode_hint);
85         }
86
87         external_audio_dialog ();
88 }
89
90 void
91 Editor::external_audio_dialog ()
92 {
93         vector<Glib::ustring> paths;
94         uint32_t track_cnt;
95
96         if (session == 0) {
97                 MessageDialog msg (0, _("You can't import or embed a file until you have a session loaded."));
98                 msg.run ();
99                 return;
100         }
101         
102         track_cnt = 0;
103
104         for (TrackSelection::iterator x = selection->tracks.begin(); x != selection->tracks.end(); ++x) {
105                 AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*>(*x);
106                 
107                 if (!atv) {
108                         continue;
109                 } else if (atv->is_audio_track()) {
110                         track_cnt++;
111                 }
112         }
113
114         if (sfbrowser == 0) {
115                 sfbrowser = new SoundFileOmega (*this, _("Add existing media"), session, track_cnt, true);
116         } else {
117                 sfbrowser->reset (track_cnt);
118         }
119
120         sfbrowser->show_all ();
121
122
123         bool keepRunning;
124
125         do {
126                 keepRunning = false;
127
128                 int response = sfbrowser->run ();
129
130                 switch (response) {
131                         case RESPONSE_APPLY:
132                                 // leave the dialog open
133                                 break;
134
135                         case RESPONSE_OK:
136                                 sfbrowser->hide ();
137                                 break;
138
139                         default:
140                                 // cancel from the browser - we are done
141                                 sfbrowser->hide ();
142                                 return;
143                 }
144
145                 /* lets do it */
146
147                 paths = sfbrowser->get_paths ();
148
149                 ImportPosition pos = sfbrowser->get_position ();
150                 ImportMode mode = sfbrowser->get_mode ();
151                 ImportDisposition chns = sfbrowser->get_channel_disposition ();
152                 nframes64_t where;
153
154                 switch (pos) {
155                         case ImportAtEditPoint:
156                                 where = get_preferred_edit_position ();
157                                 break;
158                         case ImportAtTimestamp:
159                                 where = -1;
160                                 break;
161                         case ImportAtPlayhead:
162                                 where = playhead_cursor->current_frame;
163                                 break;
164                         case ImportAtStart:
165                                 where = session->current_start_frame();
166                                 break;
167                 }
168
169                 SrcQuality quality = sfbrowser->get_src_quality();
170
171
172                 if (sfbrowser->copy_files_btn.get_active()) {
173                         do_import (paths, chns, mode, quality, where);
174                 } else {
175                         do_embed (paths, chns, mode, where);
176                 }
177
178                 if (response == RESPONSE_APPLY) {
179                         sfbrowser->clear_selection ();
180                         keepRunning = true;
181                 }
182
183         } while (keepRunning);
184 }
185
186 typedef std::map<PBD::ID,boost::shared_ptr<ARDOUR::Source> > SourceMap;
187
188 /**
189  * Updating is still disabled, see note in libs/ardour/import.cc Session::import_audiofiles()
190  *
191  * all_or_nothing:
192  *   true  = show "Update", "Import" and "Skip"
193  *   false = show "Import", and "Cancel"
194  *
195  * Returns:
196  *     0  To update an existing source of the same name
197  *     1  To import/embed the file normally (make sure the new name will be unique)
198  *     2  If the user wants to skip this file
199  **/
200 int
201 Editor::check_whether_and_how_to_import(string path, bool all_or_nothing)
202 {
203         string wave_name (Glib::path_get_basename(path));
204
205         SourceMap all_sources = session->get_sources();
206         bool wave_name_exists = false;
207
208         for (SourceMap::iterator i = all_sources.begin(); i != all_sources.end(); ++i) {
209                 string tmp (Glib::path_get_basename (i->second->path()));
210
211                 if (tmp == wave_name) {
212                         wave_name_exists = true;
213                         break;
214                 }
215         }
216
217         int function = 1;
218
219
220         if (wave_name_exists) {
221                 string message;
222                 if (all_or_nothing) {
223                         // updating is still disabled
224                         //message = string_compose(_("The session already contains a source file named %1. Do you want to update that file (and thus all regions using the file) or import this file as a new file?"),wave_name);
225                         message = string_compose(_("The session already contains a source file named %1. This file will be imported as a new file, please confirm."),wave_name);
226                 } else {
227                         message = _("Lorem ipsum. Do you want to skidaddle?");
228
229                 }
230                 MessageDialog dialog(message, false,Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_NONE, true);
231
232                 if (all_or_nothing) {
233                         // disabled
234                         //dialog.add_button("Update", 0);
235                         dialog.add_button("Import", 1);
236                         dialog.add_button("Skip",   2);
237                 } else {
238                         dialog.add_button("Import", 1);
239                         dialog.add_button("Cancel", 2);
240                 }
241                 
242                 
243                 //dialog.add_button("Skip all", 4); // All or rest?
244
245                 dialog.show();
246
247                 function = dialog.run ();
248
249                 dialog.hide();
250         }
251
252         return function;
253 }
254
255 boost::shared_ptr<AudioTrack>
256 Editor::get_nth_selected_audio_track (int nth) const
257 {
258         AudioTimeAxisView* atv;
259         TrackSelection::iterator x;
260         
261         for (x = selection->tracks.begin(); nth > 0 && x != selection->tracks.end(); ++x) {
262
263                 atv = dynamic_cast<AudioTimeAxisView*>(*x);
264                 
265                 if (!atv) {
266                         continue;
267                 } else if (atv->is_audio_track()) {
268                         --nth;
269                 }
270         }
271         
272         if (x == selection->tracks.end()) {
273                 atv = dynamic_cast<AudioTimeAxisView*>(selection->tracks.back());
274         } else {
275                 atv = dynamic_cast<AudioTimeAxisView*>(*x);
276         }
277         
278         if (!atv || !atv->is_audio_track()) {
279                 return boost::shared_ptr<AudioTrack>();
280         }
281         
282         return atv->audio_track();
283 }       
284
285 boost::shared_ptr<MidiTrack>
286 Editor::get_nth_selected_midi_track (int nth) const
287 {
288         MidiTimeAxisView* mtv;
289         TrackSelection::iterator x;
290         
291         for (x = selection->tracks.begin(); nth > 0 && x != selection->tracks.end(); ++x) {
292
293                 mtv = dynamic_cast<MidiTimeAxisView*>(*x);
294                 
295                 if (!mtv) {
296                         continue;
297                 } else if (mtv->is_midi_track()) {
298                         --nth;
299                 }
300         }
301         
302         if (x == selection->tracks.end()) {
303                 mtv = dynamic_cast<MidiTimeAxisView*>(selection->tracks.back());
304         } else {
305                 mtv = dynamic_cast<MidiTimeAxisView*>(*x);
306         }
307         
308         if (!mtv || !mtv->is_midi_track()) {
309                 return boost::shared_ptr<MidiTrack>();
310         }
311         
312         return mtv->midi_track();
313 }       
314
315 void
316 Editor::do_import (vector<ustring> paths, ImportDisposition chns, ImportMode mode, SrcQuality quality, nframes64_t& pos)
317 {
318         boost::shared_ptr<Track> track;
319         vector<ustring> to_import;
320         bool ok = true;
321         int nth = 0;
322
323         if (interthread_progress_window == 0) {
324                 build_interthread_progress_window ();
325         }
326
327
328         if (chns == Editing::ImportMergeFiles) {
329                 /* create 1 region from all paths, add to 1 track,
330                    ignore "track"
331                 */
332                 bool cancel = false;
333                 for (vector<ustring>::iterator a = paths.begin(); a != paths.end() && ok; ++a) {
334                         int check = check_whether_and_how_to_import(*a, false);
335                         if (check == 2) {
336                                 cancel = true;
337                                 break;
338                         }
339                 }
340
341                 if (!cancel) {
342                         if (import_sndfiles (paths, mode, quality, pos, 1, 1, track, false)) {
343                                 ok = false;
344                         }
345                 }
346
347         } else {
348                 bool replace = false;
349
350                 for (vector<ustring>::iterator a = paths.begin(); a != paths.end() && ok; ++a) {
351
352                         int check = check_whether_and_how_to_import(*a, true);
353
354                         if (check == 2 ) { 
355                                 // skip
356                                 continue;
357                         }
358
359                         if (check == 0) {
360                                 fatal << "Updating existing sources should be disabled!" << endl;
361                                 replace = true;
362                         } else if (check == 1) {
363                                 replace = false;
364                         }
365                         
366
367                         switch (chns) {
368                                 case Editing::ImportDistinctFiles:
369
370                                         to_import.clear ();
371                                         to_import.push_back (*a);
372
373                                         if (mode == Editing::ImportToTrack) {
374                                                 track = get_nth_selected_audio_track (nth++);
375                                         }
376
377                                         if (import_sndfiles (to_import, mode, quality, pos, 1, -1, track, replace)) {
378                                                 ok = false;
379                                         }
380
381                                         break;
382
383                                 case Editing::ImportDistinctChannels:
384
385                                         to_import.clear ();
386                                         to_import.push_back (*a);
387
388                                         if (import_sndfiles (to_import, mode, quality, pos, -1, -1, track, replace)) {
389                                                 ok = false;
390                                         }
391
392                                         break;
393
394                                 case Editing::ImportSerializeFiles:
395
396                                         to_import.clear ();
397                                         to_import.push_back (*a);
398
399                                         /* create 1 region from this path, add to 1 track,
400                                            reuse "track" across paths
401                                            */
402
403                                         if (import_sndfiles (to_import, mode, quality, pos, 1, 1, track, replace)) {
404                                                 ok = false;
405                                         }
406
407                                         break;
408
409                                 case Editing::ImportMergeFiles:
410                                         // Not entered
411                                         break;
412                         }
413                 }
414
415                 if (ok) {
416                         session->save_state ("");
417                 }
418
419                 interthread_progress_window->hide_all ();
420         }
421 }
422
423 bool
424 Editor::idle_do_embed (vector<ustring> paths, ImportDisposition chns, ImportMode mode, nframes64_t& pos)
425 {
426         _do_embed (paths, chns, mode, pos);
427         return false;
428 }
429
430 void
431 Editor::do_embed (vector<ustring> paths, ImportDisposition chns, ImportMode mode, nframes64_t& pos)
432 {
433 #ifdef GTKOSX
434         Glib::signal_idle().connect (bind (mem_fun (*this, &Editor::idle_do_embed), paths, chns, mode, pos));
435 #else
436         _do_embed (paths, chns, mode, pos);
437 #endif
438 }
439
440 void
441 Editor::_do_embed (vector<ustring> paths, ImportDisposition chns, ImportMode mode, nframes64_t& pos)
442 {
443         boost::shared_ptr<Track> track;
444         bool check_sample_rate = true;
445         bool ok = false;
446         vector<ustring> to_embed;
447         bool multi = paths.size() > 1;
448         int nth = 0;
449
450         switch (chns) {
451         case Editing::ImportDistinctFiles:
452                 for (vector<ustring>::iterator a = paths.begin(); a != paths.end(); ++a) {
453
454                         to_embed.clear ();
455                         to_embed.push_back (*a);
456
457                         if (mode == Editing::ImportToTrack) {
458                                 track = get_nth_selected_audio_track (nth++);
459                         }
460
461                         if (embed_sndfiles (to_embed, multi, check_sample_rate, mode, pos, 1, -1, track) < -1) {
462                                 goto out;
463                         }
464                 }
465                 break;
466                 
467         case Editing::ImportDistinctChannels:
468                 for (vector<ustring>::iterator a = paths.begin(); a != paths.end(); ++a) {
469
470                         to_embed.clear ();
471                         to_embed.push_back (*a);
472
473                         if (embed_sndfiles (to_embed, multi, check_sample_rate, mode, pos, -1, -1, track) < -1) {
474                                 goto out;
475                         }
476                 }
477                 break;
478
479         case Editing::ImportMergeFiles:
480                 if (embed_sndfiles (paths, multi, check_sample_rate, mode, pos, 1, 1, track) < -1) {
481                         goto out;
482                 }
483         break;
484
485         case Editing::ImportSerializeFiles:
486                 for (vector<ustring>::iterator a = paths.begin(); a != paths.end(); ++a) {
487
488                         to_embed.clear ();
489                         to_embed.push_back (*a);
490
491                         if (embed_sndfiles (to_embed, multi, check_sample_rate, mode, pos, 1, 1, track) < -1) {
492                                 goto out;
493                         }
494                 }
495                 break;
496         }
497
498         ok = true;
499         
500   out:  
501         if (ok) {
502                 session->save_state ("");
503         }
504 }
505
506 int
507 Editor::import_sndfiles (vector<ustring> paths, ImportMode mode, SrcQuality quality, nframes64_t& pos, 
508                          int target_regions, int target_tracks, boost::shared_ptr<Track>& track, bool replace)
509 {
510         WindowTitle title = string_compose (_("importing %1"), paths.front());
511
512         interthread_progress_window->set_title (title.get_string());
513         interthread_progress_window->set_position (Gtk::WIN_POS_MOUSE);
514         interthread_progress_window->show_all ();
515         interthread_progress_bar.set_fraction (0.0f);
516         interthread_cancel_label.set_text (_("Cancel Import"));
517         current_interthread_info = &import_status;
518
519         import_status.paths = paths;
520         import_status.done = false;
521         import_status.cancel = false;
522         import_status.freeze = false;
523         import_status.done = 0.0;
524         import_status.quality = quality;
525         import_status.replace_existing_source = replace;
526
527         interthread_progress_connection = Glib::signal_timeout().connect 
528                 (bind (mem_fun(*this, &Editor::import_progress_timeout), (gpointer) 0), 100);
529         
530         track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
531         ARDOUR_UI::instance()->flush_pending ();
532
533         /* start import thread for this spec. this will ultimately call Session::import_audiofiles()
534            and if successful will add the file(s) as a region to the session region list.
535         */
536         
537         pthread_create_and_store ("import", &import_status.thread, 0, _import_thread, this);
538         pthread_detach (import_status.thread);
539         
540         while (!(import_status.done || import_status.cancel)) {
541                 gtk_main_iteration ();
542         }
543
544         interthread_progress_window->hide ();
545         
546         import_status.done = true;
547         interthread_progress_connection.disconnect ();
548         
549         /* import thread finished - see if we should build a new track */
550
551         boost::shared_ptr<AudioRegion> r;
552         
553         if (import_status.cancel || import_status.sources.empty()) {
554                 goto out;
555         }
556
557         if (add_sources (paths, import_status.sources, pos, mode, target_regions, target_tracks, track, false) == 0) {
558                 session->save_state ("");
559         }
560
561   out:
562         track_canvas.get_window()->set_cursor (*current_canvas_cursor);
563         return 0;
564 }
565
566 int
567 Editor::embed_sndfiles (vector<Glib::ustring> paths, bool multifile,
568                         bool& check_sample_rate, ImportMode mode, nframes64_t& pos, int target_regions, int target_tracks,
569                         boost::shared_ptr<Track>& track)
570 {
571         boost::shared_ptr<AudioFileSource> source;
572         SourceList sources;
573         string linked_path;
574         SoundFileInfo finfo;
575         int ret = 0;
576
577         track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
578         ARDOUR_UI::instance()->flush_pending ();
579
580         for (vector<Glib::ustring>::iterator p = paths.begin(); p != paths.end(); ++p) {
581
582                 ustring path = *p;
583
584                 /* lets see if we can link it into the session */
585                 
586                 sys::path tmp = session->session_directory().sound_path() / Glib::path_get_basename(path);
587                 linked_path = tmp.to_string();
588                 
589                 if (link (path.c_str(), linked_path.c_str()) == 0) {
590
591                         /* there are many reasons why link(2) might have failed.
592                            but if it succeeds, we now have a link in the
593                            session sound dir that will protect against
594                            unlinking of the original path. nice.
595                         */
596                         
597                         path = linked_path;
598
599                 } else {
600
601                         /* one possible reason is that its already linked */
602
603                         if (errno == EEXIST) {
604                                 struct stat sb;
605
606                                 if (stat (linked_path.c_str(), &sb) == 0) {
607                                         if (sb.st_nlink > 1) { // its a hard link, assume its the one we want
608                                                 path = linked_path;
609                                         }
610                                 }
611                         }
612                 }
613                 
614                 /* note that we temporarily truncated _id at the colon */
615                 
616                 string error_msg;
617
618                 if (!AudioFileSource::get_soundfile_info (path, finfo, error_msg)) {
619                         error << string_compose(_("Editor: cannot open file \"%1\", (%2)"), path, error_msg ) << endmsg;
620                         goto out;
621                 }
622                 
623                 if (check_sample_rate  && (finfo.samplerate != (int) session->frame_rate())) {
624                         vector<string> choices;
625                         
626                         if (multifile) {
627                                 choices.push_back (_("Cancel entire import"));
628                                 choices.push_back (_("Don't embed it"));
629                                 choices.push_back (_("Embed all without questions"));
630                         
631                                 Gtkmm2ext::Choice rate_choice (
632                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), 
633                                                         short_path (path, 40)),
634                                         choices, false);
635                                 
636                                 int resx = rate_choice.run ();
637                                 
638                                 switch (resx) {
639                                 case 0: /* stop a multi-file import */
640                                         ret = -2;
641                                         goto out;
642                                 case 1: /* don't embed this one */
643                                         ret = -1;
644                                         goto out;
645                                 case 2: /* do it, and the rest without asking */
646                                         check_sample_rate = false;
647                                         break;
648                                 case 3: /* do it */
649                                         break;
650                                 default:
651                                         ret = -2;
652                                         goto out;
653                                 }
654                         } else {
655                                 choices.push_back (_("Cancel"));
656                                 choices.push_back (_("Embed it anyway"));
657                         
658                                 Gtkmm2ext::Choice rate_choice (
659                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), path),
660                                         choices, false);
661                                 
662                                 int resx = rate_choice.run ();
663                                 
664                                 switch (resx) {
665                                 case 0: /* don't import */
666                                         ret = -1;
667                                         goto out;
668                                 case 1: /* do it */
669                                         break;
670                                 default:
671                                         ret = -2;
672                                         goto out;
673                                 }
674                         }
675                 }
676                 
677                 track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
678
679                 for (int n = 0; n < finfo.channels; ++n) {
680                         try {
681
682                                 /* check if we have this thing embedded already */
683
684                                 boost::shared_ptr<Source> s;
685
686                                 if ((s = session->source_by_path_and_channel (path, n)) == 0) {
687                                         source = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createReadable 
688                                                                                                (DataType::AUDIO, *session, path,  n,
689                                                                                                 (mode == ImportAsTapeTrack ? 
690                                                                                                  AudioFileSource::Destructive : 
691                                                                                                  AudioFileSource::Flag (0)),
692                                                                                                 true, true));
693                                 } else {
694                                         source = boost::dynamic_pointer_cast<AudioFileSource> (s);
695                                 }
696
697                                 sources.push_back(source);
698                         } 
699                         
700                         catch (failed_constructor& err) {
701                                 error << string_compose(_("could not open %1"), path) << endmsg;
702                                 goto out;
703                         }
704                         
705                         ARDOUR_UI::instance()->flush_pending ();
706                 }
707         }
708
709         if (sources.empty()) {
710                 goto out;
711         }
712
713         ret = add_sources (paths, sources, pos, mode, target_regions, target_tracks, track, true);
714
715   out:
716         track_canvas.get_window()->set_cursor (*current_canvas_cursor);
717         return ret;
718 }
719
720 int
721 Editor::add_sources (vector<Glib::ustring> paths, SourceList& sources, nframes64_t& pos, ImportMode mode, 
722                      int target_regions, int target_tracks, boost::shared_ptr<Track>& track, bool add_channel_suffix)
723 {
724         vector<boost::shared_ptr<Region> > regions;
725         ustring region_name;
726         uint32_t input_chan = 0;
727         uint32_t output_chan = 0;
728
729         if (pos == -1) { // "use timestamp"
730                 if (sources[0]->natural_position() != 0) {
731                         pos = sources[0]->natural_position();
732                 } else {
733                         pos = get_preferred_edit_position ();
734                 }
735         }
736
737         cout << "TARGET REGIONS: " << target_regions << endl;
738
739         if (target_regions == 1) {
740
741                 /* take all the sources we have and package them up as a region */
742
743                 region_name = region_name_from_path (paths.front(), (sources.size() > 1), false);
744                 
745                 regions.push_back (RegionFactory::create (sources, 0, sources[0]->length(), region_name, 0,
746                                                            Region::Flag (Region::DefaultFlags|Region::WholeFile|Region::External)));
747                 
748         } else if (target_regions == -1) {
749
750                 /* take each source and create a region for each one */
751
752                 SourceList just_one;
753                 SourceList::iterator x;
754                 uint32_t n;
755
756                 for (n = 0, x = sources.begin(); x != sources.end(); ++x, ++n) {
757
758                         just_one.clear ();
759                         just_one.push_back (*x);
760                         
761                         region_name = region_name_from_path ((*x)->path(), false, true, sources.size(), n);
762
763                         cout << "REGION NAME: " << region_name << endl;
764                         cout << "SOURCE LENGTH: " << (*x)->length() << endl;
765
766                         regions.push_back (RegionFactory::create (just_one, 0, (*x)->length(), region_name, 0,
767                                                                    Region::Flag (Region::DefaultFlags|Region::WholeFile|Region::External)));
768
769                 }
770         }
771
772         if (target_regions == 1) {
773                 input_chan = regions.front()->n_channels();
774         } else {
775                 if (target_tracks == 1) {
776                         input_chan = regions.size();
777                 } else {
778                         input_chan = 1;
779                 }
780         }
781
782         if (Config->get_output_auto_connect() & AutoConnectMaster) {
783                 output_chan = (session->master_out() ? session->master_out()->n_inputs().n_audio() : input_chan);
784         } else {
785                 output_chan = input_chan;
786         }
787
788         int n = 0;
789
790         for (vector<boost::shared_ptr<Region> >::iterator r = regions.begin(); r != regions.end(); ++r, ++n) {
791
792                 finish_bringing_in_material (*r, input_chan, output_chan, pos, mode, track);
793
794                 if (target_tracks != 1) {
795                         track.reset ();
796                 } else {
797                         pos += (*r)->length();
798                 } 
799         }
800
801         /* setup peak file building in another thread */
802
803         for (SourceList::iterator x = sources.begin(); x != sources.end(); ++x) {
804                 SourceFactory::setup_peakfile (*x, true);
805         }
806
807         return 0;
808 }
809         
810 int
811 Editor::finish_bringing_in_material (boost::shared_ptr<Region> region, uint32_t in_chans, uint32_t out_chans, nframes64_t& pos, 
812                                   ImportMode mode, boost::shared_ptr<Track>& existing_track)
813 {
814         boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion>(region);
815         boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(region);
816
817         switch (mode) {
818         case ImportAsRegion:
819                 /* relax, its been done */
820                 break;
821                 
822         case ImportToTrack:
823         {
824                 if (!existing_track) {
825
826                         if (ar) {
827                                 existing_track = get_nth_selected_audio_track (0);
828                         } else if (mr) {
829                                 existing_track = get_nth_selected_midi_track (0);
830                         }
831
832                         if (!existing_track) {
833                                 return -1;
834                         }
835                 }
836
837                 boost::shared_ptr<Playlist> playlist = existing_track->diskstream()->playlist();
838                 boost::shared_ptr<Region> copy (RegionFactory::create (region));
839                 begin_reversible_command (_("insert file"));
840                 XMLNode &before = playlist->get_state();
841                 playlist->add_region (copy, pos);
842                 session->add_command (new MementoCommand<Playlist>(*playlist, &before, &playlist->get_state()));
843                 commit_reversible_command ();
844                 break;
845         }
846
847         case ImportAsTrack:
848         { 
849                 if (!existing_track) {
850                         if (ar) {
851                                 list<boost::shared_ptr<AudioTrack> > at (session->new_audio_track (in_chans, out_chans, Normal, 1));
852
853                                 if (at.empty()) {
854                                         return -1;
855                                 }
856
857                                 existing_track = at.front();
858                         } else if (mr) {
859                                 list<boost::shared_ptr<MidiTrack> > mt (session->new_midi_track (Normal, 1));
860
861                                 if (mt.empty()) {
862                                         return -1;
863                                 }
864
865                                 existing_track = mt.front();
866                         }
867
868                         existing_track->set_name (region->name());
869                 }
870
871                 boost::shared_ptr<Region> copy (RegionFactory::create (region));
872                 existing_track->diskstream()->playlist()->add_region (copy, pos);
873                 break;
874         }
875
876
877         case ImportAsTapeTrack:
878         {
879                 if (!ar)
880                         return -1;
881
882                 list<boost::shared_ptr<AudioTrack> > at (session->new_audio_track (in_chans, out_chans, Destructive));
883                 if (!at.empty()) {
884                         boost::shared_ptr<Region> copy (RegionFactory::create (region));
885                         at.front()->set_name (basename_nosuffix (copy->name()));
886                         at.front()->diskstream()->playlist()->add_region (copy, pos);
887                 }
888                 break;
889         }
890         }
891
892         return 0;
893 }
894
895 void *
896 Editor::_import_thread (void *arg)
897 {
898         PBD::ThreadCreated (pthread_self(), X_("Import"));
899
900         Editor *ed = (Editor *) arg;
901         return ed->import_thread ();
902 }
903
904 void *
905 Editor::import_thread ()
906 {
907         session->import_audiofiles (import_status);
908         pthread_exit_pbd (0);
909         /*NOTREACHED*/
910         return 0;
911 }
912
913 gint
914 Editor::import_progress_timeout (void *arg)
915 {
916         interthread_progress_label.set_text (import_status.doing_what);
917
918         if (import_status.freeze) {
919                 interthread_cancel_button.set_sensitive(false);
920         } else {
921                 interthread_cancel_button.set_sensitive(true);
922         }
923
924         if (import_status.doing_what == "building peak files") {
925                 interthread_progress_bar.pulse ();
926                 return FALSE;
927         } else {
928                 interthread_progress_bar.set_fraction (import_status.progress);
929         }
930
931         return !(import_status.done || import_status.cancel);
932 }
933