a-fluidsynth: implement LV2_BANKPATCH__notify
[ardour.git] / gtk2_ardour / editor_pt_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 #include <algorithm>
26
27 #include "pbd/pthread_utils.h"
28 #include "pbd/basename.h"
29 #include "pbd/shortpath.h"
30 #include "pbd/stateful_diff_command.h"
31
32 #include "ardour/audio_track.h"
33 #include "ardour/audiofilesource.h"
34 #include "ardour/audioregion.h"
35 #include "ardour/midi_region.h"
36 #include "ardour/midi_track.h"
37 #include "ardour/midi_model.h"
38 #include "ardour/operations.h"
39 #include "ardour/region_factory.h"
40 #include "ardour/smf_source.h"
41 #include "ardour/source_factory.h"
42 #include "ardour/utils.h"
43 #include "ardour/playlist.h"
44 #include "ardour/session.h"
45 #include "pbd/memento_command.h"
46
47 #include "ptformat/ptfformat.h"
48
49 #include "ardour_ui.h"
50 #include "cursor_context.h"
51 #include "editor.h"
52 #include "sfdb_ui.h"
53 #include "editing.h"
54 #include "audio_time_axis.h"
55 #include "midi_time_axis.h"
56 #include "session_import_dialog.h"
57 #include "gui_thread.h"
58 #include "interthread_progress_window.h"
59 #include "mouse_cursors.h"
60 #include "editor_cursors.h"
61
62 #include "pbd/i18n.h"
63
64 using namespace std;
65 using namespace ARDOUR;
66 using namespace PBD;
67 using namespace Gtk;
68 using namespace Gtkmm2ext;
69 using namespace Editing;
70 using std::string;
71
72 /* Functions supporting the incorporation of PT sessions into ardour */
73
74 void
75 Editor::external_pt_dialog ()
76 {
77         std::string ptpath;
78
79         if (_session == 0) {
80                 MessageDialog msg (_("You can't import a PT session until you have a session loaded."));
81                 msg.run ();
82                 return;
83         }
84
85         Gtk::FileChooserDialog dialog(_("Import PT Session"), FILE_CHOOSER_ACTION_OPEN);
86         dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
87         dialog.add_button(Gtk::Stock::OK, Gtk::RESPONSE_OK);
88
89         while (true) {
90                 int result = dialog.run();
91
92                 if (result == Gtk::RESPONSE_OK) {
93                         ptpath = dialog.get_filename ();
94
95                         if (!Glib::file_test (ptpath, Glib::FILE_TEST_IS_DIR|Glib::FILE_TEST_EXISTS)) {
96                                 Gtk::MessageDialog msg (string_compose (_("%1: this is only the directory/folder name, not the filename.\n"), ptpath));
97                                 msg.run ();
98                                 continue;
99                         }
100                 }
101
102                 if (ptpath.length()) {
103                         do_ptimport(ptpath, SrcBest);
104                         break;
105                 }
106
107                 if (result == Gtk::RESPONSE_CANCEL) {
108                         break;
109                 }
110         }
111 }
112
113 void
114 Editor::do_ptimport (std::string ptpath,
115                       SrcQuality  quality)
116 {
117         vector<boost::shared_ptr<Region> > regions;
118         boost::shared_ptr<ARDOUR::Track> track;
119         ARDOUR::PluginInfoPtr instrument;
120         vector<string> to_import;
121         string fullpath;
122         bool ok = false;
123         bool onefailed = false;
124         PTFFormat ptf;
125         framepos_t pos = -1;
126
127         vector<ptflookup_t> ptfwavpair;
128         vector<ptflookup_t> ptfregpair;
129
130         if (ptf.load(ptpath, _session->frame_rate()) == -1) {
131                 MessageDialog msg (_("Doesn't seem to be a valid PT session file"));
132                 msg.run ();
133                 return;
134         } else {
135                 MessageDialog msg (string_compose (_("PT v%1 Session @ %2Hz\n\n%3 audio files\n%4 regions\n%5 active regions\n\nContinue..."), (int)ptf.version, ptf.sessionrate, ptf.audiofiles.size(), ptf.regions.size(), ptf.tracks.size()));
136                 msg.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
137
138                 int result = msg.run ();
139                 if (result != Gtk::RESPONSE_OK) {
140                         return;
141                 }
142         }
143         current_interthread_info = &import_status;
144         import_status.current = 1;
145         import_status.total = ptf.audiofiles.size ();
146         import_status.all_done = false;
147
148         ImportProgressWindow ipw (&import_status, _("Import"), _("Cancel Import"));
149
150         SourceList just_one;
151         SourceList imported;
152
153         for (vector<PTFFormat::wav_t>::iterator a = ptf.audiofiles.begin(); a != ptf.audiofiles.end(); ++a) {
154                 ptflookup_t p;
155
156                 fullpath = Glib::build_filename (Glib::path_get_dirname(ptpath), "Audio Files");
157                 fullpath = Glib::build_filename (fullpath, a->filename);
158                 to_import.clear ();
159                 to_import.push_back (fullpath);
160                 ipw.show ();
161                 ok = import_sndfiles (to_import, Editing::ImportDistinctFiles, Editing::ImportAsRegion, quality, pos, 1, -1, track, false, instrument);
162                 if (!import_status.sources.empty()) {
163                         p.index1 = a->index;
164                         p.id = import_status.sources.back()->id();
165
166                         ptfwavpair.push_back(p);
167                         imported.push_back(import_status.sources.back());
168                 } else {
169                         onefailed = true;
170                 }
171         }
172
173         if (onefailed) {
174                 MessageDialog msg (_("Failed to load one or more of the audio files, but continuing to attempt import."));
175                 msg.run ();
176         } else {
177                 MessageDialog msg (_("Success! Import should complete soon."));
178                 msg.run ();
179         }
180
181         // Create a dummy midi track first to get a midi Source
182         list<boost::shared_ptr<MidiTrack> > mt (
183                 _session->new_midi_track (ChanCount (DataType::MIDI, 1),
184                                           ChanCount (DataType::MIDI, 1),
185                                           true,
186                                           instrument, (Plugin::PresetRecord*) 0,
187                                           (RouteGroup*) 0,
188                                           1,
189                                           string(),
190                                           PresentationInfo::max_order));
191         if (mt.empty()) {
192                 return;
193         }
194
195         for (vector<PTFFormat::region_t>::iterator a = ptf.regions.begin();
196                         a != ptf.regions.end(); ++a) {
197                 for (vector<ptflookup_t>::iterator p = ptfwavpair.begin();
198                                 p != ptfwavpair.end(); ++p) {
199                         if ((p->index1 == a->wave.index) && (strcmp(a->wave.filename.c_str(), "") != 0)) {
200                                 for (SourceList::iterator x = imported.begin();
201                                                 x != imported.end(); ++x) {
202                                         if ((*x)->id() == p->id) {
203                                                 // Matched an uncreated ptf region to ardour region
204                                                 ptflookup_t rp;
205                                                 PropertyList plist;
206
207                                                 plist.add (ARDOUR::Properties::start, a->sampleoffset);
208                                                 plist.add (ARDOUR::Properties::position, 0);
209                                                 plist.add (ARDOUR::Properties::length, a->length);
210                                                 plist.add (ARDOUR::Properties::name, a->name);
211                                                 plist.add (ARDOUR::Properties::layer, 0);
212                                                 plist.add (ARDOUR::Properties::whole_file, false);
213                                                 plist.add (ARDOUR::Properties::external, true);
214
215                                                 just_one.clear();
216                                                 just_one.push_back(*x);
217
218                                                 boost::shared_ptr<Region> r = RegionFactory::create (just_one, plist);
219                                                 regions.push_back(r);
220
221                                                 rp.id = regions.back()->id();
222                                                 rp.index1 = a->index;
223                                                 ptfregpair.push_back(rp);
224                                         }
225                                 }
226                         }
227                 }
228                 if (strcmp(a->wave.filename.c_str(), "") == 0) {
229                         /* Empty wave - assume MIDI region */
230                         boost::shared_ptr<MidiTrack> midi_track = mt.back();
231                         boost::shared_ptr<Playlist> playlist = midi_track->playlist();
232                         framepos_t f = (framepos_t)a->startpos;
233                         framecnt_t length = (framecnt_t)a->length;
234                         MusicFrame pos (f, 0);
235                         boost::shared_ptr<Source> src = _session->create_midi_source_by_stealing_name (midi_track);
236                         PropertyList plist;
237                         plist.add (ARDOUR::Properties::start, 0);
238                         plist.add (ARDOUR::Properties::length, length);
239                         plist.add (ARDOUR::Properties::name, PBD::basename_nosuffix(src->name()));
240                         boost::shared_ptr<Region> region = (RegionFactory::create (src, plist));
241                         /* sets beat position */
242                         region->set_position (pos.frame, pos.division);
243                         midi_track->playlist()->add_region (region, pos.frame, 1.0, false, pos.division);
244
245                         boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(region);
246                         boost::shared_ptr<MidiModel> mm = mr->midi_source(0)->model();
247                         MidiModel::NoteDiffCommand *midicmd;
248                         midicmd = mm->new_note_diff_command ("Import ProTools MIDI");
249
250                         for (vector<PTFFormat::midi_ev_t>::iterator
251                                         j = a->midi.begin();
252                                         j != a->midi.end(); ++j) {
253                                 Evoral::Beats start = (Evoral::Beats)(j->pos/960000.);
254                                 Evoral::Beats len = (Evoral::Beats)(j->length/960000.);
255                                 // PT C-2 = 0, Ardour C-1 = 0, subtract twelve to convert...
256                                 midicmd->add(boost::shared_ptr<Evoral::Note<Evoral::Beats> >
257                                         (new Evoral::Note<Evoral::Beats>( (uint8_t)1, start, len, j->note - 12, j->velocity )));
258                         }
259                         mm->apply_command (_session, midicmd);
260                         boost::shared_ptr<Region> copy (RegionFactory::create (mr, true));
261                         playlist->clear_changes ();
262                         playlist->add_region (copy, a->startpos);
263                 }
264         }
265
266         boost::shared_ptr<AudioTrack> existing_track;
267         uint16_t nth = 0;
268         vector<ptflookup_t> usedtracks;
269         ptflookup_t utr;
270
271         for (vector<PTFFormat::track_t>::iterator a = ptf.tracks.begin();
272                         a != ptf.tracks.end(); ++a) {
273                 for (vector<ptflookup_t>::iterator p = ptfregpair.begin();
274                                 p != ptfregpair.end(); ++p) {
275
276                         if (p->index1 == a->reg.index)  {
277                                 // Matched a ptf active region to an ardour region
278                                 utr.index1 = a->index;
279                                 utr.index2 = nth;
280                                 utr.id = p->id;
281                                 boost::shared_ptr<Region> r = RegionFactory::region_by_id (p->id);
282                                 vector<ptflookup_t>::iterator lookuptr = usedtracks.begin();
283                                 vector<ptflookup_t>::iterator found;
284                                 if ((found = std::find(lookuptr, usedtracks.end(), utr)) != usedtracks.end()) {
285                                         DEBUG_TRACE (DEBUG::FileUtils, string_compose ("\twav(%1) reg(%2) ptf_tr(%3) ard_tr(%4)\n", a->reg.wave.filename.c_str(), a->reg.index, found->index1, found->index2));
286                                         existing_track =  get_nth_selected_audio_track(found->index2);
287                                         // Put on existing track
288                                         boost::shared_ptr<Playlist> playlist = existing_track->playlist();
289                                         boost::shared_ptr<Region> copy (RegionFactory::create (r, true));
290                                         playlist->clear_changes ();
291                                         playlist->add_region (copy, a->reg.startpos);
292                                         //_session->add_command (new StatefulDiffCommand (playlist));
293                                 } else {
294                                         // Put on a new track
295                                         DEBUG_TRACE (DEBUG::FileUtils, string_compose ("\twav(%1) reg(%2) new_tr(%3)\n", a->reg.wave.filename.c_str(), a->reg.index, nth));
296                                         list<boost::shared_ptr<AudioTrack> > at (_session->new_audio_track (1, 2, 0, 1, string(), PresentationInfo::max_order, Normal));
297                                         if (at.empty()) {
298                                                 return;
299                                         }
300                                         existing_track = at.back();
301                                         std::string trackname;
302                                         try {
303                                                 trackname = Glib::convert_with_fallback (a->name, "UTF-8", "UTF-8", "_");
304                                         } catch (Glib::ConvertError& err) {
305                                                 trackname = string_compose ("Invalid %1", a->index);
306                                         }
307                                         // TODO legalize track name (no slashes, no colons)
308 #if 0 // TODO --  "find_route_name" is currently private
309                                         /* generate a unique name by adding a number if needed */
310                                         uint32_t id = 0;
311                                         if (!_session->find_route_name (trackname.c_str (), id, trackname, false)) {
312                                                 fatal << _("PTImport: UINT_MAX routes? impossible!") << endmsg;
313                                                 abort(); /*NOTREACHED*/
314                                         }
315 #endif
316                                         existing_track->set_name (trackname);
317                                         boost::shared_ptr<Playlist> playlist = existing_track->playlist();
318                                         boost::shared_ptr<Region> copy (RegionFactory::create (r, true));
319                                         playlist->clear_changes ();
320                                         playlist->add_region (copy, a->reg.startpos);
321                                         //_session->add_command (new StatefulDiffCommand (playlist));
322                                         nth++;
323                                 }
324                                 usedtracks.push_back(utr);
325                         }
326                 }
327         }
328
329         import_status.sources.clear();
330
331         if (ok) {
332                 _session->save_state ("");
333         }
334         import_status.all_done = true;
335 }