aboutsummaryrefslogtreecommitdiff
path: root/src/lib/hd24utils.cpp
blob: 6efb3a7e1421e7d4761b1b2efb004fd52e6a9d97 (plain)
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
#define UTILDEBUG 0
#ifdef DARWIN
#	define creat64 creat
#	define open64 open
#	define lseek64 lseek
#	define pread64 pread
#	define pwrite64 pwrite
#endif

#if defined(LINUX) || defined(DARWIN)
#	define PRINTAPP "lp"
#endif

#ifdef WINDOWS
#	include <windows.h>
#	include <shellapi.h>
#	define PRINTAPP "print"
#	define popen _popen
#	define pclose _pclose
#else
#	include <unistd.h>
#endif

#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <math.h>
#include <hd24devicenamegenerator.h>
#include <FL/FLTKstuff.H>
#include <FL/Fl_Preferences.H>
#include <FL/filename.H>
#include "convertlib.h"
#include "hd24utils.h"
#include "memutils.h"
#define _LARGE_FILES
#define LARGE_FILES
#define LARGEFILE64_SOURCE
#define _FILE_OFFSET_BITS		64
#define FILE_OFFSET_BITS		64
#define SECTORSIZE			512
#define FSINFO_VERSION_MAJOR 		0x8
#define FSINFO_VERSION_MINOR 		0x9
#define FSINFO_BLOCKSIZE_IN_SECTORS	0x10
#define FSINFO_AUDIOBLOCKS_PER_CLUSTER	0x14
#define FSINFO_STARTSECTOR_FAT		0x38
#define FSINFO_NUMSECTORS_FAT		0x3c
#define FSINFO_CLUSTERS_ON_DISK		0x44
#define FSINFO_MAXPROJECTS		0x50
#define FSINFO_MAXSONGSPERPROJECT	0x54
#define FSINFO_DATAAREA 		0x7c
#define DRIVEINFO_VOLUME 		0x1b8
#define DRIVEINFO_PROJECTCOUNT		0x0c
#define DRIVEINFO_LASTPROJ		0x10
#define DRIVEINFO_PROJECTLIST		0x20

void hd24utils::gencatalog_showsongs(hd24project* currentproj,string* strcatalog)
{
	if (currentproj==NULL) {
		return;
	}
	if (strcatalog==NULL) {
		return;
	}
	int numsongs=currentproj->songcount();
	*strcatalog+="     ======================================================================\n";
	if (numsongs==0) {
		*strcatalog+="      There are no songs in this project.\n";
		return;
	}
        hd24song* currsong=NULL;
	for (int i=1; i<=numsongs; i++) {
		currsong=currentproj->getsong(i);
		if (currsong==NULL) continue;

		*strcatalog+="     ";
		*strcatalog+="  ";
		if (i<10) {
			*strcatalog+=" ";
		}
		string* songnum=Convert::int2str(i);
		*strcatalog+=*songnum;
		*strcatalog+=": ";
		delete songnum;
	
	        string* currsname=currsong->songname();
		string* pad=Convert::padright(*currsname,35," ");
	        delete(currsname);
		*strcatalog+=*pad;
		delete pad;
		string* dur=currsong->display_duration();
		*strcatalog+=*dur;
		delete dur;
		*strcatalog+= ", " ;

		string* chans=Convert::int2str(currsong->logical_channels());
		string* chans2=Convert::padleft(*chans,2," ");
		*strcatalog+=*chans;
		delete chans;
		delete chans2;
		*strcatalog+="ch. ";

		string* samrate=Convert::int2str(currsong->samplerate());
		*strcatalog+=*samrate;
		delete samrate;
		*strcatalog+=" Hz";


		if (currsong->iswriteprotected()) 
		{
			*strcatalog+="*";
		}

		*strcatalog+="\n";
		
                delete currsong;
                currsong=NULL;
	}
	return;
}

