Implement key change & modulation in MIDI process

This commit is contained in:
Hasinjato 2026-10-29 11:24:16 +03:00
parent 4179e3d0ce
commit c40858fcc6
5 changed files with 92 additions and 119 deletions

View file

@ -175,8 +175,7 @@ actual class FMediaPlayer actual constructor(
val tempoType: String = "", val tempoType: String = "",
val endGridForTempo: Int = -1, val endGridForTempo: Int = -1,
val targetTempoMultiplier: Float = 0.6f, val targetTempoMultiplier: Float = 0.6f,
val newBpm: Float? = null, val newBpm: Float? = null
val newKey: String? = null
) )
private val navigationSteps = mutableListOf<NavigationStep>() private val navigationSteps = mutableListOf<NavigationStep>()
private val prefs: Settings = provideSettings() private val prefs: Settings = provideSettings()
@ -573,7 +572,6 @@ actual class FMediaPlayer actual constructor(
val dcG = Regex("""D\.?C\.?_GROUP_PART""")*/ val dcG = Regex("""D\.?C\.?_GROUP_PART""")*/
val finReg = Regex("""(fine|fin|farany|end)""", RegexOption.IGNORE_CASE) val finReg = Regex("""(fine|fin|farany|end)""", RegexOption.IGNORE_CASE)
val modulaRegex = Regex("""D(ô|o)?\s*dia\s*(C|Db|D|Eb|E|F|Gb|G|Ab|A|Bb|B)""", RegexOption.IGNORE_CASE)
val tempoRegex = Regex("""^(?:♩|P)\s*[:=]\s*(\d+)""", RegexOption.IGNORE_CASE) val tempoRegex = Regex("""^(?:♩|P)\s*[:=]\s*(\d+)""", RegexOption.IGNORE_CASE)
metadataList.forEach { midiMarker -> metadataList.forEach { midiMarker ->
val ci = midiMarker.gridIndex ?: 0 val ci = midiMarker.gridIndex ?: 0
@ -611,20 +609,6 @@ actual class FMediaPlayer actual constructor(
} }
} }
// Modulation Do dia ..
val modMatch = modulaRegex.find(mTrim)
if (modMatch != null) {
val targetKey = modMatch.groupValues[2]
navigationSteps.add(
NavigationStep(
marker = mTrim,
gridIndex = ci,
newKey = targetKey
)
)
println("Modulation mémorisée à la grille $ci -> $targetKey")
}
when { when {
isDsFin || isDcFin -> { isDsFin || isDcFin -> {
val target = if (lastSegno > 0) lastSegno else 0 val target = if (lastSegno > 0) lastSegno else 0
@ -769,7 +753,7 @@ actual class FMediaPlayer actual constructor(
}.sortedBy { step -> }.sortedBy { step ->
when { when {
step.isHold -> 0 step.isHold -> 0
step.newBpm != null || step.newKey != null || step.isFarany -> 1 step.newBpm != null || step.isFarany -> 1
step.isTempoChange || step.hairPin != null || step.dynamic != null -> 2 step.isTempoChange || step.hairPin != null || step.dynamic != null -> 2
else -> 3 else -> 3
} }
@ -789,13 +773,6 @@ actual class FMediaPlayer actual constructor(
} }
} }
// Modulation
step.newKey != null -> {
val baseKeyIdx = Transpose.keyToNumber.indexOf("C").coerceAtLeast(0)
val targetKeyIdx = Transpose.keyToNumber.indexOf(step.newKey).coerceAtLeast(0)
transpositionSemitones = targetKeyIdx - baseKeyIdx
}
// ── Point d'orgue ───────────────────── // ── Point d'orgue ─────────────────────
step.isHold -> { step.isHold -> {
val beatMs = (60_000 / targetBpm).toLong() val beatMs = (60_000 / targetBpm).toLong()

View file

@ -4,6 +4,8 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import mg.dot.feufaro.FileRepository import mg.dot.feufaro.FileRepository
import mg.dot.feufaro.solfa.Transpose
import mg.dot.feufaro.viewmodel.MidiMarkers
class MidiWriterKotlin constructor(private val fileRepository: FileRepository) { class MidiWriterKotlin constructor(private val fileRepository: FileRepository) {
private val sequence = MidiSequence(60) private val sequence = MidiSequence(60)
@ -46,17 +48,59 @@ class MidiWriterKotlin constructor(private val fileRepository: FileRepository)
fun addMetaMessage(type: Int, tick: Int, nbData: Int, metaByteString: String) { fun addMetaMessage(type: Int, tick: Int, nbData: Int, metaByteString: String) {
sequence.addMeta( type, tick, nbData, metaByteString) sequence.addMeta( type, tick, nbData, metaByteString)
} }
fun process(pitches: List<MidiPitch>) { fun process(
pitches: List<MidiPitch>,
markers: List<MidiMarkers> = emptyList(),
initialKey: String = "C"
) {
val lastTick = 0 val lastTick = 0
nextTick.clear() nextTick.clear()
// addMetaMessage(0x59, 4, 2, 2,0) // addMetaMessage(0x59, 4, 2, 2,0)
tick = 0 tick = 0
pitches.forEach { val modulaRegex = Regex("""D(ô|o)?\s*dia\s*(C|Db|D|Eb|E|F|Gb|G|Ab|A|Bb|B)""", RegexOption.IGNORE_CASE)
if (it.metaType > 0) { val keyChangeMap = mutableMapOf<Long, String>()
val metaDataString = String(it.metaBytes, Charsets.UTF_8)
addMetaMessage(it.metaType, it.tick, it.metaByteSize, metaDataString) markers.forEach { midiMarker ->
} else if (it.pitch != "") { val gridIdx = (midiMarker.gridIndex ?: 0) * 60L
addNote(it.voiceNumber, it.pitch.toInt(), 100, it.tick.toLong()) midiMarker.marker.forEach { text ->
val cleanText = text.trim()
val modMatch = modulaRegex.find(cleanText)
if (modMatch != null) {
val targetKey = modMatch.groupValues[2]
keyChangeMap[gridIdx] = targetKey
}
}
}
var currentKey = initialKey
val baseKeyIdx = Transpose.keyToNumber.indexOf(initialKey).coerceAtLeast(0)
pitches.forEach { noteEvent ->
val rawTick = noteEvent.tick.toLong()
val pendingKeyTicks = keyChangeMap.keys.filter { it <= rawTick }.sorted()
pendingKeyTicks.forEach { keyRawTick ->
val targetKey = keyChangeMap[keyRawTick] ?: initialKey
currentKey = targetKey
val keyIdx = Transpose.keyToNumber.indexOf(targetKey)
if (keyIdx != -1) {
val sf = Transpose.keyToArmature[keyIdx]
val keyBytes = byteArrayOf(sf.toByte(), 0.toByte())
addMetaMessage(0x59, keyRawTick.toInt(), 2, String(keyBytes, Charsets.ISO_8859_1))
}
keyChangeMap.remove(keyRawTick)
}
val currentKeyIdx = Transpose.keyToNumber.indexOf(currentKey).coerceAtLeast(0)
val transpositionSemitones = currentKeyIdx - baseKeyIdx
if (noteEvent.metaType > 0) {
val metaDataString = String(noteEvent.metaBytes, Charsets.UTF_8)
addMetaMessage(noteEvent.metaType, noteEvent.tick, noteEvent.metaByteSize, metaDataString)
} else if (noteEvent.pitch != "") {
val finalTransposedPitch = noteEvent.pitch.toInt() + transpositionSemitones
addNote(noteEvent.voiceNumber, finalTransposedPitch, 100, noteEvent.tick.toLong())
} }
} }
} }

View file

@ -274,7 +274,10 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
attachLyricsToPitches(localAccumulator) attachLyricsToPitches(localAccumulator)
val pitches = pitches.sortedWith(compareBy({ it.tick }, { it.voiceNumber })) val pitches = pitches.sortedWith(compareBy({ it.tick }, { it.voiceNumber }))
val midiWriter = MidiWriterKotlin(fileRepository) val midiWriter = MidiWriterKotlin(fileRepository)
midiWriter.process(pitches) val markers = finalizeMarkers(localAccumulator, sharedScreenModel)
val originalKey = sharedScreenModel.songKey.value.ifEmpty { meta["C"] ?: "C" }
midiWriter.process(pitches, markers, originalKey)
midiWriter.save("whawyd3.mid") midiWriter.save("whawyd3.mid")
val allowed = sharedScreenModel.allowedStanzas.value val allowed = sharedScreenModel.allowedStanzas.value
val currentStz = sharedScreenModel.stanza.value val currentStz = sharedScreenModel.stanza.value
@ -447,7 +450,10 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository
attachLyricsToPitches(localAccumulator) attachLyricsToPitches(localAccumulator)
val pitches = pitches.sortedWith(compareBy({ it.tick }, { it.voiceNumber })) val pitches = pitches.sortedWith(compareBy({ it.tick }, { it.voiceNumber }))
val midiWriter = MidiWriterKotlin(fileRepository) val midiWriter = MidiWriterKotlin(fileRepository)
midiWriter.process(pitches) val markers = sharedScreenModel.getFullMarkers()
val originalKey = sharedScreenModel.songKey.value.ifEmpty { meta["C"] ?: "C" }
midiWriter.process(pitches, markers, originalKey)
midiWriter.save("whawyd3.mid") midiWriter.save("whawyd3.mid")
} }
} }
@ -3191,4 +3197,32 @@ private fun getBpmFromMeasure(measure: String?): Float {
else -> 120.0f else -> 120.0f
} }
}
private fun finalizeMarkers(listTuos: List<TimeUnitObject>, sharedScreenModel: SharedScreenModel): List<MidiMarkers> {
val rawMarkers = listTuos.drop(1).mapIndexedNotNull { globalIndex, oneTUO ->
val rawMarker = oneTUO.pTemplate.markerToString()
val hairPin = oneTUO.hasHairPin()
val markerList = sharedScreenModel.parseMarkers(rawMarker).toMutableList()
if (hairPin != null) {
markerList.add(hairPin.toString())
}
if (markerList.isNotEmpty()) {
val myTimestamp = sharedScreenModel.tuoTimestamps.value.getOrElse(globalIndex) { 0L }
MidiMarkers(
timestamp = myTimestamp,
gridIndex = globalIndex,
template = oneTUO.pTemplate.template,
lastCallerMarker = oneTUO.pTemplate.lastCalledMarker,
marker = markerList,
noteBefore = oneTUO.prevTUO?.pTemplate?.template ?: "",
separat = oneTUO.sep0,
note = oneTUO.tuNotes.getOrNull(1).toString()
)
} else null
}.distinctBy { it.gridIndex }
sharedScreenModel.updateAndFinalizeMidiData(rawMarkers)
return sharedScreenModel.getFullMarkers()
} }

