Remove another C++11 construct (local struct) from UI code
[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 struct midipair {
114         midipair (uint16_t idx, string n)
115                 : ptfindex (idx)
116                   , trname (n)
117         {}
118         uint16_t ptfindex;
119         string trname;
120 };
121
122 void
123 Editor::do_ptimport (std::string ptpath,
124                       SrcQuality  quality)
125 {
126         vector<boost::shared_ptr<Region> > regions;
127         boost::shared_ptr<ARDOUR::Track> track;
128         ARDOUR::PluginInfoPtr instrument;
129         vector<string> to_import;
130         string fullpath;
131         bool ok = false;
132         bool onefailed = false;
133         PTFFormat ptf;
134         samplepos_t pos = -1;
135         uint32_t srate = _session->sample_rate ();
136
137         vector<ptflookup_t> ptfwavpair;
138         vector<ptflookup_t> ptfregpair;
139
140         if (ptf.load (ptpath, srate) == -1) {
141                 MessageDialog msg (_("Doesn't seem to be a valid PT session file"));
142                 msg.run ();
143                 return;
144         } else {
145                 MessageDialog msg (string_compose (_("PT v%1 Session @ %2Hz\n\n%3 audio files\n%4 audio regions\n%5 active audio regions\n%6 midi regions\n%7 active midi regions\n\nContinue..."), (int)ptf.version, ptf.sessionrate, ptf.audiofiles.size (), ptf.regions.size () - ptf.midiregions.size (), ptf.tracks.size (), ptf.midiregions.size (), ptf.miditracks.size ()));
146                 msg.add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
147
148                 int result = msg.run ();
149                 if (result != Gtk::RESPONSE_OK) {
150                         return;
151                 }
152         }
153         current_interthread_info = &import_status;
154         import_status.current = 1;
155         import_status.total = ptf.audiofiles.size ();
156         import_status.all_done = false;
157
158         ImportProgressWindow ipw (&import_status, _("Import"), _("Cancel Import"));
159
160         SourceList just_one;
161         SourceList imported;
162
163         for (vector<PTFFormat::wav_t>::iterator a = ptf.audiofiles.begin (); a != ptf.audiofiles.end (); ++a) {
164                 ptflookup_t p;
165
166                 fullpath = Glib::build_filename (Glib::path_get_dirname (ptpath), "Audio Files");
167                 fullpath = Glib::build_filename (fullpath, a->filename);
168                 to_import.clear ();
169                 to_import.push_back (fullpath);
170                 ipw.show ();
171                 ok = import_sndfiles (to_import, Editing::ImportDistinctFiles, Editing::ImportAsRegion, quality, pos, 1, -1, track, false, instrument);
172                 if (!import_status.sources.empty ()) {
173                         p.index1 = a->index;
174                         p.id = import_status.sources.back ()->id ();
175
176                         ptfwavpair.push_back (p);
177                         imported.push_back (import_status.sources.back ());
178                 } else {
179                         onefailed = true;
180                 }
181         }
182
183         if (onefailed) {
184                 MessageDialog msg (_("Failed to load one or more of the audio files, but continuing to attempt import."));
185                 msg.run ();
186         } else {
187                 MessageDialog msg (_("Success! Import should complete soon."));
188                 msg.run ();
189         }
190
191         for (vector<PTFFormat::region_t>::iterator a = ptf.regions.begin ();
192                         a != ptf.regions.end (); ++a) {
193                 for (vector<ptflookup_t>::iterator p = ptfwavpair.begin ();
194                                 p != ptfwavpair.end (); ++p) {
195                         if ((p->index1 == a->wave.index) && (strcmp (a->wave.filename.c_str (), "") != 0)) {
196                                 for (SourceList::iterator x = imported.begin (); x != imported.end (); ++x) {
197                                         if ((*x)->id () == p->id) {
198                                                 /* Matched an uncreated ptf region to ardour region */
199                                                 ptflookup_t rp;
200                                                 PropertyList plist;
201
202                                                 plist.add (ARDOUR::Properties::start, a->sampleoffset);
203                                                 plist.add (ARDOUR::Properties::position, 0);
204                                                 plist.add (ARDOUR::Properties::length, a->length);
205                                                 plist.add (ARDOUR::Properties::name, a->name);
206                                                 plist.add (ARDOUR::Properties::layer, 0);
207                                                 plist.add (ARDOUR::Properties::whole_file, false);
208                                                 plist.add (ARDOUR::Properties::external, true);
209
210                                                 just_one.clear ();
211                                                 just_one.push_back (*x);
212
213                                                 boost::shared_ptr<Region> r = RegionFactory::create (just_one, plist);
214                                                 regions.push_back (r);
215
216                                                 rp.id = regions.back ()->id ();
217                                                 rp.index1 = a->index;
218                                                 ptfregpair.push_back (rp);
219                                         }
220                                 }
221                         }
222                 }
223         }
224
225         boost::shared_ptr<AudioTrack> existing_track;
226         uint16_t nth = 0;
227         vector<ptflookup_t> usedtracks;
228         ptflookup_t utr;
229
230         for (vector<PTFFormat::track_t>::iterator a = ptf.tracks.begin (); a != ptf.tracks.end (); ++a) {
231                 for (vector<ptflookup_t>::iterator p = ptfregpair.begin ();
232                                 p != ptfregpair.end (); ++p) {
233
234                         if (p->index1 == a->reg.index)  {
235                                 /* Matched a ptf active region to an ardour region */
236                                 utr.index1 = a->index;
237                                 utr.index2 = nth;
238                                 utr.id = p->id;
239                                 boost::shared_ptr<Region> r = RegionFactory::region_by_id (p->id);
240                                 vector<ptflookup_t>::iterator lookuptr = usedtracks.begin ();
241                                 vector<ptflookup_t>::iterator found;
242                                 if ((found = std::find (lookuptr, usedtracks.end (), utr)) != usedtracks.end ()) {
243                                         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));
244                                         existing_track = get_nth_selected_audio_track (found->index2); // FIXME, don't rely on selection
245                                         /* Put on existing track */
246                                         boost::shared_ptr<Playlist> playlist = existing_track->playlist ();
247                                         boost::shared_ptr<Region> copy (RegionFactory::create (r, true));
248                                         playlist->clear_changes ();
249                                         playlist->add_region (copy, a->reg.startpos);
250                                         //_session->add_command (new StatefulDiffCommand (playlist));
251                                 } else {
252                                         /* Put on a new track */
253                                         DEBUG_TRACE (DEBUG::FileUtils, string_compose ("\twav(%1) reg(%2) new_tr(%3)\n", a->reg.wave.filename.c_str (), a->reg.index, nth));
254                                         list<boost::shared_ptr<AudioTrack> > at (_session->new_audio_track (1, 2, 0, 1, "", PresentationInfo::max_order, Normal));
255                                         if (at.empty ()) {
256                                                 return;
257                                         }
258                                         existing_track = at.back ();
259                                         std::string trackname;
260                                         try {
261                                                 trackname = Glib::convert_with_fallback (a->name, "UTF-8", "UTF-8", "_");
262                                         } catch (Glib::ConvertError& err) {
263                                                 trackname = string_compose ("Invalid %1", a->index);
264                                         }
265                                         /* TODO legalize track name (no slashes, no colons) */
266 #if 0 /* TODO --  "find_route_name" is currently private */
267                                         /* generate a unique name by adding a number if needed */
268                                         uint32_t id = 0;
269                                         if (!_session->find_route_name (trackname.c_str (), id, trackname, false)) {
270                                                 fatal << _("PTImport: UINT_MAX routes? impossible!") << endmsg;
271                                                 abort(); /*NOTREACHED*/
272                                         }
273 #endif
274                                         existing_track->set_name (trackname);
275                                         boost::shared_ptr<Playlist> playlist = existing_track->playlist();
276                                         boost::shared_ptr<Region> copy (RegionFactory::create (r, true));
277                                         playlist->clear_changes ();
278                                         playlist->add_region (copy, a->reg.startpos);
279                                         //_session->add_command (new StatefulDiffCommand (playlist));
280                                         nth++;
281                                 }
282                                 usedtracks.push_back (utr);
283                         }
284                 }
285         }
286
287         /* MIDI - Find list of unique midi tracks first */
288
289         vector<midipair> uniquetr;
290         uint16_t ith = 0;
291
292         for (vector<PTFFormat::track_t>::iterator a = ptf.miditracks.begin (); a != ptf.miditracks.end (); ++a) {
293                 bool found = false;
294                 for (vector<midipair>::iterator b = uniquetr.begin (); b != uniquetr.end (); ++b) {
295                         if (b->trname == a->name) {
296                                 found = true;
297                                 break;
298                         }
299                 }
300                 if (!found) {
301                         uniquetr.push_back (midipair (ith, a->name));
302                         //printf(" : %d : %s\n", ith, a->name.c_str());
303                         ith++;
304                 }
305         }
306
307         vector<boost::shared_ptr<MidiTrack> > midi_tracks;
308         /* MIDI - Create unique midi tracks and a lookup table for used tracks */
309         for (vector<midipair>::iterator a = uniquetr.begin (); a != uniquetr.end (); ++a) {
310                 ptflookup_t miditr;
311                 list<boost::shared_ptr<MidiTrack> > mt (_session->new_midi_track (
312                                 ChanCount (DataType::MIDI, 1),
313                                 ChanCount (DataType::MIDI, 1),
314                                 true,
315                                 instrument, (Plugin::PresetRecord*) 0,
316                                 (RouteGroup*) 0,
317                                 1,
318                                 a->trname,
319                                 PresentationInfo::max_order,
320                                 Normal));
321                 assert (mt.size () == 1);
322                 midi_tracks.push_back (mt.front ());
323         }
324
325         /* MIDI - Add midi regions one-by-one to corresponding midi tracks */
326         for (vector<PTFFormat::track_t>::iterator a = ptf.miditracks.begin (); a != ptf.miditracks.end (); ++a) {
327
328                 boost::shared_ptr<MidiTrack> midi_track = midi_tracks.at (a->index);
329                 assert (midi_track);
330                 boost::shared_ptr<Playlist> playlist = midi_track->playlist ();
331                 samplepos_t f = (samplepos_t)a->reg.startpos * srate / 1920000.;
332                 samplecnt_t length = (samplecnt_t)a->reg.length * srate / 1920000.;
333                 MusicSample pos (f, 0);
334                 boost::shared_ptr<Source> src = _session->create_midi_source_by_stealing_name (midi_track);
335                 PropertyList plist;
336                 plist.add (ARDOUR::Properties::start, 0);
337                 plist.add (ARDOUR::Properties::length, length);
338                 plist.add (ARDOUR::Properties::name, PBD::basename_nosuffix (src->name ()));
339                 //printf(" : %d - trackname: (%s)\n", a->index, src->name ().c_str ());
340                 boost::shared_ptr<Region> region = (RegionFactory::create (src, plist));
341                 /* sets beat position */
342                 region->set_position (pos.sample, pos.division);
343                 midi_track->playlist ()->add_region (region, pos.sample, 1.0, false, pos.division);
344
345                 boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(region);
346                 boost::shared_ptr<MidiModel> mm = mr->midi_source (0)->model ();
347                 MidiModel::NoteDiffCommand *midicmd;
348                 midicmd = mm->new_note_diff_command ("Import ProTools MIDI");
349
350                 for (vector<PTFFormat::midi_ev_t>::iterator j = a->reg.midi.begin (); j != a->reg.midi.end (); ++j) {
351                         //printf(" : MIDI : pos=%f len=%f\n", (float)j->pos / 960000., (float)j->length / 960000.);
352                         Temporal::Beats start = (Temporal::Beats)(j->pos / 960000.);
353                         Temporal::Beats len = (Temporal::Beats)(j->length / 960000.);
354                         /* PT C-2 = 0, Ardour C-1 = 0, subtract twelve to convert ? */
355                         midicmd->add (boost::shared_ptr<Evoral::Note<Temporal::Beats> > (new Evoral::Note<Temporal::Beats> ((uint8_t)1, start, len, j->note, j->velocity)));
356                 }
357                 mm->apply_command (_session, midicmd);
358                 boost::shared_ptr<Region> copy (RegionFactory::create (mr, true));
359                 playlist->clear_changes ();
360                 playlist->add_region (copy, f);
361         }
362
363         import_status.sources.clear ();
364
365         if (ok) {
366                 _session->save_state ("");
367         }
368         import_status.all_done = true;
369 }