void hd24utils::gencatalog_showprojects(hd24fs* currenthd24,string* strcatalog)
{
	int numprojs=currenthd24->projectcount();
	hd24project* currproj=NULL;
	for (int i=1; i<=numprojs; i++) 
	{
		currproj=currenthd24->getproject(i);

		*strcatalog+="     ======================================================================\n";
		*strcatalog+="     Project ";
		string* projnum=Convert::int2str(i);
		*strcatalog+=*projnum;
		delete projnum;
		*strcatalog+=": ";

	        string* currpname=currproj->projectname();	        
		*strcatalog+= *currpname;
	        delete(currpname);

		*strcatalog+="\n"; // << endl;
		gencatalog_showsongs (currproj,strcatalog); //to_out);
		delete(currproj);
	}
	
}

int hd24utils::gencatalog(hd24fs* currenthd24,string* strcatalog) 
{

	time_t currenttime;
	struct tm timestamp;
	char timebuf[80];
	time(&currenttime);
	timestamp = *localtime(&currenttime);
	strftime(timebuf,sizeof(timebuf),"%a %Y-%m-%d %H:%M:%S %Z", &timestamp);
	*strcatalog+= "     Catalog timestamp      : ";
	*strcatalog+= timebuf ;
	*strcatalog+="\n";

	*strcatalog+="     Volume name            : ";
	string* volname=currenthd24->volumename();
	*strcatalog+=*volname;
	delete volname;
	*strcatalog+="\n";

	*strcatalog+="     Number of projects     : ";
	string* pcount=Convert::int2str(currenthd24->projectcount());
	*strcatalog+=*pcount;
	delete pcount;

	*strcatalog+="\n";
	gencatalog_showprojects(currenthd24,strcatalog);
	return 0;
}

string* hd24utils::savecatalog(hd24fs* currenthd24,string* filename)
{
	string* error=new string("");

	// gencatalog
	string* catalog=new string("");

	if (hd24utils::gencatalog(currenthd24,catalog)!=0) 
	{
		*error+="Error generating catalog.";
		return error;
	}
	fstream to_out(filename->c_str(),ios::out);
	if (to_out==NULL) 
	{
		*error+="Cannot write catalog.";
		return error;
	}	
	to_out << *catalog ;

	to_out.flush();
	to_out.close();
	return NULL;
}

string* hd24utils::printcatalog(hd24fs* currenthd24)
{

	string* error=new string("");
	string catname="_hd24cat.txt";	


	// gencatalog
	string* catalog=new string("");

	if (hd24utils::gencatalog(currenthd24,catalog)!=0) 
	{
		*error+="Error generating catalog.";
		return error;
	}
	fstream to_out(catname.c_str(),ios::out);
	if (to_out==NULL) 
	{
		*error+="Cannot write catalog.";
		return error;
	}	
	*catalog += "\f\n"; // form feed
	to_out << *catalog ;

	to_out.flush();
	to_out.close();

#ifdef WINDOWS
	SHELLEXECUTEINFO ShExecInfo = {0};
	ShExecInfo.cbSize = sizeof (SHELLEXECUTEINFO);
	ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS; //SEE_MASK_INVOKEIDLIST;
	ShExecInfo.hwnd = NULL;
	ShExecInfo.lpVerb="print";
	ShExecInfo.lpFile=catname.c_str();
	ShExecInfo.lpParameters = "";
	ShExecInfo.lpDirectory=NULL;
	ShExecInfo.nShow = SW_HIDE;
	ShExecInfo.hInstApp = NULL;
	ShellExecuteEx(&ShExecInfo);
	WaitForSingleObject(ShExecInfo.hProcess,INFINITE);
	unlink (catname.c_str());
#else	
	char s[1024];
	string* catcmd = new string (PRINTAPP);
	*catcmd += " ";
       	*catcmd += catname;
	*catcmd += " 2>&1";
	FILE *fp = popen(catcmd->c_str() , "r");
	while (fgets(s, sizeof(s)-1, fp)) 
	{
		*error += s; 
	}
	pclose(fp);
	unlink (catname.c_str());
#endif
	return error;
}


