diff --git a/composeApp/src/androidMain/kotlin/mg/dot/feufaro/midi/MidiPlayer.kt b/composeApp/src/androidMain/kotlin/mg/dot/feufaro/midi/MidiPlayer.kt index 3e5468f..cc5b32d 100644 --- a/composeApp/src/androidMain/kotlin/mg/dot/feufaro/midi/MidiPlayer.kt +++ b/composeApp/src/androidMain/kotlin/mg/dot/feufaro/midi/MidiPlayer.kt @@ -175,8 +175,7 @@ actual class FMediaPlayer actual constructor( val tempoType: String = "", val endGridForTempo: Int = -1, val targetTempoMultiplier: Float = 0.6f, - val newBpm: Float? = null, - val newKey: String? = null + val newBpm: Float? = null ) private val navigationSteps = mutableListOf() private val prefs: Settings = provideSettings() @@ -573,7 +572,6 @@ actual class FMediaPlayer actual constructor( val dcG = Regex("""D\.?C\.?_GROUP_PART""")*/ 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) metadataList.forEach { midiMarker -> 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 { isDsFin || isDcFin -> { val target = if (lastSegno > 0) lastSegno else 0 @@ -769,7 +753,7 @@ actual class FMediaPlayer actual constructor( }.sortedBy { step -> when { 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 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 ───────────────────── step.isHold -> { val beatMs = (60_000 / targetBpm).toLong() diff --git a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/midi/MidiWriterKotlin.kt b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/midi/MidiWriterKotlin.kt index 9054d54..1ec4e65 100644 --- a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/midi/MidiWriterKotlin.kt +++ b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/midi/MidiWriterKotlin.kt @@ -4,6 +4,8 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import mg.dot.feufaro.FileRepository +import mg.dot.feufaro.solfa.Transpose +import mg.dot.feufaro.viewmodel.MidiMarkers class MidiWriterKotlin constructor(private val fileRepository: FileRepository) { 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) { sequence.addMeta( type, tick, nbData, metaByteString) } - fun process(pitches: List) { + fun process( + pitches: List, + markers: List = emptyList(), + initialKey: String = "C" + ) { val lastTick = 0 nextTick.clear() // addMetaMessage(0x59, 4, 2, 2,0) tick = 0 - pitches.forEach { - if (it.metaType > 0) { - val metaDataString = String(it.metaBytes, Charsets.UTF_8) - addMetaMessage(it.metaType, it.tick, it.metaByteSize, metaDataString) - } else if (it.pitch != "") { - addNote(it.voiceNumber, it.pitch.toInt(), 100, it.tick.toLong()) + val modulaRegex = Regex("""D(ô|o)?\s*dia\s*(C|Db|D|Eb|E|F|Gb|G|Ab|A|Bb|B)""", RegexOption.IGNORE_CASE) + val keyChangeMap = mutableMapOf() + + markers.forEach { midiMarker -> + val gridIdx = (midiMarker.gridIndex ?: 0) * 60L + 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()) } } } diff --git a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/Solfa.kt b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/Solfa.kt index 54ce7cc..c40fd8e 100644 --- a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/Solfa.kt +++ b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/Solfa.kt @@ -274,7 +274,10 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository attachLyricsToPitches(localAccumulator) val pitches = pitches.sortedWith(compareBy({ it.tick }, { it.voiceNumber })) 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") val allowed = sharedScreenModel.allowedStanzas.value val currentStz = sharedScreenModel.stanza.value @@ -447,7 +450,10 @@ class Solfa(val sharedScreenModel: SharedScreenModel, private val fileRepository attachLyricsToPitches(localAccumulator) val pitches = pitches.sortedWith(compareBy({ it.tick }, { it.voiceNumber })) 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") } } @@ -3191,4 +3197,32 @@ private fun getBpmFromMeasure(measure: String?): Float { else -> 120.0f } +} + +private fun finalizeMarkers(listTuos: List, sharedScreenModel: SharedScreenModel): List { + 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() } \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/TimeUnitObject.kt b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/TimeUnitObject.kt index 8d3d768..d630900 100644 --- a/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/TimeUnitObject.kt +++ b/composeApp/src/commonMain/kotlin/mg/dot/feufaro/solfa/TimeUnitObject.kt @@ -739,39 +739,6 @@ fun LazyVerticalGridTUO( val measures = remember(tuoList, 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 = remember(tuoList) { val map = mutableMapOf() @@ -798,14 +765,6 @@ fun LazyVerticalGridTUO( 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) { sharedScreenModel.updateSyllablesFromList( measures = measures, diff --git a/composeApp/src/desktopMain/kotlin/mg/dot/feufaro/midi/MidiPlayer.kt b/composeApp/src/desktopMain/kotlin/mg/dot/feufaro/midi/MidiPlayer.kt index 40c38e0..2e0db35 100644 --- a/composeApp/src/desktopMain/kotlin/mg/dot/feufaro/midi/MidiPlayer.kt +++ b/composeApp/src/desktopMain/kotlin/mg/dot/feufaro/midi/MidiPlayer.kt @@ -64,8 +64,7 @@ actual class FMediaPlayer actual constructor( val tempoType: String = "", val endGridForTempo: Int = -1, val targetTempoMultiplier: Float = 0.6f, - val newBpm: Float? = null, - val newKey: String? = null + val newBpm: Float? = null ) private val navigationSteps = mutableListOf() @@ -243,7 +242,6 @@ actual class FMediaPlayer actual constructor( var lastFactor = Dynamic.ZERO.factor val ritRegex = Regex("""rit\.?|ritard\.?|ritenuto\.?|ritardando""", 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) 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 { //DSFin isDsFin || isDcFin -> { @@ -545,7 +529,7 @@ actual class FMediaPlayer actual constructor( val currentStanza = sharedScreenModel.stanza.value.coerceAtLeast(1) 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 (Math.abs(sequencer!!.tempoInBPM - targetBpm) > 0.1) { @@ -558,7 +542,7 @@ actual class FMediaPlayer actual constructor( }.sortedBy { step -> when { 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 else -> 3 } @@ -576,31 +560,6 @@ actual class FMediaPlayer actual constructor( 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 -> { if(step.finActive) { step.alreadyDone = true