summaryrefslogtreecommitdiff
path: root/attic/muse2-oom/muse2/muse/importmidi.cpp
blob: 6917a0fd6c1f8d207c4ea2655ccbf5dc2137604a (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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//=========================================================
//  MusE
//  Linux Music Editor
//  $Id: importmidi.cpp,v 1.26.2.10 2009/11/05 03:14:35 terminator356 Exp $
//
//  (C) Copyright 1999-2003 Werner Schweer (ws@seh.de)
//=========================================================

#include <assert.h>
#include <errno.h>
#include <values.h>

#include <QMessageBox>

#include "app.h"
#include "song.h"
#include "globals.h"
#include "filedialog.h"
#include "midi.h"
#include "midifile.h"
#include "midiport.h"
#include "transport.h"
#include "arranger.h"
//#include "arranger/arranger.h"    // p4.0.2
#include "mpevent.h"
#include "event.h"
#include "midictrl.h"
#include "instruments/minstrument.h"
#include "drummap.h"
//#include "midiedit/drummap.h"    // p4.0.2        
#include "xml.h"
#include "audio.h"
#include "gconfig.h"

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

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

void MusE::importMidi(const QString &file)
      {
      QString fn;
      if (file.isEmpty()) {
            fn = getOpenFileName(lastMidiPath, midi_file_pattern, this,
               tr("MusE: Import Midi"), 0);
            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();
                  break;
            case 1:
                  loadProjectFile(fn, false, false);    // replace
                  break;
            default:
                  return;
            }
      }

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

bool MusE::importMidi(const QString name, bool merge)
      {
      bool popenFlag;
      FILE* fp = fileOpen(this, name, QString(".mid"), "r", popenFlag);
      if (fp == 0)
            return true;
      MidiFile mf(fp);
      bool rv = mf.read();
      popenFlag ? pclose(fp) : fclose(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;
            }
      //
      //  evaluate song Type (GM, XG, GS, unknown)
      //
      MType t = song->mtype();
      if (!merge) {
            t = mf.mtype();
            song->setMType(t);
            }
      MidiInstrument* instr = 0;
      for (iMidiInstrument i = midiInstruments.begin(); i != midiInstruments.end(); ++i) {
            MidiInstrument* mi = *i;
            if ((mi->iname() == "GM" && ((t == MT_UNKNOWN) || (t == MT_GM)))
               || ((mi->iname() == "GS") && (t == MT_GS))
               || ((mi->iname() == "XG") && (t == MT_XG))) {
                  instr = mi;
                  break;
                  }
            }
      if (instr == 0) {
            // the standard instrument files (GM, GS, XG) must be present
            printf("no instrument, type %d\n", t);
            abort();
            }

      MidiFileTrackList* etl = mf.trackList();
      int division     = mf.division();

      //
      // 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;
            // somewhat silly and slooow:
            for (int port = 0; port < MIDI_PORTS; ++port) {
                  for (int channel = 0; channel < MIDI_CHANNELS; ++channel) {
                        //
                        // check if there are any events for port/channel in track:
                        //
                        iMPEvent i;
                        for (i = el->begin(); i != el->end(); ++i) {
                              MidiPlayEvent ev = *i;
                              if (ev.type() != ME_SYSEX && ev.type() != ME_META
                                 && ev.channel() == channel && ev.port() == port)
                                    break;
                              }
                        if (i == el->end())
                              continue;
                        MidiTrack* track = new MidiTrack();
                        if ((*t)->isDrumTrack)
                        {
                              track->setType(Track::DRUM);
                        }
                              
                        track->setOutChannel(channel);
                        track->setOutPort(port);

                        MidiPort* mport = &midiPorts[track->outPort()];
                        // this overwrites any instrument set for this port:
                        mport->setInstrument(instr);

                        EventList* mel = track->events();
                        //buildMidiEventList(mel, el, track, division, first);
                        // Don't do loops.
                        buildMidiEventList(mel, el, track, division, first, false);
                        first = false;

                        // Removed by T356. Handled by addPortCtrlEvents() below.
                        //for (iEvent i = mel->begin(); i != mel->end(); ++i) {
                        //      Event event = i->second;
                        //      if (event.type() == Controller) {
                        //            importController(channel, mport, event.dataA());
                        //            midiPorts[track->outPort()].setCtrl(channel, event.tick(), event.dataA(), event.dataB());
                        //            }
                        //      }

                        // Comment Added by T356.
                        // Hmm. buildMidiEventList already takes care of this. 
                        // But it seems to work. How? Must test. 
                        if (channel == 9 && song->mtype() != MT_UNKNOWN) {
                              track->setType(Track::DRUM);
                              //
                              // 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);
                                          }
                                    else
                                    if(ev.type() == Controller)
                                    {
                                      int ctl = ev.dataA();
                                      MidiController *mc = mport->drumController(ctl);
                                      if(mc)
                                        ev.setA((ctl & ~0xff) | drumInmap[ctl & 0x7f]);
                                    }
                                  }
                              }
                              
                        processTrack(track);
                        
                        // Added by T356. Send all controller values to the port's controller value list.
                        // No, done in song->insertTrack2() now.
                        //track->addPortCtrlEvents();
                        
                        song->insertTrack0(track, -1);
                        }
                  }
            if (first) {
                  //
                  // track does only contain non-channel messages
                  // (SYSEX or META)
                  //
                  MidiTrack* track = new MidiTrack();
                  track->setOutChannel(0);
                  track->setOutPort(0);
                  EventList* mel = track->events();
                  //buildMidiEventList(mel, el, track, division, true);
                  // Do SysexMeta. Don't do loops.
                  buildMidiEventList(mel, el, track, division, true, false);
                  processTrack(track);
                  song->insertTrack0(track, -1);
                  }
            }

      if (!merge) {
            TrackList* tl = song->tracks();
            if (!tl->empty()) {
                  Track* track = tl->front();
                  track->setSelected(true);
                  }
            song->initLen();

            int z, n;
            ///sigmap.timesig(0, z, n);
            AL::sigmap.timesig(0, z, n);

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

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

            song->updatePos();

            arranger->reset();
            ///arranger->setMode(int(song->mtype())); // p4.0.7 Tim
            }
      else {
            song->initLen();
           }

      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;
            }

      QString partname = track->name();
      int len = song->roundUpBar(lastTick+1);

      // p3.3.27
      if(config.importMidiSplitParts)
      {
        
        int bar2, beat;
        unsigned tick;
        ///sigmap.tickValues(len, &bar2, &beat, &tick);
        AL::sigmap.tickValues(len, &bar2, &beat, &tick);
        
        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 = sigmap.bar2tick(bar+1, 0, 0);
              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) {
                          MidiPart* part = new MidiPart(track);
                          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) {
              MidiPart* part = new MidiPart(track);
              part->setTick(st);
  // printf("new part %d len: %d\n", st, x2-st);
              part->setLenTick(x2-st);
              part->setName(partname);
              pl->add(part);
              }
      }
      else
      {
        // Just one long part...
        MidiPart* part = new MidiPart(track);
        //part->setTick(st);
        part->setTick(0);
        part->setLenTick(len);
        part->setName(partname);
        pl->add(part);
      }

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

      for (iPart p = pl->begin(); p != pl->end(); ++p) {
            MidiPart* part = (MidiPart*)(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);
                  }
            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());
      }