void hd24utils::interlacetobuffer(unsigned char* sourcebuf,unsigned char* targetbuf,
		__uint32 totbytes,__uint32 bytespersam,__uint32 trackwithingroup,__uint32 trackspergroup)
{
	__uint32 samplenum;
	__uint32 totsams=totbytes/bytespersam;
	__uint32 trackoff=(trackwithingroup*bytespersam);
	__uint32 q=0;
	// unroll loop for bytespersam=1,2,3
	switch (bytespersam) 
	{
		case 3:
		for (samplenum=0;samplenum<totsams;samplenum++)
		{
			__uint32 samoff=(samplenum*bytespersam);
			q=trackspergroup*samoff+trackoff;
			targetbuf[q++]=sourcebuf[samoff];
	                targetbuf[q++]=sourcebuf[samoff+1];
	                targetbuf[q++]=sourcebuf[samoff+2];
		}		
		break;
		case 1:
			for (samplenum=0;samplenum<totsams;samplenum++)
			{
				__uint32 samoff=(samplenum*bytespersam);
				q=trackspergroup*samoff+trackoff;
				targetbuf[q]=sourcebuf[samoff];
			}	
			break;
		case 2:
			for (samplenum=0;samplenum<totsams;samplenum++)
			{
				__uint32 samoff=(samplenum*bytespersam);
				q=trackspergroup*samoff+trackoff;
				targetbuf[q++]=sourcebuf[samoff];
	                        targetbuf[q++]=sourcebuf[samoff+1];
			}		
			break;
		default:
			for (samplenum=0;samplenum<totsams;samplenum++)
			{
				__uint32 samoff=(samplenum*bytespersam);
				q=trackspergroup*samoff;
				for (__uint32 j=0; j<bytespersam; j++) {
				   targetbuf[q+j+trackoff]=sourcebuf[samoff+j];
				}
			}
			break;
	}
}

