summaryrefslogtreecommitdiff
path: root/muse/muse/importmidi.cpp
blob: 4fd5808db2a8a98376b3255cd710c4d9d1d4d52f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//=============================================================================
//  MusE
//  Linux Music Editor
//  $Id:$
//
//  Copyright (C) 2002-2006 by Werner Schweer and others
//
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License version 2.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//=============================================================================

#include "globals.h"
#include "muse.h"
#include "song.h"
#include "widgets/filedialog.h"
#include "midi.h"
#include "midifile.h"
#include "transport.h"
#include "midiedit/drummap.h"
#include "al/sig.h"
#include "al/tempo.h"
#include "instruments/minstrument.h"
#include "gconfig.h"
#include "driver/alsamidi.h"
#include "part.h"

//---------------------------------------------------------
//   importMidi
//---------------------------------------------------------

void MusE::importMidi()
      {
      QString empty("");
      importMidi(empty);
      }

void MusE::importMidi(const QString &file)
      {
      QString fn;
      QStringList pattern;

      const char** s = midi_file_pattern;
      while (*s)
            pattern << *s++;

      if (file.isEmpty()) {
            fn = getOpenFileName(lastMidiPath, pattern, this,
               tr("MusE: Import Midi"));
            if (fn.isEmpty())
                  return;
            lastMidiPath = fn;
            }
      else
            fn = file;

      int n = QMessageBox::question(this, appName,
         tr("Add midi file to current project?\n"),
         tr("&Add to Project"),
         tr("&Replace"),
         tr("&Abort"), 0, 2);

      switch (n) {
            case 0:
                  importMidi(fn, true);
                  song->update(-1);
                  break;
            case 1:
//TODO                  loadProjectFile(fn, false, false);    // replace
                  break;
            default:
                  return;
            }
      }

//---------------------------------------------------------
//   importMidi
//    return true on error
//---------------------------------------------------------

