Mercurial > vba-clojure
view clojure/com/aurellem/run/music.clj @ 477:ee000791ab4e
formatted ship-of-regret-and-sleep.mid for smooth mini-midi conversion.
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Fri, 04 May 2012 07:23:07 -0500 |
parents | f28a3baa4c56 |
children | 91db9d1ce213 |
line wrap: on
line source
1 (ns com.aurellem.run.music2 (:use (com.aurellem.gb saves gb-driver util constants3 items vbm characters money4 rlm-assembly))5 (:use (com.aurellem.run util title save-corruption6 bootstrap-0 bootstrap-1))7 (:require clojure.string)8 (:import [com.aurellem.gb.gb_driver SaveState])9 (:import java.io.File))11 (def third-kind12 (File. "/home/r/proj/midi/third-kind.mid"))14 (def pony15 (File. "/home/r/proj/vba-clojure/music/pony-title.mid"))17 (def sync-test18 (File. "/home/r/proj/vba-clojure/music/sync-test.mid"))20 (def drum-test21 (File. "/home/r/proj/vba-clojure/music/drum-test.mid"))23 (def regret24 (File. "/home/r/proj/vba-clojure/music/ship-of-regret-and-sleep.mid"))26 (defn raw-midi-text [#^File midi-file]27 (:out28 (clojure.java.shell/sh29 "midicsv"30 (.getCanonicalPath midi-file)31 "-")))33 (def command-line #"^(\d+), (\d+), ([^,]+)(.*)$")35 (defmulti parse-command :command)37 (defn discard-args [command] (dissoc command :args))39 (defmethod parse-command :Start_track40 [command] (discard-args command))42 (defmethod parse-command :End_track43 [command] (discard-args command))45 (defmethod parse-command :default46 [command] command)48 (defn parse-number-list49 [number-list-str]50 (map #(Integer/parseInt %)51 (clojure.string/split number-list-str #", ")))53 (defmethod parse-command :Tempo54 [command]55 (update-in command [:args] #(Integer/parseInt %)))57 (defn parse-midi-note-list58 [midi-note-list-str]59 (let [[channel note velocity]60 (parse-number-list midi-note-list-str)]61 {:channel channel :note note :velocity velocity}))63 (defmethod parse-command :Note_on_c64 [command]65 (update-in command [:args] parse-midi-note-list))67 (defmethod parse-command :Note_off_c68 [command]69 (update-in command [:args] parse-midi-note-list))71 (defmethod parse-command :Header72 [command]73 (let [args (:args command)74 [format num-tracks division] (parse-number-list args)]75 (assoc command :args76 {:format format77 :num-tracks num-tracks78 :division division})))80 (defmethod parse-command :Program_c81 [command]82 (let [args (:args command)83 [channel program-num] (parse-number-list args)]84 (assoc command :args85 {:channel channel86 :program-num program-num})))88 (defn parse-midi [#^File midi-file]89 (map90 (comp parse-command91 (fn [line]92 (let [[[_ channel time command args]]93 (re-seq command-line line)]94 {:channel (Integer/parseInt channel)95 :time (Integer/parseInt time)96 :command (keyword command)97 :args (apply str (drop 2 args))})))98 (drop-last99 (clojure.string/split-lines100 (raw-midi-text midi-file)))))102 (def music-base new-kernel)104 (defn store [n address]105 (flatten106 [0xF5107 0xE5109 0x3E110 n112 0x21113 (reverse (disect-bytes-2 address))115 0x77117 0xE1118 0xF1]))120 (defn infinite-loop []121 [0x18 0xFE])123 (def divider-register 0xFF04)125 (defrecord Bit-Note [frequency volume duration duty])127 (defn clear-music-registers []128 (flatten129 [(store (Integer/parseInt "00000000" 2) 0xFF10) ;; sweep130 (store (Integer/parseInt "00000000" 2) 0xFF11) ;; pattern duty131 (store (Integer/parseInt "00000000" 2) 0xFF12) ;; volume132 (store (Integer/parseInt "00000000" 2) 0xFF13) ;; frequency-low133 (store (Integer/parseInt "00000000" 2) 0xFF14) ;; frequency-high135 (store (Integer/parseInt "00000000" 2) 0xFF16) ;; pattern duty 000000136 (store (Integer/parseInt "00000000" 2) 0xFF17) ;; volume 0000137 (store (Integer/parseInt "00000000" 2) 0xFF18) ;; frequency-low138 (store (Integer/parseInt "00000000" 2) 0xFF19) ;; 00000 frequency-high140 (store (Integer/parseInt "00000000" 2) 0xFF1A)141 (store (Integer/parseInt "00000000" 2) 0xFF1B)142 (store (Integer/parseInt "00000000" 2) 0xFF1C)143 (store (Integer/parseInt "00000000" 2) 0xFF1D)144 (store (Integer/parseInt "00000000" 2) 0xFF1E)146 (store (Integer/parseInt "00000000" 2) 0xFF20) ;; length147 (store (Integer/parseInt "00000000" 2) 0xFF21) ;; volume148 (store (Integer/parseInt "00000000" 2) 0xFF22) ;; noise-frequency149 (store (Integer/parseInt "00000000" 2) 0xFF23) ;; control150 ]))153 ;; mini-midi syntax155 ;; codes156 ;; note-code == 0x00157 ;; change-duty-code = 0x01158 ;; silence-code = 0x02160 ;; silence format161 ;; 2 bytes162 ;; [silence-code (0x02)]163 ;; [duration-8-bits]165 ;; note data format166 ;; 4 bytes167 ;; [note-code (0x00)]168 ;; [volume-4-bits 0 frequency-high-3-bits]169 ;; [frequengy-low-8-bits]170 ;; [duration-8-bits]172 ;; change-duty-format173 ;; 2 bytes174 ;; [change-duty-code (0x01)]175 ;; [new-duty]177 (def note-code 0x00)178 (def change-duty-code 0x01)179 (def silence-code 0x02)181 (defn do-message182 "Read the message which starts at the current value of HL and do183 what it says. Duration is left in A, and HL is advanced184 appropraitely."185 ([] (do-message 0x16 1))186 ([sound-base-address wave-duty]187 (assert (<= 0 wave-duty 3))188 (let [switch189 [0x2A ;; load message code into A, increment HL191 ;; switch on message192 0xFE193 note-code195 0x20196 :note-length]198 play-note199 [0x3E ;; set wave-duty200 (bit-shift-left wave-duty 6)201 0xE0202 sound-base-address203 0x2A ;; load volume/frequency-high info204 0xF5 ;; push A205 0xE6206 (Integer/parseInt "11110000" 2) ;; volume mask207 0xE0208 (inc sound-base-address) ;;0x17 ;; set volume209 0xF1 ;; pop A210 0xE6211 (Integer/parseInt "00000111" 2) ;; frequency-high mask212 0xE0213 (+ 3 sound-base-address) ;;0x19 ;; set frequency-high215 0x2A ;; load frequency low-bits216 0xE0217 (+ 2 sound-base-address) ;;0x18 ;; set frequency-low-bits218 0x2A]] ;; load duration219 (replace220 {:note-length (count play-note)}221 (concat switch play-note)))))223 (defn play-noise224 "read [noise-code, volume, duration] and play the noise. Duration is left in225 A, and HL is advanced appropraitely."226 ([]227 [0x2A ;; load noise-code into A228 0xE0229 0x22 ;; write noise-code231 0x2A ;; load volume232 0xE0233 0x21 ;; write volume235 0x2A] ;; load duration into A236 ))239 ;; (defn play-note240 ;; "Play the note referenced by HL in the appropiate channel.241 ;; Leaves desired-duration in A."243 ;; [0x2A ;; load volume/frequency-high info244 ;; 0xF5 ;; push A245 ;; 0xE6246 ;; (Integer/parseInt "11110000" 2) ;; volume mask247 ;; 0xE0248 ;; 0x17 ;; set volume249 ;; 0xF1 ;; pop A250 ;; 0xE6251 ;; (Integer/parseInt "00000111" 2) ;; frequency-high mask252 ;; 0xE0253 ;; 0x19 ;; set frequency-high255 ;; 0x2A ;; load frequency low-bits256 ;; 0xE0257 ;; 0x18 ;; set frequency-low-bits259 ;; 0x2A ;; load duration260 ;; ])262 (defn music-step [sound-base-address wave-duty noise?]263 ;; C == current-ticks264 ;; A == desired-ticks266 (flatten267 [;; restore variables from stack268 0xE1 ;; pop HL269 0xC1 ;; pop CB270 0xF1 ;; pop AF273 0xF5 ;; push A274 0xF0275 0x05 ;; load current ticks from 0xF005276 0xB8 ;;277 0x30 ;; increment C only if last result caused carry278 0x01279 0x0C281 0x47 ;; update sub-ticks (A->B)283 0xF1 ;; pop AF, now A contains desired-ticks285 0xB9 ;; compare with current ticks287 ;; if desired-ticks = current ticks288 ;; go to next note ; set current set ticks to 0.290 (if noise?291 [0x20292 (+ 2 (count (play-noise)))293 (play-noise)]295 [0x20296 (+ (count (do-message 0 0)) 2)297 (do-message sound-base-address wave-duty)])299 0x0E300 0x00 ;; 0->C (current-ticks)302 ;; save variables to stack303 0xF5 ;; push AF304 0xC5 ;; push CB305 0xE5 ;; push HL308 ]))310 (def music-1 0x11)311 (def music-2 0x16)313 (defn music-kernel [wave-duty-1 wave-duty-2]314 (flatten315 [;; global initilization section316 (clear-music-registers)318 0x3E319 0x01320 0xE0321 0x06 ;; set TMA to 0323 0x3E324 (Integer/parseInt "00000110" 2)325 0xE0326 0x07 ;; set TAC to 65536 Hz and activate timer328 ;; initialize frame 1329 0x21330 0x00331 0xA0 ;; set HL to 0xA000 == music-start 1332 0x0E333 0x00 ;; 0->C334 0x06335 0x00 ;; 0->B337 0xAF ;; 0->A339 0xF5 ;; push AF340 0xC5 ;; push CB341 0xE5 ;; push HL343 ;; initialize frame 2344 0x21345 0x00346 0xB0 ;; set HL to 0xB000 == music-start 2348 0xF5 ;; push AF349 0xC5 ;; push CB350 0xE5 ;; push HL353 ;; initialize frame 3 (noise)354 0x21355 0x00356 0xA9 ;; 0xA9OO -> HL358 0xF5 ;; push AF359 0xC5 ;; push CB360 0xE5 ;; push HL362 ;; main music loop364 0xE8 ;; SP + 12; activate frame 1365 12366 (music-step music-1 wave-duty-1 false)368 0xE8 ;; SP - 6; activate frame 2369 (->signed-8-bit -6)370 (music-step music-2 wave-duty-2 false)372 0xE8 ;; SP - 6; activate frame 3373 (->signed-8-bit -6)374 (music-step nil nil true)376 0x18377 (->signed-8-bit (+378 ;; two music-steps379 (- (* 2 (count (music-step 0 0 false))))380 (- (count (music-step nil nil true)))381 -2 ;; this jump instruction382 -2 ;; activate frame 1383 -2 ;; activate frame 2384 -2 ;; activate frame 3385 ))]))387 (defn frequency-code->frequency388 [code]389 (assert (<= 0 code 2047))390 (/ 131072 (- 2048 code)))392 (defn clamp [x low high]393 (cond (> x high) high394 (< x low) low395 true x))397 (defn frequency->frequency-code398 [frequency]399 (clamp400 (Math/round401 (float402 (/ (- (* 2048 frequency) 131072) frequency)))403 0x00 2048))405 (defn note-codes [frequency volume duration]406 (assert (<= 0 volume 0xF))407 (if (<= duration 0xFF)408 (let [frequency-code409 (frequency->frequency-code frequency)410 volume&high-frequency411 (+ (bit-shift-left volume 4)412 (bit-shift-right frequency-code 8))413 low-frequency414 (bit-and 0xFF frequency-code)]415 [note-code416 volume&high-frequency417 low-frequency418 duration])419 (vec420 (flatten421 [(note-codes frequency volume 0xFF)422 (note-codes frequency volume (- duration 0xFF))]))))425 (defn midi-code->frequency426 [midi-code]427 (* 8.1757989156428 (Math/pow 2 (* (float (/ 12)) midi-code))))430 ;; division == clock-pulses / quarter-note431 ;; tempo == microseconds / quarter-note433 ;; have: clock-pulses434 ;; want: seconds437 (defn silence [length]438 {:frequency 1439 :duration length440 :volume 0})442 (defn commands443 "return all events where #(= (:command %) command)"444 [command s]445 (filter #(= command (:command %)) s))447 (defn track-info [#^File midi-file]448 (let [events (parse-midi midi-file)449 track-titles (commands :Title_t events)450 track-info451 (map #(read-string (read-string (:args %))) track-titles)452 track-map453 (zipmap track-info track-titles)]454 track-map))456 (defn target-tracks457 "return the track-numbers in the form [voice-0 voice-1 noise]"458 [#^File midi-file]459 (let [track-data (track-info midi-file)460 track-order461 (zipmap (map :out (keys track-data))462 (vals track-data))463 channel-nums (map (comp :channel track-order) (range 3))]464 channel-nums))466 (defn midi-track->abstract-mini-midi467 [#^File midi-file track-num]468 (let [midi-events (parse-midi midi-file)470 note-on-events (commands :Note_on_c midi-events)471 note-off-events (commands :Note_off_c midi-events)473 select-channel474 (fn [n s]475 (sort-by :time (filter #(= n (:channel %)) s)))477 channel-on (select-channel track-num note-on-events)479 channel-off (select-channel track-num note-off-events)482 tempo (:args (first (commands :Tempo midi-events)))483 division484 (:division (:args (first (commands :Header midi-events))))486 notes487 (map488 (fn [note-on note-off]489 {:frequency (midi-code->frequency (:note (:args note-on)))490 :midi-code (:note (:args note-on))491 :duration492 (/ (* (/ tempo division)493 (- (:time note-off) (:time note-on)))494 1e6) ;; convert clock-pulses into seconds495 :volume (int (/ (:velocity (:args note-on)) 10))496 :time-stamp (/ (* (/ tempo division)497 (:time note-on)) 1e6)})498 channel-on channel-off)500 silences501 (map (fn [note-1 note-2]502 (let [note-1-space (- (:time-stamp note-2)503 (:time-stamp note-1))504 note-1-length (:duration note-1)]505 (silence (- note-1-space note-1-length))))506 ;; to handle silence at the beginning.507 (concat [(assoc (silence 0)508 :time-stamp 0)] notes)509 notes)511 notes-with-silence512 (concat513 (filter (comp not zero? :duration)514 (interleave silences notes))515 [(silence 3)])]516 notes-with-silence))518 (defn midi-track->mini-midi-voice [#^File midi-file track-num]519 (let [abstract-mini-midi520 (midi-track->abstract-mini-midi midi-file track-num)]521 (map522 (fn [note-event]523 (note-codes (:frequency note-event)524 (:volume note-event)525 (int (* (:duration note-event) 0x100))))526 abstract-mini-midi)))528 (def midi-code->gb-noise-code529 {nil 0xFF530 35 87531 38 20532 39 0533 })535 (defn noise-codes [code volume duration]536 (assert (<= 0 volume 0xF))537 (if (<= duration 0xFF)538 [(midi-code->gb-noise-code code code)539 (bit-shift-left volume 4)540 duration]541 (vec542 (flatten543 [(noise-codes code volume 0xFF)544 (noise-codes code volume (- duration 0xFF))]))))546 (defn midi-track->mini-midi-noise [#^File midi-file track-num]547 (let [abstract-mini-midi548 (midi-track->abstract-mini-midi midi-file track-num)]549 (map550 (fn [noise-event]551 (noise-codes (:midi-code noise-event)552 (:volume noise-event)553 (int (* (:duration noise-event) 0x100))))554 abstract-mini-midi)))557 (defn midi->mini-midi [#^File midi-file]558 (let [targets (target-tracks midi-file)559 duty-info (keys (track-info midi-file))]561 {:voice-1 (midi-track->mini-midi-voice midi-file (nth targets 0))562 :voice-2 (midi-track->mini-midi-voice midi-file (nth targets 1))563 :noise (midi-track->mini-midi-noise midi-file (nth targets 2))564 :duty (zipmap (map :out duty-info)565 (map #(get % :duty 0) duty-info))}))567 (defn play-midi [#^File midi-file]568 (let [voice-1-target 0xA000569 voice-2-target 0xB000570 noise-target 0xA900571 program-target 0xC000572 mini-midi (midi->mini-midi midi-file)573 long-silence (flatten (note-codes 20 0 20001))574 long-noise-silence575 (interleave (range 500) (repeat 0x00) (repeat 255))577 voice-1 (flatten (:voice-1 mini-midi))578 wave-duty-1 ((:duty mini-midi) 0 0)580 voice-2 (flatten (:voice-2 mini-midi))581 wave-duty-2 ((:duty mini-midi) 1 0)583 noise (flatten (:noise mini-midi))584 ]586 (-> (second (music-base))587 (set-memory-range voice-1-target long-silence)588 (set-memory-range voice-2-target long-silence)589 (set-memory-range noise-target long-noise-silence)590 (set-memory-range voice-1-target voice-1)591 (set-memory-range voice-2-target voice-2)592 (set-memory-range noise-target noise)593 (set-memory-range594 program-target595 (music-kernel wave-duty-1 wave-duty-2))596 (PC! program-target))))598 (defn test-noise []599 (let [noise-pattern600 (concat (interleave (range 0x100) (repeat 0xF0) (repeat 255))601 (interleave (range 10) (repeat 0x00) (repeat 255)))]603 (-> (second (music-base))604 (set-memory-range 0xA900 (flatten noise-pattern))605 (set-memory-range 0xC000 (music-kernel 0 0))606 (PC! 0xC000))))608 (defn test-play-noise [noise-code]609 (Thread/sleep 300)610 (println "playing noise:" noise-code)611 (run-moves612 (let [noise-pattern613 (interleave (repeat 10 noise-code) (repeat 0xF0) (repeat 255))]614 (-> (second (music-base))615 (set-memory-range 0xA900 (flatten noise-pattern))616 (set-memory-range 0xC000 (music-kernel 0 0))617 (PC! 0xC000)))618 (repeat 20 [])))620 (defn test-all-noises []621 (dorun (map test-play-noise (range 0x100))))623 (def C4 (partial note-codes 261.63))624 (def D4 (partial note-codes 293.66))625 (def E4 (partial note-codes 329.63))626 (def F4 (partial note-codes 349.23))627 (def G4 (partial note-codes 392))628 (def A4 (partial note-codes 440))629 (def B4 (partial note-codes 493.88))630 (def C5 (partial note-codes 523.3))632 (def scale633 (flatten634 [(C4 0xF 0x40)635 (D4 0xF 0x40)636 (E4 0xF 0x40)637 (F4 0xF 0x40)638 (G4 0xF 0x40)639 (A4 0xF 0x40)640 (B4 0xF 0x40)641 (C5 0xF 0x40)]))643 (defn play-music [music-bytes]644 (let [program-target 0xC000645 music-target 0xA000]646 (-> (set-memory-range (second (music-base))647 program-target (music-kernel))648 (set-memory-range music-target music-bytes)649 (PC! program-target))))651 (defn run-program652 ([program]653 (let [target 0xC000]654 (-> (set-memory-range (second (music-base))655 target program)656 (PC! target)))))658 (defn test-timer []659 (flatten660 [0x3E661 0x01662 0xE0663 0x06 ;; set TMA to 0665 0x3E666 (Integer/parseInt "00000100" 2)667 0xE0668 0x07 ;; set TAC to 16384 Hz and activate timer670 (repeat671 500672 [0xF0673 0x05])]))