bool hd24utils::dirExists(const char * pszDirName)
{
#ifdef WIN32
    unsigned int dwAttrs;
    if (!(pszDirName))
    {
      //setupLog(NULL, "DirExists failed: passed in NULL parameter for directory");
      return (1==0);
    }
    dwAttrs = GetFileAttributes(pszDirName);
    if ((dwAttrs != 0xFFFFFFFF) && (dwAttrs & FILE_ATTRIBUTE_DIRECTORY))
    {
      return (1==1);
    }
    return (1==0);
#else
    struct stat fi;

    if (stat (pszDirName, &fi) == -1 || !S_ISDIR(fi.st_mode))
    {
      return (1==0);
    }
    else
    {
      return (1==1);
    }
#endif
}
int hd24utils::savedrivesectors(hd24fs* currenthd24,string* outputfilename,unsigned long firstsector,unsigned long endsector,char* message,int* cancel) {
	unsigned long i;
#define MULTISECTOR 100	
	unsigned char bootblock[(MULTISECTOR+1)*512]; // 1 sector spare
	memset(bootblock,0,MULTISECTOR*512);
#if defined(LINUX) || defined(DARWIN)
#if (UTILDEBUG==1)
	cout << "creat64" << endl;
#endif
	FSHANDLE handle=creat64(outputfilename->c_str(),O_WRONLY);
#endif
#ifdef WINDOWS
	FSHANDLE handle=CreateFile(outputfilename->c_str(),GENERIC_WRITE|GENERIC_READ,
              FILE_SHARE_READ|FILE_SHARE_WRITE,
              NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
	if (hd24fs::isinvalidhandle(handle)) {
		handle=CreateFile(outputfilename->c_str(),GENERIC_WRITE|GENERIC_READ,
	      FILE_SHARE_READ|FILE_SHARE_WRITE,
	      NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
	}
		
	#endif
	if (hd24fs::isinvalidhandle(handle)) {
	//	cout << "Cannot open file "<<filename <<" for writing. Access denied?" << endl;
		return 1;		
	}
	int q=0;
	for (i=firstsector;i<=endsector;i++) {
		q++;
		int numsectors=1;
		if ((endsector-i) >=MULTISECTOR) {
			numsectors=MULTISECTOR;
		}
		if (currenthd24!=NULL) {
			currenthd24->readsector_noheader(currenthd24,i,bootblock); // raw reading 
		}
#if defined(LINUX) || defined(DARWIN)
		__uint64 targetoff=i;
		targetoff-=firstsector;
		targetoff*=512;
		ssize_t byteswritten=0;
		if (currenthd24!=NULL) {
			byteswritten=pwrite64(handle,bootblock,512,targetoff);
		} else {
			byteswritten=pwrite64(handle,bootblock,512*numsectors,targetoff);
			i+=(numsectors-1);
		}
#endif
#ifdef WINDOWS
		//DWORD dummy;
		//long bytes=0;
		__uint64 targetoff=i;
		targetoff-=firstsector;
		__uint64 byteswritten=0;
		if (currenthd24!=NULL) {
			byteswritten=currenthd24->writesectors(handle,targetoff,bootblock,1);
		} else {
			byteswritten=currenthd24->writesectors(handle,targetoff,bootblock,numsectors);
			i+=(numsectors-1);
		}
#endif
		if (byteswritten==0) {
#if defined(LINUX) || defined(DARWIN)
			close (handle);
#endif
#ifdef WINDOWS
			CloseHandle(handle);
#endif
			return 1;
		}
		if (message!=NULL) {
			if (q%1000==0) {
				sprintf(message,"Saving sector %ld of %ld",i,(endsector+1));
			
				// cout << i << endl;	
				Fl::wait(0);
			}
		}
	}
#if defined(LINUX) || defined(DARWIN)
	close (handle);
	chmod(outputfilename->c_str(),0664);
#endif
#ifdef WINDOWS
	CloseHandle(handle);
#endif

	return 0;
}

int hd24utils::savedriveimage(hd24fs* currenthd24,string* imagefilename,char* message,int* cancel) {
	unsigned long firstsector=0;
	unsigned long endsector=currenthd24->getlastsectornum();
	return savedrivesectors(currenthd24,imagefilename,firstsector,endsector,message,cancel);
}

int hd24utils::newdriveimage(string* imagefilename,__uint32 endsector,char* message,int* cancel) {
	if (endsector<1353964)
	{
		// requested drive size is less than possible minimum size
		return -1;
	}
	
	unsigned long firstsector=0;
#if (UTILDEBUG==1)
cout << "about to save drive sectors" <<endl;
#endif
	int result=savedrivesectors(NULL,imagefilename,firstsector,endsector,message,cancel);
	if (result!=0)
	{
		return result;
	}
#if (UTILDEBUG==1)
cout << "saved drive sectors, creating new fs object to format" <<endl;
#endif
	hd24fs* newfs=new hd24fs((const char*)NULL,hd24fs::MODE_RDWR,imagefilename,true);
#if (UTILDEBUG==1)
cout << "write enabling fs" <<endl;
#endif
	newfs->write_enable();
#if (UTILDEBUG==1)
cout << "quickformatting fs" <<endl;
#endif
	newfs->quickformat(message);
#if (UTILDEBUG==1)
	cout << "format result=" << *message << endl;
cout << "deleting format fs object" <<endl;
#endif
	delete newfs;
#if (UTILDEBUG==1)
cout << "destructed fs object" <<endl;
#endif	
	return 0;
}

void hd24utils::dumpsector(const char* buffer)
{
	for (int i=0;i<512;i+=16) {
		string* dummy=Convert::int32tohex(i);
	       	cout << *dummy	<< "  ";
		delete dummy; dummy=NULL;
		for (int j=0;j<16;j++) {
			string* dummy= Convert::byte2hex(buffer[i+j]);
			cout << *dummy;
			if (j==7) {
				cout << "-" ;
			} else {
				cout << " " ;
			}
			delete dummy; dummy=NULL;
		}
		cout << " ";
		for (int j=0;j<16;j++) {
			cout << Convert::safebyte(buffer[i+j]);
		}
		cout << "" << endl;
	}
}
int hd24utils::saveheader(hd24fs* currenthd24,string* headerfilename) {
	return savedrivesectors(currenthd24,headerfilename,0,0x700,NULL,NULL);
	// TODO: 0x700 sectors is arbitrary. First song entry is at 0x77,
	// total of 99*99 songs of 7 sectors each puts actual required length 
	// at 0x10c76. However, this has served fine so far.

}

void hd24utils::findfile(const char* rawname,const char* path,char* result) 
{
	string* strpath=new string(path);
#ifdef WINDOWS
	string* pathsep=new string(";");
#else
	string* pathsep=new string(":");
#endif
	int last=0;	
	string* exename;
	string* exepath;	
#if (UTILDEBUG==1)
	cout << "search path for exe " << endl;
#endif
	while (last==0)
	{
		unsigned int idx=strpath->find(pathsep->c_str());
		if (idx==string::npos) {
			last=1;
			exepath=new string(strpath->c_str());
			exename=new string(strpath->c_str());
			*strpath="";
		} else {
			exepath=new string(strpath->substr(0,idx));
			exename=new string(strpath->substr(0,idx));
			*strpath=strpath->substr(idx+1);
		}
#if (UTILDEBUG==1)
		cout << "exepath= " << *exepath << endl;
#endif
		if (exepath->substr(exepath->length()-1,1)!=PATHSLASH) {
		     *exepath+=PATHSLASH;
		}	
		if (exename->substr(exename->length()-1,1)!=PATHSLASH) {
		     *exename+=PATHSLASH;
		}	

		*exename+=rawname;
#if (UTILDEBUG==1)
		cout << "test if file " << exename->c_str() << " exists" << endl;
#endif
		if (hd24utils::fileExists(exename->c_str())) {
			strncpy(result,exepath->c_str(),2048);
			if (exename!=NULL) {
				delete exename;
				exename=NULL;
			}
			if (exepath!=NULL) {
				delete exepath;
				exepath=NULL;
			}
			if (strpath!=NULL) {		
				delete strpath;
				strpath=NULL;
			}
			if (pathsep!=NULL) {
				delete pathsep;
				pathsep=NULL;
			}
			return ;
		}
		if (exename!=NULL) {
			delete exename;
			exename=NULL;
		}
		if (exepath!=NULL) {
			delete exepath;
			exepath=NULL;
		}		
	}	

	if (strpath!=NULL) {		
		delete strpath;
		strpath=NULL;
	}
	if (pathsep!=NULL) {
		delete pathsep;
		pathsep=NULL;
	}

	result[0]=(char)0;
	return;
}

bool hd24utils::fileExists(const char* strFilename) {
	struct stat stFileInfo;
 	int intStat;

	// Attempt to get the file attributes
	intStat = stat(strFilename,&stFileInfo);
	if(intStat == 0) 
	{
		// We were able to get the file attributes
		// so the file obviously exists.
		return true;
	}
	// We were not able to get the file attributes.
	// This may mean that we don't have permission to
	// access the folder which contains this file. If you
	// need to do that level of checking, lookup the
	// return values of stat which will give you
	// more details on why stat failed.
	return false;
}

string* hd24utils::getlastdir(string which)
{
	string* whichdir;
	char buffer[FL_PATH_MAX];

	Fl_Preferences* userprefs=new Fl_Preferences(Fl_Preferences::USER, "HD24","HD24connect" );
	/* Attempt to find last used project dir */
	if (userprefs->entryExists(which.c_str())) {
		userprefs->get(which.c_str(),buffer,".",FL_PATH_MAX);
		whichdir=new string(buffer);
	} else {
	        whichdir=new string(".");
	}
	delete userprefs;
	return whichdir;
}

void hd24utils::setlastdir(string which,const char* newdir)
{
	Fl_Preferences* userprefs=new Fl_Preferences(Fl_Preferences::USER, "HD24","HD24connect" );
	userprefs->set(which.c_str(),newdir);
	// cout << "just set " << which << " to " << newdir << endl;
	delete userprefs;
}