bool MusE::importMidi(const QString name, bool merge)
      {
      QFile* fp = fileOpen(this, name, QString(".mid"), QIODevice::ReadOnly);
      if (fp == 0)
            return true;
      MidiFile mf;
      bool rv = mf.read(fp);
      fp->close();
      delete fp;

      if (rv) {
            QString s(tr("reading midifile\n  "));
            s += name;
            s += tr("\nfailed: ");
            s += mf.error();
            QMessageBox::critical(this, QString("MusE"), s);
            return rv;
            }
      MidiFileTrackList* etl = mf.trackList();
      int division           = mf.division();

      MidiOutPort* outPort = 0;
      MidiInPort* inPort = 0;

      if (!merge || song->midiOutPorts()->empty()) {
            outPort = new MidiOutPort();
            outPort->setDefaultName();
            song->insertTrack0(outPort, -1);

            //
            // route output to preferred midi device
            //
            if (!config.defaultMidiOutputDevice.isEmpty()) {
                  Route dst(config.defaultMidiOutputDevice, 0, Route::MIDIPORT);
                  outPort->outRoutes()->push_back(dst);
                  }
            //
            // set preferred instrument
            //
            MidiInstrument* instr = 0;    // genericMidiInstrument;
            for (iMidiInstrument mi = midiInstruments.begin(); mi != midiInstruments.end(); ++mi) {
                  if ((*mi)->iname() == config.defaultMidiInstrument) {
                        instr = *mi;
                        break;
                        }
                  }

            if (config.createDefaultMidiInput) {
                  inPort = new MidiInPort();
                  inPort->setDefaultName();
                  song->insertTrack0(inPort, -1);
                  if (config.connectToAllMidiDevices) {
                        std::list<PortName>* ol = midiDriver->inputPorts();
                        for (std::list<PortName>::iterator ip = ol->begin(); ip != ol->end(); ++ip) {
                              Route src(ip->name, 0, Route::MIDIPORT);
                              inPort->inRoutes()->push_back(src);
                              }
                        }
                  else if (!config.defaultMidiInputDevice.isEmpty()) {
                        Route src(config.defaultMidiInputDevice, 0, Route::MIDIPORT);
                        inPort->inRoutes()->push_back(src);
                        }
                  }

            //
            // if midi file is GM/GS/XG this overrides the preferred
            // instrument setting

            if (mf.midiType() != MT_GENERIC) {
                  MidiInstrument* instr2 = 0;
                  for (iMidiInstrument i = midiInstruments.begin(); i != midiInstruments.end(); ++i) {
                        MidiInstrument* mi = *i;
                        switch(mf.midiType()) {
                              case MT_GM:
                                    if (mi->iname() == "GM")
                                          instr2 = mi;
                                    break;
                              case MT_GS:
                                    if (mi->iname() == "GS")
                                          instr2 = mi;
                                    break;
                              case MT_XG:
                                    if (mi->iname() == "XG")
                                          instr2 = mi;
                                    break;
                              case MT_GENERIC: // cannot happen
                                    break;
                              }
                        if (instr2)
                              break;
                        }
                  if (instr2)
                        instr = instr2;
                  }
            if (instr == 0)
                  instr = genericMidiInstrument;
            outPort->setInstrument(instr);
            }
      else
            outPort = song->midiOutPorts()->front();

      //
      // create MidiTrack and copy events to ->events()
      //    - combine note on/off events
      //    - calculate tick value for internal resolution
      //
      for (iMidiFileTrack t = etl->begin(); t != etl->end(); ++t) {
            MPEventList* el  = &((*t)->events);
            if (el->empty())
                  continue;
            //
            // if we split the track, SYSEX and META events go into
            // the first target track

            bool first = true;
            for (int channel = 0; channel < MIDI_CHANNELS; ++channel) {
                  //
                  // check if there are any events for channel in track:
                  //
                  iMPEvent i;
                  for (i = el->begin(); i != el->end(); ++i) {
                        MidiEvent ev = *i;
                        if (ev.type() != ME_SYSEX
                           && ev.type() != ME_META
                           && ev.channel() == channel)
                              break;
                        }
                  if (i == el->end())
                        continue;

                  MidiTrack* track = new MidiTrack();
//TODO3                  if ((*t)->isDrumTrack)
//                        track->setUseDrumMap(true);
                  track->outRoutes()->push_back(Route(outPort->channel(channel), -1, Route::TRACK));
                  if (inPort && config.connectToAllMidiTracks) {
                        for (int ch = 0; ch < MIDI_CHANNELS; ++ch) {
                              Route src(inPort, ch, Route::TRACK);
                              track->inRoutes()->push_back(src);
                              }
                        }

                  EventList* mel = track->events();
                  buildMidiEventList(mel, el, track, division, first);
                  first = false;

                  for (iEvent i = mel->begin(); i != mel->end(); ++i) {
                        Event event = i->second;
                        if (event.type() == Controller) {
                              int ctrl = event.dataA();
                              MidiInstrument* instr = outPort->instrument();
                              MidiChannel* mc = outPort->channel(channel);
                              mc->addMidiController(instr, ctrl);
                              CVal val;
                              val.i = event.dataB();
                              mc->addControllerVal(ctrl, event.tick(), val);
                              }
                        }
#if 0 //TODO3
                  if (channel == 9) {
                        track->setUseDrumMap(true);
                        //
                        // remap drum pitch with drumInmap
                        //
                        EventList* tevents = track->events();
                        for (iEvent i = tevents->begin(); i != tevents->end(); ++i) {
                              Event ev  = i->second;
                              if (ev.isNote()) {
                                    int pitch = drumInmap[ev.pitch()];
                                    ev.setPitch(pitch);
                                    }
                              }
                        }
#endif
                  processTrack(track);
                  if (track->name().isEmpty())
                        track->setDefaultName();
                  song->insertTrack0(track, -1);
                  }
            if (first) {
                  //
                  // track does only contain non-channel messages
                  // (SYSEX or META)
                  //
                  MidiTrack* track = new MidiTrack();
                  addRoute(Route(track, -1, Route::TRACK), Route(outPort->channel(0), -1, Route::TRACK));
                  EventList* mel = track->events();
                  buildMidiEventList(mel, el, track, division, true);
                  processTrack(track);
                  if (track->name().isEmpty())
                        track->setDefaultName();
                  song->insertTrack0(track, -1);
                  }
            }

      if (!merge) {
            TrackList* tl = song->tracks();
            if (!tl->empty()) {
                  Track* track = tl->front();
                  track->setSelected(true);
                  }
            unsigned int l = 1;
            MidiTrackList* mtl = song->midis();
            for (iMidiTrack t = mtl->begin(); t != mtl->end(); ++t) {
                  MidiTrack* track = *t;
                  PartList* parts = track->parts();
                  for (iPart p = parts->begin(); p != parts->end(); ++p) {
                        unsigned last = p->second->tick() + p->second->lenTick();
                        if (last > l)
                              l = last;
                        }
                  }
            song->setLen(l);

            AL::TimeSignature sig = AL::sigmap.timesig(0);
            int z = sig.z;
            int n = sig.n;

            transport->setTimesig(z, n);
//TD          int tempo = AL::tempomap.tempo(0);
//            transport->setTempo(tempo);

            bool masterF = !AL::tempomap.empty();
            song->setMasterFlag(masterF);
            transport->setMasterFlag(masterF);

            song->updatePos();
            }
      return false;
      }