//---------------------------------------------------------
//   importController
//---------------------------------------------------------

void MusE::importController(int channel, MidiPort* mport, int n)
      {
      MidiInstrument* instr = mport->instrument();
      MidiCtrlValListList* vll = mport->controller();
      iMidiCtrlValList i = vll->find(channel, n);
      if (i != vll->end())
            return;           // controller does already exist
      MidiController* ctrl = 0;
      MidiControllerList* mcl = instr->controller();
// printf("import Ctrl\n");
      for (iMidiController i = mcl->begin(); i != mcl->end(); ++i) {
            MidiController* mc = i->second;
            int cn = mc->num();
// printf("   %x %x\n", n, cn);
            if (cn == n) {
                  ctrl = mc;
                  break;
                  }
            // wildcard?
            if (((cn & 0xff) == 0xff) && ((cn & ~0xff) == (n & ~0xff))) {
                  ctrl = i->second;
                  break;
                  }
            }
      if (ctrl == 0) {
            printf("controller 0x%x not defined for instrument %s, channel %d\n",
               n, instr->iname().toLatin1().constData(), channel);
// TODO: register default Controller
//      MidiController* MidiPort::midiController(int num) const
            }
      MidiCtrlValList* newValList = new MidiCtrlValList(n);
      vll->add(channel, newValList);
      }


