-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmain.cpp
511 lines (434 loc) · 12.8 KB
/
main.cpp
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
// TODO:
// - catch Ctrl+C
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // for memcmp()
#include <ctype.h>
#include <locale.h>
#include <errno.h>
#include <vector>
#include <string>
#include <map>
#include <sstream>
#include <algorithm>
#ifdef _MSC_VER
#define stricmp _stricmp
#define strnicmp _strnicmp
#else
#define stricmp strcasecmp
#define strnicmp strncasecmp
#endif
#ifdef _WIN32
#include <conio.h>
#include <Windows.h>
#define USE_WMAIN
#else
#include <unistd.h>
#define Sleep(x) usleep(x * 1000)
#include <limits.h> // for PATH_MAX
#include <signal.h> // for kill()
#define MAX_PATH PATH_MAX
#endif
#include <ini.h>
#include <getopt.h>
#include "stdtype.h"
#include "utils.hpp"
#include "m3uargparse.hpp"
#include "config.hpp"
#include "version.h"
#ifndef SHARE_PREFIX
#define SHARE_PREFIX "/usr"
#endif
// from playctrl.cpp
extern UINT8 PlayerMain(UINT8 showFileName);
struct OptionItem
{
unsigned char flags; // 0 - no parameter, 1 - has 1 parameter
char shortOpt; // character for short option ['\0' = no short option]
const char* longOpt; // word for long option
const char* paramName; // [optional] parameter name for "help" screen
const char* helpText;
};
typedef std::vector<OptionItem> OptionList;
static char* GetAppFilePath(void);
static void InitAppSearchPaths(const char* argv_0);
static std::string ReadLineAsUTF8(void);
static int IniValHandler(void* user, const char* section, const char* name, const char* value);
static UINT8 LoadConfig(const std::string& iniPath, Configuration& cfg);
static std::string GenerateOptData(const OptionList& optList, std::vector<struct option>* longOpts);
static void PrintVersion(void);
static void PrintArgumentHelp(const OptionList& optList);
static int ParseArguments(int argc, char* argv[], const OptionList& optList, Configuration& argCfg);
// can't initialize an std::vector directly in C++98
static const OptionItem OPT_LIST_ARR[] =
{
{0, 'h', "help", NULL, "show this help screen"},
{0, 'v', "version", NULL, "show version"},
{0, 'w', "dump-wav", NULL, "enable WAV dumping"},
{1, 'd', "output-device", "id", "output device ID"},
{1, 'c', "config", "option", "set configuration option, format: section.key=Data"},
};
static const size_t OPT_LIST_SIZE = sizeof(OPT_LIST_ARR) / sizeof(OPT_LIST_ARR[0]);
std::vector<std::string> appSearchPaths;
static std::vector<std::string> cfgFileNames;
Configuration playerCfg;
std::vector<SongFileList> songList;
std::vector<PlaylistFileList> plList;
#ifdef USE_WMAIN
int wmain(int argc, wchar_t* wargv[])
{
char** argv;
#else
int main(int argc, char* argv[])
{
#endif
const OptionList optionList(OPT_LIST_ARR, OPT_LIST_ARR + OPT_LIST_SIZE);
int argbase;
UINT8 retVal;
//int resVal;
Configuration argCfg;
UINT8 fnEnterMode;
setlocale(LC_ALL, ""); // enable UTF-8 support on Linux
setlocale(LC_NUMERIC, "C"); // enforce decimal dot
#ifdef USE_WMAIN
argv = (char**)malloc(argc * sizeof(char*));
for (argbase = 0; argbase < argc; argbase ++)
{
int bufSize = WideCharToMultiByte(CP_UTF8, 0, wargv[argbase], -1, NULL, 0, NULL, NULL);
argv[argbase] = (char*)malloc(bufSize);
WideCharToMultiByte(CP_UTF8, 0, wargv[argbase], -1, argv[argbase], bufSize, NULL, NULL);
}
// Note: I'm not freeing argv anywhere. I'll let Windows take care about it this one time.
#endif
printf(APP_NAME);
printf("\n----------\n");
argbase = ParseArguments(argc, argv, optionList, argCfg);
if (argbase == 0)
return 0;
else if (argbase < 0)
return 1;
#if 0
if (argc < argbase + 1)
{
PrintVersion();
printf("Usage: %s [options] file1.vgm [file2.vgz] [...]\n", argv[0]);
PrintArgumentHelp(optionList);
return 0;
}
#endif
InitAppSearchPaths(argv[0]);
cfgFileNames.push_back("VGMPlay.ini");
cfgFileNames.push_back("vgmplay.ini");
std::string cfgFilePath = FindFile_List(cfgFileNames, appSearchPaths);
if (cfgFilePath.empty())
printf("%s not found - falling back to defaults.\n", cfgFileNames[cfgFileNames.size() - 1].c_str());
if (! cfgFilePath.empty())
{
LoadConfig(cfgFilePath, playerCfg); // load INI file
playerCfg += argCfg; // override INI settings with commandline options
}
#if 0 // print current configuration
{
printf("Config File:\n");
for (auto& cfgSect : playerCfg._sections)
{
printf("[%s]\n", cfgSect.first.c_str());
for (auto& uEnt : cfgSect.second.unord)
printf("\t.%s = %s\n", uEnt.first.c_str(), uEnt.second.c_str());
for (auto& oEnt : cfgSect.second.ordered)
printf("\t+%s = %s\n", oEnt.first.c_str(), oEnt.second.c_str());
}
}
#endif
if (argbase < argc)
{
fnEnterMode = 1;
retVal = ParseSongFiles(std::vector<const char*>(argv + argbase, argv + argc), songList, plList);
}
else
{
fnEnterMode = 0;
printf("\nFile Name:\t");
std::string fileName = ReadLineAsUTF8();
if (fileName.empty())
return 0; // nothing entered
std::vector<const char*> fileList;
fileList.push_back(fileName.c_str());
retVal = ParseSongFiles(fileList, songList, plList);
}
if (retVal)
{
printf("One or more playlists couldn't be read!\n");
if (! songList.empty()) // only wait when we won't exit immediately after
getchar();
}
if (songList.empty())
{
printf("No songs to play.\n");
return 0;
}
printf("\n");
retVal = PlayerMain(fnEnterMode);
printf("Bye.\n");
return 0;
}
static char* GetAppFilePath(void)
{
char* appPath;
int retVal;
#ifdef _WIN32
#ifdef USE_WMAIN
std::vector<wchar_t> appPathW;
appPathW.resize(MAX_PATH);
retVal = GetModuleFileNameW(NULL, &appPathW[0], appPathW.size());
if (! retVal)
appPathW[0] = L'\0';
retVal = WideCharToMultiByte(CP_UTF8, 0, &appPathW[0], -1, NULL, 0, NULL, NULL);
if (retVal < 0)
retVal = 1;
appPath = (char*)malloc(retVal);
retVal = WideCharToMultiByte(CP_UTF8, 0, &appPathW[0], -1, appPath, retVal, NULL, NULL);
if (retVal < 0)
appPath[0] = '\0';
appPathW.clear();
#else
appPath = (char*)malloc(MAX_PATH * sizeof(char));
retVal = GetModuleFileNameA(NULL, appPath, MAX_PATH);
if (! retVal)
appPath[0] = '\0';
#endif
#else
appPath = (char*)malloc(PATH_MAX * sizeof(char));
retVal = readlink("/proc/self/exe", appPath, PATH_MAX);
if (retVal == -1)
appPath[0] = '\0';
#endif
return appPath;
}
static void InitAppSearchPaths(const char* argv_0)
{
appSearchPaths.clear();
#ifndef _WIN32
// 1. [Unix only] global share directory
appSearchPaths.push_back(SHARE_PREFIX "/share/vgmplay/");
#endif
// 2. actual application path (potentially resolved symlink)
char* appPath = GetAppFilePath();
const char* appTitle = GetFileTitle(appPath);
if (appTitle != appPath)
appSearchPaths.push_back(std::string(appPath, appTitle - appPath));
free(appPath);
// 3. called path
appTitle = GetFileTitle(argv_0);
if (appTitle != argv_0)
{
std::string callPath(argv_0, appTitle - argv_0);
if (callPath != appSearchPaths[appSearchPaths.size() - 1])
appSearchPaths.push_back(callPath);
}
// 4. home/config directory
std::string cfgDir;
#ifdef _WIN32
cfgDir = getenv("USERPROFILE");
cfgDir += "/.vgmplay/";
#else
char* xdgPath = getenv("XDG_CONFIG_HOME");
if (xdgPath != NULL && xdgPath[0] != '\0')
{
cfgDir = xdgPath;
}
else
{
cfgDir = getenv("HOME");
cfgDir += "/.config";
}
cfgDir += "/vgmplay/";
#endif
appSearchPaths.push_back(cfgDir);
// 5. working directory
appSearchPaths.push_back("./");
return;
}
static std::string ReadLineAsUTF8(void)
{
std::string fileName(MAX_PATH, '\0');
char* strPtr;
#ifdef _WIN32
UINT oldCP = GetConsoleCP();
// Set the Console Input Codepage to ANSI.
// The Output Codepage must be left at OEM, else the displayed characters are wrong.
SetConsoleCP(GetACP()); // set input codepage
#endif
strPtr = fgets(&fileName[0], (int)fileName.size(), stdin);
if (strPtr == NULL)
fileName[0] = '\0';
fileName.resize(strlen(&fileName[0])); // resize to actual size
RemoveControlChars(fileName);
#ifdef _WIN32
RemoveQuotationMarks(fileName, '\"');
#else
RemoveQuotationMarks(fileName, '\'');
#endif
#ifdef _WIN32
// Using GetConsoleCP() is important here, as playing with the console font resets
// the Console Codepage to OEM.
if (! fileName.empty())
{
std::wstring fileNameW;
UINT conCP = GetConsoleCP();
int bufSize;
// convert from ANSI/OEM codepage via UTF-16 to UTF-8
// using string.size() results in a conversion that *excludes* the '\0' terminator
bufSize = MultiByteToWideChar(conCP, 0, fileName.c_str(), fileName.size(), NULL, 0);
fileNameW.resize(bufSize);
MultiByteToWideChar(conCP, 0, fileName.c_str(), fileName.size(), &fileNameW[0], bufSize);
bufSize = WideCharToMultiByte(CP_UTF8, 0, fileNameW.c_str(), fileNameW.size(), NULL, 0, NULL, NULL);
fileName.resize(bufSize);
WideCharToMultiByte(CP_UTF8, 0, fileNameW.c_str(), fileNameW.size(), &fileName[0], bufSize, NULL, NULL);
}
// This fixes the display of non-ANSI characters.
SetConsoleCP(oldCP);
#endif
return fileName;
}
static int IniValHandler(void* user, const char* section, const char* name, const char* value)
{
Configuration* cfg = (Configuration*)user;
bool ordered = false;
if (! strnicmp(name, "Mute", 4))
ordered = true;
else if (! strnicmp(name, "Pan", 3))
ordered = true;
cfg->AddEntry(section, name, value, ordered);
return 1;
}
static UINT8 LoadConfig(const std::string& iniPath, Configuration& cfg)
{
int retVal;
retVal = ini_parse(iniPath.c_str(), IniValHandler, &cfg);
if (retVal == -2)
return 0xF8; // malloc error
else if (retVal == -1)
return 0xF0; // file not found
else if (retVal < 0)
return 0xFF; // unknown error
else if (retVal > 0)
return 0x01; // parse error
else
return 0x00;
}
static std::string GenerateOptData(const OptionList& optList, std::vector<struct option>* longOpts)
{
size_t curOpt;
std::string shortOpts;
if (longOpts != NULL)
longOpts->resize(optList.size() + 1);
shortOpts = "";
for (curOpt = 0; curOpt < optList.size(); curOpt ++)
{
const OptionItem& optDef = optList[curOpt];
if (optDef.shortOpt != '\0')
{
shortOpts += optDef.shortOpt;
if (optDef.flags & 0x01)
shortOpts += ':';
}
if (longOpts != NULL)
{
struct option& lOpt = (*longOpts)[curOpt];
lOpt.name = optDef.longOpt;
lOpt.val = optDef.shortOpt;
lOpt.flag = NULL;
lOpt.has_arg = (optDef.flags & 0x01) ? required_argument : no_argument;
}
}
if (longOpts != NULL)
{
// write terminator option
struct option& lOptTerm = (*longOpts)[optList.size()];
memset(&lOptTerm, 0x00, sizeof(struct option));
}
return shortOpts;
}
static void PrintVersion(void)
{
printf("VGMPlay %s, supports VGM %s\n", VGMPLAY_VER_STR, VGM_VER_STR);
return;
}
static void PrintArgumentHelp(const OptionList& optList)
{
std::vector<std::string> cmdCol; // command column
const int indent = 4;
size_t maxCmdLen;
size_t curOpt;
cmdCol.resize(optList.size());
maxCmdLen = 0;
for (curOpt = 0; curOpt < optList.size(); curOpt ++)
{
const OptionItem& oItm = optList[curOpt];
std::string& cmdStr = cmdCol[curOpt];
cmdStr = std::string("-") + oItm.shortOpt + ", --" + oItm.longOpt;
if ((oItm.flags & 0x01) && oItm.paramName != NULL)
cmdStr = cmdStr + " " + oItm.paramName;
if (maxCmdLen < cmdStr.length())
maxCmdLen = cmdStr.length();
}
maxCmdLen += 2; // add 2 characters of padding
maxCmdLen = (maxCmdLen + 3) & ~3; // round up to 4
for (curOpt = 0; curOpt < optList.size(); curOpt ++)
{
const OptionItem& oItm = optList[curOpt];
int padding = static_cast<int>(maxCmdLen - cmdCol[curOpt].length());
printf("%*s%s%*s%s\n", indent, "", cmdCol[curOpt].c_str(), padding, " ", oItm.helpText);
}
return;
}
static int ParseArguments(int argc, char* argv[], const OptionList& optList, Configuration& argCfg)
{
std::string sOpts;
std::vector<struct option> lOpts;
sOpts = GenerateOptData(optList, &lOpts);
optind = 1;
while(true)
{
int retVal = getopt_long(argc, argv, sOpts.c_str(), &lOpts[0], NULL);
if (retVal == -1)
break; // finished argument parsing
else if (retVal == '?')
return -1; // getopt already prints a message by default, so just return
switch(retVal)
{
case 'v': // version
PrintVersion();
return 0;
case 'h': // help
PrintVersion();
printf("Usage: %s [options] file1.vgm [file2.vgz] [...]\n", argv[0]);
PrintArgumentHelp(optList);
return 0;
case 'w': // dump-wav
argCfg.AddEntry("General", "LogSound", "1");
break;
case 'd': // output-device
argCfg.AddEntry("General", "OutputDevice", optarg);
break;
case 'c': // configuration setting
{
std::string optstr = optarg;
char* sect = &optstr[0];
char* key = strchr(sect, '.');
if (key == NULL)
break;
*key = '\0'; key ++;
char* val = strchr(key, '=');
if (val == NULL)
break;
*val = '\0'; val ++;
// reuse INI handler, so that the MuteMask values are put into the correct section
IniValHandler(&argCfg, sect, key, val);
}
break;
}
}
return optind;
}