MidiFile.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using System.Collections.Generic;
  5. using NAudio.Midi;
  6. using NAudio.Utils;
  7. namespace OpenVIII.AV.Midi
  8. {
  9. public class MidiFile : NAudio.Midi.MidiFile
  10. {
  11. public class MergeSort
  12. {
  13. /// <summary>
  14. /// In-place and stable implementation of MergeSort
  15. /// </summary>
  16. static void Sort<T>(IList<T> list, int lowIndex, int highIndex, IComparer<T> comparer)
  17. {
  18. if (lowIndex >= highIndex)
  19. {
  20. return;
  21. }
  22. int midIndex = (lowIndex + highIndex) / 2;
  23. // Partition the list into two lists and Sort them recursively
  24. Sort(list, lowIndex, midIndex, comparer);
  25. Sort(list, midIndex + 1, highIndex, comparer);
  26. // Merge the two sorted lists
  27. int endLow = midIndex;
  28. int startHigh = midIndex + 1;
  29. while ((lowIndex <= endLow) && (startHigh <= highIndex))
  30. {
  31. // MRH, if use < 0 sort is not stable
  32. if (comparer.Compare(list[lowIndex], list[startHigh]) <= 0)
  33. {
  34. lowIndex++;
  35. }
  36. else
  37. {
  38. // list[lowIndex] > list[startHigh]
  39. // The next element comes from the second list,
  40. // move the list[start_hi] element into the next
  41. // position and shuffle all the other elements up.
  42. T t = list[startHigh];
  43. for (int k = startHigh - 1; k >= lowIndex; k--)
  44. {
  45. list[k + 1] = list[k];
  46. }
  47. list[lowIndex] = t;
  48. lowIndex++;
  49. endLow++;
  50. startHigh++;
  51. }
  52. }
  53. }
  54. /// <summary>
  55. /// MergeSort a list of comparable items
  56. /// </summary>
  57. public static void Sort<T>(IList<T> list) where T : IComparable<T>
  58. {
  59. Sort(list, 0, list.Count - 1, Comparer<T>.Default);
  60. }
  61. /// <summary>
  62. /// MergeSort a list
  63. /// </summary>
  64. public static void Sort<T>(IList<T> list, IComparer<T> comparer)
  65. {
  66. Sort(list, 0, list.Count - 1, comparer);
  67. }
  68. }
  69. public MidiFile(string filename) : base(filename, true)
  70. {
  71. }
  72. private static void ExportBinary(BinaryWriter writer, MidiEventCollection events)
  73. {
  74. writer.Write(System.Text.Encoding.UTF8.GetBytes("MThd"));
  75. writer.Write(SwapUInt32(6)); // chunk size
  76. writer.Write(SwapUInt16((ushort)events.MidiFileType));
  77. writer.Write(SwapUInt16((ushort)events.Tracks));
  78. writer.Write(SwapUInt16((ushort)events.DeltaTicksPerQuarterNote));
  79. for (int track = 0; track < events.Tracks; track++)
  80. {
  81. IList<MidiEvent> eventList = events[track];
  82. writer.Write(System.Text.Encoding.UTF8.GetBytes("MTrk"));
  83. long trackSizePosition = writer.BaseStream.Position;
  84. writer.Write(SwapUInt32(0));
  85. long absoluteTime = events.StartAbsoluteTime;
  86. // use a stable sort to preserve ordering of MIDI events whose
  87. // absolute times are the same
  88. MergeSort.Sort(eventList, new MidiEventComparer());
  89. if (eventList.Count > 0 && !MidiEvent.IsEndTrack(eventList[eventList.Count - 1])) {
  90. Memory.Log.WriteLine("Exporting a track with a missing end track");
  91. }
  92. foreach (var midiEvent in eventList)
  93. {
  94. midiEvent.Export(ref absoluteTime, writer);
  95. }
  96. uint trackChunkLength = (uint)(writer.BaseStream.Position - trackSizePosition) - 4;
  97. writer.BaseStream.Position = trackSizePosition;
  98. writer.Write(SwapUInt32(trackChunkLength));
  99. writer.BaseStream.Position += trackChunkLength;
  100. }
  101. }
  102. private static uint SwapUInt32(uint i)
  103. {
  104. return ((i & 0xFF000000) >> 24) | ((i & 0x00FF0000) >> 8) | ((i & 0x0000FF00) << 8) | ((i & 0x000000FF) << 24);
  105. }
  106. private static ushort SwapUInt16(ushort i)
  107. {
  108. return (ushort)(((i & 0xFF00) >> 8) | ((i & 0x00FF) << 8));
  109. }
  110. private static void ExportCheckTracks(MidiEventCollection events)
  111. {
  112. if (events.MidiFileType == 0 && events.Tracks > 1)
  113. {
  114. throw new ArgumentException("Can't export more than one track to a type 0 file");
  115. }
  116. }
  117. /// <summary>
  118. /// Exports a MIDI file
  119. /// </summary>
  120. /// <param name="filename">Filename to export to</param>
  121. /// <param name="events">Events to export</param>
  122. public static void Export(string filename, MidiEventCollection events)
  123. {
  124. ExportCheckTracks(events);
  125. using (var writer = new BinaryWriter(File.Create(filename)))
  126. ExportBinary(writer, events);
  127. }
  128. /// <summary>
  129. /// Exports a MIDI file
  130. /// </summary>
  131. /// <param name="stream">Stream to work with</param>
  132. /// <param name="events">Events to export</param>
  133. public static void Export(Stream stream, MidiEventCollection events)
  134. {
  135. ExportCheckTracks(events);
  136. using (var writer = new BinaryWriter(stream))
  137. ExportBinary(writer, events);
  138. }
  139. }
  140. }