//---------------------------------------------------------
//   importPart
//---------------------------------------------------------
void MusE::importPart()
      {
      unsigned curPos = song->cpos();
      TrackList* tracks = song->tracks();
      Track* track = 0;
      // Get first selected track:
      for (iTrack i = tracks->begin(); i != tracks->end(); i++) {
            Track* t = *i;
            if (t->selected()) {
                  // Changed by T356. Support mixed .mpt files.
                  //if (t->isMidiTrack()) {
                  if (t->isMidiTrack() || t->type() == Track::WAVE) {
                        track = t;
                        break;
                        }
                  else {
                        //QMessageBox::warning(this, QString("MusE"), tr("Import part is only valid for midi tracks!"));
                        QMessageBox::warning(this, QString("MusE"), tr("Import part is only valid for midi and wave tracks!"));
                        return;
                        }
                  }
            }

      if (track) {
            bool loadAll;
            QString filename = getOpenFileName(QString(""), part_file_pattern, this, tr("MusE: load part"), &loadAll);
            if (!filename.isEmpty()){
                  // Make a backup of the current clone list, to retain any 'copy' items,
                  //  so that pasting works properly after.
                  CloneList copyCloneList = cloneList;
                  // Clear the clone list to prevent any dangerous associations with
                  //  current non-original parts.
                  cloneList.clear();
            
                  importPartToTrack(filename, curPos, track);
                  
                  // Restore backup of the clone list, to retain any 'copy' items,
                  //  so that pasting works properly after.
                  cloneList.clear();
                  cloneList = copyCloneList;
               }   
            }
      else {
            QMessageBox::warning(this, QString("MusE"), tr("No track selected for import"));
            }
      }

//---------------------------------------------------------
//   importPartToTrack
//---------------------------------------------------------
void MusE::importPartToTrack(QString& filename, unsigned tick, Track* track)
{
      // Changed by T356
      /*
      bool popenFlag = false;
      FILE* fp = fileOpen(this, filename, ".mpt", "r", popenFlag, false, false);

      if(fp) 
      {
        MidiPart* importedPart = new MidiPart((MidiTrack*)track);
        Xml tmpXml = Xml(fp);

        Xml::Token token = tmpXml.parse();
        const QString& tag = tmpXml.s1();
        if (token == Xml::TagStart && tag == "part") 
        {
          // Make a backup of the current clone list, to retain any 'copy' items,
          //  so that pasting works properly after.
          CloneList copyCloneList = cloneList;
          // Clear the clone list to prevent any dangerous associations with
          //  current non-original parts.
          cloneList.clear();

          importedPart->read(tmpXml);
          importedPart->setTick(tick);
          
          // Restore backup of the clone list, to retain any 'copy' items,
          //  so that pasting works properly after.
          cloneList.clear();
          cloneList = copyCloneList;
          
          audio->msgAddPart(importedPart);
        }
        else 
        {
          printf("Unknown tag: %s\n", tag.toLatin1().constData());
        }
        fclose(fp);
      }      
      return;
      */            
        
      
      bool popenFlag = false;
      FILE* fp = fileOpen(this, filename, ".mpt", "r", popenFlag, false, false);

      if(fp) 
      {
        Xml xml = Xml(fp);
        bool firstPart = true;
        int posOffset = 0;
        int  notDone = 0;
        int  done = 0;
        
        bool end = false;
        song->startUndo();
        for (;;) 
        {
          Xml::Token token = xml.parse();
          const QString& tag = xml.s1();
          switch (token) 
          {
            case Xml::Error:
            case Xml::End:
                  end = true;
                  break;
            case Xml::TagStart:
                  if (tag == "part") {
                        //MidiPart* p = new MidiPart((MidiTrack*)track);
                        //p->read(xml);
                        
                        // Read the part.
                        Part* p = 0;
                        p = readXmlPart(xml, track);
                        // If it could not be created...
                        if(!p)
                        {
                          // Increment the number of parts not done and break.
                          ++notDone;
                          break;
                        } 
                        
                        // Increment the number of parts done.
                        ++done;
                        
                        if(firstPart) 
                        {
                          firstPart=false;
                          posOffset = tick - p->tick();
                        }
                        p->setTick(p->tick() + posOffset);
                        //finalPos=p->tick() + p->lenTick();
                        ////pos += p->lenTick();
                        audio->msgAddPart(p,false);
                        }
                  else
                        xml.unknown("MusE::importPartToTrack");
                  break;
            case Xml::TagEnd:
                  break;
            default:
                  end = true;
                  break;
          }
          if(end)
            break;
        }
        fclose(fp);
        song->endUndo(SC_PART_INSERTED);
        
        if(notDone)
        {
          int tot = notDone + done;
          QMessageBox::critical(this, QString("MusE"),
            QString().setNum(notDone) + (tot > 1 ? (tr(" out of ") + QString().setNum(tot)) : QString("")) + 
            (tot > 1 ? tr(" parts") : tr(" part")) + 
            tr(" could not be imported.\nLikely the track is the wrong type."));
        }
        
        return;
      }
}