//---------------------------------------------------------
//   processTrack
//    divide events into parts
//---------------------------------------------------------

void MusE::processTrack(MidiTrack* track)
      {
      EventList* tevents = track->events();
      if (tevents->empty())
            return;

      //---------------------------------------------------
      //    Parts ermitteln
      //    die Midi-Spuren werden in Parts aufgebrochen;
      //    ein neuer Part wird bei einer L�cke von einem
      //    Takt gebildet; die L�nge wird jeweils auf
      //    Takte aufgerundet und aligned
      //---------------------------------------------------

      PartList* pl = track->parts();

      int lastTick = 0;
      for (iEvent i = tevents->begin(); i != tevents->end(); ++i) {
            Event event = i->second;
            int epos = event.tick() + event.lenTick();
            if (epos > lastTick)
                  lastTick = epos;
            }

      int len = song->roundUpBar(lastTick+1);
      int bar2, beat;
      unsigned tick;
      AL::sigmap.tickValues(len, &bar2, &beat, &tick);

      QString partname = track->name();

      int lastOff = 0;
      int st = -1;      // start tick current part
      int x1 = 0;       // start tick current measure
      int x2 = 0;       // end tick current measure

      for (int bar = 0; bar < bar2; ++bar, x1 = x2) {
            x2 = AL::sigmap.bar2tick(bar+1, 0, 0);
            if (lastOff > x2) {
                  // this measure is busy!
                  continue;
                  }
            iEvent i1 = tevents->lower_bound(x1);
            iEvent i2 = tevents->lower_bound(x2);

            if (i1 == i2) {   // empty?
                  if (st != -1) {
                        Part* part = new Part(track);
                        part->setType(AL::TICKS);
                        part->setTick(st);
                        part->setLenTick(x1-st);
// printf("new part %d len: %d\n", st, x1-st);
                        part->setName(partname);
                        pl->add(part);
                        st = -1;
                        }
                  }
            else {
                  if (st == -1)
                        st = x1;    // begin new  part
                  //HACK:
                  //lastOff:
                  for (iEvent i = i1; i != i2; ++i) {
                        Event event = i->second;
                        if (event.type() == Note) {
                              int off = event.tick() + event.lenTick();
                              if (off > lastOff)
                                    lastOff = off;
                              }
                        }
                  }
            }
      if (st != -1) {
            Part* part = new Part(track);
            part->setType(AL::TICKS);
            part->setTick(st);
// printf("new part %d len: %d\n", st, x2-st);
            part->setLenTick(x2-st);
            part->setName(partname);
            pl->add(part);
            }

      //-------------------------------------------------------------
      //    assign events to parts
      //-------------------------------------------------------------

      for (iPart p = pl->begin(); p != pl->end(); ++p) {
            Part* part = p->second;
            int stick = part->tick();
            int etick = part->tick() + part->lenTick();
            iEvent r1 = tevents->lower_bound(stick);
            iEvent r2 = tevents->lower_bound(etick);
            int startTick = part->tick();

            EventList* el = part->events();
            for (iEvent i = r1; i != r2; ++i) {
                  Event ev = i->second;
                  int ntick = ev.tick() - startTick;
                  ev.setTick(ntick);
                  el->add(ev, ntick);
                  }
            tevents->erase(r1, r2);
            }

      if (tevents->size())
            printf("-----------events left: %zd\n", tevents->size());
      for (iEvent i = tevents->begin(); i != tevents->end(); ++i) {
            printf("%d===\n", i->first);
            i->second.dump();
            }
      // all events should be processed:
      assert(tevents->empty());
      }