View file

@ -739,39 +739,6 @@ fun LazyVerticalGridTUO(
val measures = remember(tuoList, gridColumnCount) { val measures = remember(tuoList, gridColumnCount) {
tuoList.drop(1).chunked(gridColumnCount) tuoList.drop(1).chunked(gridColumnCount)
} }
// Avant column affichage:
val metadataList = remember(tuoList) {
tuoList.drop(1).mapIndexedNotNull { globalIndex, oneTUO ->
val rawMarker = oneTUO.pTemplate.markerToString()
val hairPin = oneTUO.hasHairPin()
val markerList = sharedScreenModel.parseMarkers(rawMarker).toMutableList()
/*val finalMarker = when {
hairPin != null && markerText.isBlank() -> hairPin.toString()
hairPin != null && markerText.isNotBlank() -> "${markerText.trim()}$hairPin"
markerText.isNotBlank() -> markerText
else -> null
}*/
if (hairPin != null) {
markerList.add(hairPin.toString())
}
if (markerList.isNotEmpty()) {
val myTimestamp = sharedScreenModel.tuoTimestamps.value.getOrElse(globalIndex) { 0L }
// println("MetaData[$globalIndex] marker='${markerList.joinToString(", ")}' hairpin=$hairPin")
MidiMarkers(
myTimestamp,
globalIndex,
oneTUO.pTemplate.template,
oneTUO.pTemplate.lastCalledMarker,
markerList,
oneTUO.prevTUO?.pTemplate?.template ?: "",
oneTUO.sep0,
oneTUO.tuNotes.getOrNull(1).toString()
)
} else null
}.distinctBy { it.gridIndex }
}
val hairpinByEndBlock: Map<Int, HairpinRange> = remember(tuoList) { val hairpinByEndBlock: Map<Int, HairpinRange> = remember(tuoList) {
val map = mutableMapOf<Int, HairpinRange>() val map = mutableMapOf<Int, HairpinRange>()
@ -798,14 +765,6 @@ fun LazyVerticalGridTUO(
map map
} }
// Envoyer les données au ViewModel une seule fois
LaunchedEffect(metadataList) {
if (metadataList.isNotEmpty()) {
println("Mise à jour MidiData avec ${metadataList.size}")
sharedScreenModel.updateAndFinalizeMidiData(metadataList)
}
}
LaunchedEffect(measures, sharedScreenModel.stanza.value) { LaunchedEffect(measures, sharedScreenModel.stanza.value) {
sharedScreenModel.updateSyllablesFromList( sharedScreenModel.updateSyllablesFromList(
measures = measures, measures = measures,

View file

@ -64,8 +64,7 @@ actual class FMediaPlayer actual constructor(
val tempoType: String = "", val tempoType: String = "",
val endGridForTempo: Int = -1, val endGridForTempo: Int = -1,
val targetTempoMultiplier: Float = 0.6f, val targetTempoMultiplier: Float = 0.6f,
val newBpm: Float? = null, val newBpm: Float? = null
val newKey: String? = null
) )
private val navigationSteps = mutableListOf<NavigationStep>() private val navigationSteps = mutableListOf<NavigationStep>()
@ -243,7 +242,6 @@ actual class FMediaPlayer actual constructor(
var lastFactor = Dynamic.ZERO.factor var lastFactor = Dynamic.ZERO.factor
val ritRegex = Regex("""rit\.?|ritard\.?|ritenuto\.?|ritardando""", RegexOption.IGNORE_CASE) val ritRegex = Regex("""rit\.?|ritard\.?|ritenuto\.?|ritardando""", RegexOption.IGNORE_CASE)
val rallRegex = Regex("""rall\.?|rallent\.?|rallentando""", RegexOption.IGNORE_CASE) val rallRegex = Regex("""rall\.?|rallent\.?|rallentando""", RegexOption.IGNORE_CASE)
val modulaRegex = Regex("""D(ô|o)?\s*dia\s*(C|Db|D|Eb|E|F|Gb|G|Ab|A|Bb|B)""", RegexOption.IGNORE_CASE)
val tempoRegex = Regex("""^(?:♩|P)\s*[:=]\s*(\d+)""", RegexOption.IGNORE_CASE) val tempoRegex = Regex("""^(?:♩|P)\s*[:=]\s*(\d+)""", RegexOption.IGNORE_CASE)
metadataList.forEach { midiMarker -> metadataList.forEach { midiMarker ->
@ -286,20 +284,6 @@ actual class FMediaPlayer actual constructor(
} }
} }
// ModulationDo dia C
val modMatch = modulaRegex.find(mTrim)
if (modMatch != null) {
val targetKey = modMatch.groupValues[2]
navigationSteps.add(
NavigationStep(
marker = mTrim,
gridIndex = currentIndex,
newKey = targetKey
)
)
println("Modulation mémorisée à la grille $currentIndex -> $targetKey")
}
when { when {
//DSFin //DSFin
isDsFin || isDcFin -> { isDsFin || isDcFin -> {
@ -545,7 +529,7 @@ actual class FMediaPlayer actual constructor(
val currentStanza = sharedScreenModel.stanza.value.coerceAtLeast(1) val currentStanza = sharedScreenModel.stanza.value.coerceAtLeast(1)
val lyrics = currentTuo?.getSingleSyllable(currentStanza)?.joinToString(" ") ?: "" val lyrics = currentTuo?.getSingleSyllable(currentStanza)?.joinToString(" ") ?: ""
println("Grille #%-3d | Tick: %-5d | Parole: [%s]".format(currentIndex, tick, lyrics)) //println("Grille #%-3d | Tick: %-5d | Parole: [%s]".format(currentIndex, tick, lyrics))
if (sequencer?.isRunning == true) { if (sequencer?.isRunning == true) {
if (Math.abs(sequencer!!.tempoInBPM - targetBpm) > 0.1) { if (Math.abs(sequencer!!.tempoInBPM - targetBpm) > 0.1) {
@ -558,7 +542,7 @@ actual class FMediaPlayer actual constructor(
}.sortedBy { step -> }.sortedBy { step ->
when { when {
step.isHold -> 0 step.isHold -> 0
step.newBpm != null || step.newKey != null || step.isFin -> 1 step.newBpm != null || step.isFin -> 1
step.isTempoChange || step.hairPin != null || step.dynamic != null -> 2 step.isTempoChange || step.hairPin != null || step.dynamic != null -> 2
else -> 3 else -> 3
} }
@ -576,31 +560,6 @@ actual class FMediaPlayer actual constructor(
sharedScreenModel.setBpmFlow(step.newBpm) sharedScreenModel.setBpmFlow(step.newBpm)
} }
// Modulation
step.newKey != null -> {
//println("Exécution modulation vers tonalité ${step.newKey} à la grille $currentIndex")
val baseKeyIdx = Transpose.keyToNumber.indexOf("C").coerceAtLeast(0)
val targetKeyIdx = Transpose.keyToNumber.indexOf(step.newKey).coerceAtLeast(0)
val semitonesShift = targetKeyIdx - baseKeyIdx
val pitchBendValue = (8192 + (semitonesShift * 2048)).coerceIn(0, 16383)
try {
val synth = synthetizer
if (synth != null) {
val channels = synth.channels
if (channels != null) {
val count = if (channels.size < 4) channels.size else 4
for (i in 0 until count) {
val channel: MidiChannel? = channels[i]
channel?.setPitchBend(pitchBendValue)
}
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
step.isFin -> { step.isFin -> {
if(step.finActive) { if(step.finActive) {
step.alreadyDone = true step.alreadyDone = true