-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMain.hs
354 lines (336 loc) · 13.8 KB
/
Main.hs
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
{-# LANGUAGE CPP #-}
module Main (main) where
import Control.Applicative ((<|>))
import Control.Monad (forM_, unless, (>=>))
import Data.Char (toLower)
import Data.List (nub, partition, sort)
import Data.Maybe (catMaybes, fromMaybe, mapMaybe,
maybeToList)
import Data.Version (showVersion)
import qualified Paths_jammittools as Paths
import Sound.Jammit.Base
import Sound.Jammit.Export
import qualified System.Console.GetOpt as Opt
import System.Directory (createDirectoryIfMissing)
import qualified System.Environment as Env
import System.Exit (exitFailure)
import System.FilePath (makeValid, takeDirectory, (<.>), (</>))
import Text.PrettyPrint.Boxes (hsep, left, render, text, top, vcat,
(/+/))
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>))
#endif
printUsage :: IO ()
printUsage = do
prog <- Env.getProgName
putStrLn $ "jammittools v" ++ showVersion Paths.version
putStrLn ""
let header = "Usage: " ++ prog ++ " -t <title> -r <artist> [options]"
putStr $ Opt.usageInfo header argOpts
putStrLn ""
putStrLn "Instrument parts:"
putStr showCharPartMap
putStrLn "For sheet music, GRBA are tab instead of notation."
putStrLn "For audio, GBDKV are the backing tracks for each instrument."
putStrLn ""
putStrLn "Example usage:"
putStrLn " # Export all sheet music and audio to a new folder"
putStrLn $ " mkdir export; " ++ prog ++ " -t title -r artist -x export"
putStrLn " # Make a sheet music PDF with Guitar 1's notation and tab"
putStrLn $ " " ++ prog ++ " -t title -r artist -y gG -s gtr1.pdf"
putStrLn " # Make an audio track with no drums and no vocals"
putStrLn $ " " ++ prog ++ " -t title -r artist -y D -n vx -a nodrumsvox.wav"
main :: IO ()
main = do
(opts, nonopts, errs) <- Opt.getOpt Opt.Permute argOpts <$> Env.getArgs
unless (null $ nonopts ++ errs) $ do
forM_ nonopts $ \nonopt -> putStrLn $ "unrecognized argument `" ++ nonopt ++ "'"
forM_ errs putStr
printUsage
exitFailure
let args = foldr ($) defaultArgs opts
exportBoth matches dout = do
let sheets = getSheetParts matches
audios = getAudioParts matches
backingOrder = [Drums, Guitar, Keyboard, Bass, Vocal]
isGuitar p = elem (partToInstrument p) [Guitar, Bass]
(gtrs, nongtrs) = partition isGuitar [minBound .. maxBound]
backingTracks = flip mapMaybe backingOrder $ \i ->
case getOneResult (Without i) audios of
Left _ -> Nothing
Right fp -> Just (i, fp)
forM_ gtrs $ \p ->
case (getOneResult (Notation p) sheets, getOneResult (Tab p) sheets) of
(Right note, Right tab) -> let
parts = [note, tab]
systemHeight = sum $ map snd parts
fout = dout </> drop 4 (map toLower $ show p) <.> "pdf"
in do
putStrLn $ "Exporting notation & tab for " ++ show p
runSheet [note, tab] (getPageLines systemHeight args) fout
_ -> return ()
forM_ nongtrs $ \p ->
case getOneResult (Notation p) sheets of
Left _ -> return ()
Right note -> let
fout = dout </> drop 4 (map toLower $ show p) <.> "pdf"
in do
putStrLn $ "Exporting notation for " ++ show p
runSheet [note] (getPageLines (snd note) args) fout
forM_ [minBound .. maxBound] $ \p ->
case getOneResult (Only p) audios of
Left _ -> return ()
Right fp -> let
fout = dout </> drop 4 (map toLower $ show p) <.> "wav"
in do
putStrLn $ "Exporting audio for " ++ show p
runAudio [fp] [] fout
if rawBackings args
then forM_ backingTracks $ \(inst, fback) -> do
putStrLn $ "Exporting backing track for " ++ show inst
let fout = dout </> "backing-" ++ map toLower (show inst) <.> "wav"
runAudio [fback] [] fout
else case backingTracks of
[] -> return ()
(inst, fback) : _ -> let
others = [ fp | (Only p, fp) <- audios, partToInstrument p /= inst ]
fout = dout </> "backing.wav"
in do
putStrLn "Exporting backing audio (could take a while)"
runAudio [fback] others fout
clickTracks <- mapM loadBeats $ map (\(fp, _, _) -> fp) matches
case catMaybes clickTracks of
[] -> return ()
beats : _ -> do
putStrLn "Exporting metronome click track"
writeMetronomeTrack (dout </> "click.wav") beats
case function args of
PrintUsage -> printUsage
ShowDatabase -> do
matches <- searchResults args
putStr $ showLibrary matches
ExportAudio fout -> do
matches <- getAudioParts <$> searchResultsChecked args
let f = mapM (`getOneResult` matches) . mapMaybe charToAudioPart
case (f $ selectParts args, f $ rejectParts args) of
(Left err , _ ) -> error err
(_ , Left err ) -> error err
(Right yaifcs, Right naifcs) -> runAudio yaifcs naifcs fout
ExportClick fout -> do
matches <- map (\(fp, _, _) -> fp) <$> searchResultsChecked args
clickTracks <- mapM loadBeats matches
case catMaybes clickTracks of
[] -> do
putStrLn $ "Couldn't load beats.plist from any of these folders: " ++ show matches
exitFailure
beats : _ -> writeMetronomeTrack fout beats
CheckPresence -> do
matches <- getAudioParts <$> searchResultsChecked args
let f = mapM (`getOneResult` matches) . mapMaybe charToAudioPart
case (f $ selectParts args, f $ rejectParts args) of
(Left err , _ ) -> error err
(_ , Left err ) -> error err
(Right _ , Right _ ) -> return ()
ExportSheet fout -> do
matches <- getSheetParts <$> searchResultsChecked args
let f = mapM (`getOneResult` matches) . mapMaybe charToSheetPart
case f $ selectParts args of
Left err -> error err
Right parts -> let
systemHeight = sum $ map snd parts
in runSheet parts (getPageLines systemHeight args) fout
ExportAll dout -> do
matches <- searchResultsChecked args
exportBoth matches dout
ExportLib dout -> do
matches <- searchResults args
let titleArtists = nub [ (title info, artist info) | (_, info, _) <- matches ]
forM_ titleArtists $ \ta@(t, a) -> do
putStrLn $ "# SONG: " ++ a ++ " - " ++ t
let entries = filter (\(_, info, _) -> ta == (title info, artist info)) matches
songDir = dout </> makeValid (removeSlashes $ a ++ " - " ++ t)
removeSlashes = map $ \c -> case c of '/' -> '_'; '\\' -> '_'; _ -> c
createDirectoryIfMissing False songDir
exportBoth entries songDir
getPageLines :: Integer -> Args -> Int
getPageLines systemHeight args = let
pageHeight = sheetWidth / 8.5 * 11 :: Double
defaultLines = round $ pageHeight / fromIntegral systemHeight
in max 1 $ fromMaybe defaultLines $ pageLines args
-- | If there is exactly one pair with the given first element, returns its
-- second element. Otherwise (for 0 or >1 elements) returns an error.
getOneResult :: (Eq a, Show a) => a -> [(a, b)] -> Either String b
getOneResult x xys = case [ b | (a, b) <- xys, a == x ] of
[y] -> Right y
[] -> Left $ "Couldn't find the part " ++ show x
ys -> Left $ unwords
[ "Found"
, show $ length ys
, "different parts for"
, show x ++ ";"
, "this is probably a bug?"
]
-- | Displays a table of the library, possibly filtered by search terms.
showLibrary :: Library -> String
showLibrary lib = let
titleArtists = sort $ nub [ (title info, artist info) | (_, info, _) <- lib ]
partsFor ttl art = map partToChar $ sort $ concat
[ mapMaybe (trackTitle >=> titleToPart) trks
| (_, info, trks) <- lib
, (ttl, art) == (title info, artist info) ]
makeColumn h col = text h /+/ vcat left (map text col)
titleColumn = makeColumn "Title" $ map fst titleArtists
artistColumn = makeColumn "Artist" $ map snd titleArtists
partsColumn = makeColumn "Parts" $ map (uncurry partsFor) titleArtists
in render $ hsep 1 top [titleColumn, artistColumn, partsColumn]
-- | Loads the Jammit library, and applies the search terms from the arguments
-- to filter it.
searchResults :: Args -> IO Library
searchResults args = do
exeDir <- takeDirectory <$> Env.getExecutablePath
jmt <- case jammitDir args of
Just j -> return [j]
Nothing -> Env.lookupEnv "JAMMIT" >>= \mv -> case mv of
Just j -> return [j]
Nothing -> maybeToList <$> findJammitDir
db <- concat <$> mapM loadLibrary (exeDir : jmt)
return $ filterLibrary args db
-- | Checks that the search actually narrowed down the library to a single song.
searchResultsChecked :: Args -> IO Library
searchResultsChecked args = do
lib <- searchResults args
case [ info | (_, info, _) <- lib ] of
[] -> do
putStrLn "No songs matched your search."
exitFailure
x : xs -> if all (\y -> title y == title x && artist y == artist x) xs
then return lib
else do
putStrLn "Multiple songs matched your search:"
putStr $ showLibrary lib
exitFailure
argOpts :: [Opt.OptDescr (Args -> Args)]
argOpts =
[ Opt.Option ['t'] ["title"]
(Opt.ReqArg
(\s a -> a { filterLibrary = fuzzySearchBy title s . filterLibrary a })
"str")
"search by song title (fuzzy)"
, Opt.Option ['r'] ["artist"]
(Opt.ReqArg
(\s a -> a { filterLibrary = fuzzySearchBy artist s . filterLibrary a })
"str")
"search by song artist (fuzzy)"
, Opt.Option ['T'] ["title-exact"]
(Opt.ReqArg
(\s a -> a { filterLibrary = exactSearchBy title s . filterLibrary a })
"str")
"search by song title (exact)"
, Opt.Option ['R'] ["artist-exact"]
(Opt.ReqArg
(\s a -> a { filterLibrary = exactSearchBy artist s . filterLibrary a })
"str")
"search by song artist (exact)"
, Opt.Option ['y'] ["yes-parts"]
(Opt.ReqArg (\s a -> a { selectParts = s }) "parts")
"parts to appear in sheet music or audio"
, Opt.Option ['n'] ["no-parts"]
(Opt.ReqArg (\s a -> a { rejectParts = s }) "parts")
"parts to subtract (add inverted) from audio"
, Opt.Option ['l'] ["lines"]
(Opt.ReqArg (\s a -> a { pageLines = Just $ read s }) "int")
"number of systems per page"
, Opt.Option ['j'] ["jammit"]
(Opt.ReqArg (\s a -> a { jammitDir = Just s }) "directory")
"location of Jammit library"
, Opt.Option ['?', 'h'] ["help"]
(Opt.NoArg $ \a -> a { function = PrintUsage })
"function: print usage info"
, Opt.Option ['d'] ["database"]
(Opt.NoArg $ \a -> a { function = ShowDatabase })
"function: display all songs in db"
, Opt.Option ['s'] ["sheet"]
(Opt.ReqArg (\s a -> a { function = ExportSheet s }) "file")
"function: export sheet music"
, Opt.Option ['a'] ["audio"]
(Opt.ReqArg (\s a -> a { function = ExportAudio s }) "file")
"function: export audio"
, Opt.Option ['m'] ["metronome"]
(Opt.ReqArg (\s a -> a { function = ExportClick s }) "file")
"function: export metronome audio"
, Opt.Option ['x'] ["export"]
(Opt.ReqArg (\s a -> a { function = ExportAll s }) "dir")
"function: export song to dir"
, Opt.Option ['b'] ["backup"]
(Opt.ReqArg (\s a -> a { function = ExportLib s }) "dir")
"function: export library to dir"
, Opt.Option ['c'] ["check"]
(Opt.NoArg $ \a -> a { function = CheckPresence })
"function: check presence of audio parts"
, Opt.Option [] ["raw"]
(Opt.NoArg $ \a -> a { rawBackings = True })
"when exporting song/library, extract all individual backing tracks"
]
data Args = Args
{ filterLibrary :: Library -> Library
, selectParts :: String
, rejectParts :: String
, pageLines :: Maybe Int
, jammitDir :: Maybe FilePath
, function :: Function
, rawBackings :: Bool
}
data Function
= PrintUsage
| ShowDatabase
| ExportSheet FilePath
| ExportAudio FilePath
| ExportClick FilePath
| ExportAll FilePath
| ExportLib FilePath
| CheckPresence
deriving (Eq, Ord, Show, Read)
defaultArgs :: Args
defaultArgs = Args
{ filterLibrary = id
, selectParts = ""
, rejectParts = ""
, pageLines = Nothing
, jammitDir = Nothing
, function = PrintUsage
, rawBackings = False
}
partToChar :: Part -> Char
partToChar p = case p of
PartGuitar1 -> 'g'
PartGuitar2 -> 'r'
PartBass1 -> 'b'
PartBass2 -> 'a'
PartDrums1 -> 'd'
PartDrums2 -> 'm'
PartKeys1 -> 'k'
PartKeys2 -> 'y'
PartPiano -> 'p'
PartSynth -> 's'
PartOrgan -> 'o'
PartVocal -> 'v'
PartBVocals -> 'x'
charPartMap :: [(Char, Part)]
charPartMap = [ (partToChar p, p) | p <- [minBound .. maxBound] ]
showCharPartMap :: String
showCharPartMap = let
len = ceiling (fromIntegral (length charPartMap) / 2 :: Double)
(map1, map2) = splitAt len charPartMap
col1 = vcat left [ text $ [c] ++ ": " ++ drop 4 (show p) | (c, p) <- map1 ]
col2 = vcat left [ text $ [c] ++ ": " ++ drop 4 (show p) | (c, p) <- map2 ]
in render $ hsep 2 top [text "", col1, col2]
charToSheetPart :: Char -> Maybe SheetPart
charToSheetPart c = let
notation = Notation <$> lookup c charPartMap
tab = Tab <$> lookup (toLower c) charPartMap
in notation <|> tab
charToAudioPart :: Char -> Maybe AudioPart
charToAudioPart c = let
only = Only <$> lookup c charPartMap
without = Without . partToInstrument <$> lookup (toLower c) charPartMap
in only <|> without