summaryrefslogtreecommitdiff
path: root/src/input/vcd/libcdio/_cdio_win32.c
blob: 418beb86c3f0bb566154a1fe1ce700c0db52ebb5 (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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
/*
    $Id: _cdio_win32.c,v 1.1 2003/10/13 11:47:11 f1rmb Exp $

    Copyright (C) 2003 Rocky Bernstein <rocky@panix.com>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

/* This file contains Win32-specific code and implements low-level 
   control of the CD drive. Inspired by vlc's cdrom.h code 
*/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

static const char _rcsid[] = "$Id: _cdio_win32.c,v 1.1 2003/10/13 11:47:11 f1rmb Exp $";

#include <cdio/cdio.h>
#include <cdio/sector.h>
#include <cdio/util.h>
#include "cdio_assert.h"
#include "cdio_private.h"
#include "scsi_mmc.h"

/* LBA = msf.frame + 75 * ( msf.second - 2 + 60 * msf.minute ) */
#define MSF_TO_LBA2(min, sec, frame) ((int)frame + 75 * (sec -2 + 60 * min))

#include <string.h>

#ifdef HAVE_WIN32_CDROM

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>

#include <windows.h>
#include <winioctl.h>

#include <sys/stat.h>
#include <sys/types.h>

/* Win32 DeviceIoControl specifics */
#ifndef MAXIMUM_NUMBER_TRACKS
#    define MAXIMUM_NUMBER_TRACKS 100
#endif
typedef struct _TRACK_DATA {
    UCHAR Reserved;
    UCHAR Control : 4;
    UCHAR Adr : 4;
    UCHAR TrackNumber;
    UCHAR Reserved1;
    UCHAR Address[4];
} TRACK_DATA, *PTRACK_DATA;
typedef struct _CDROM_TOC {
    UCHAR Length[2];
    UCHAR FirstTrack;
    UCHAR LastTrack;
    TRACK_DATA TrackData[MAXIMUM_NUMBER_TRACKS];
} CDROM_TOC, *PCDROM_TOC;
typedef enum _TRACK_MODE_TYPE {
    YellowMode2,
    XAForm2,
    CDDA
} TRACK_MODE_TYPE, *PTRACK_MODE_TYPE;
typedef struct __RAW_READ_INFO {
    LARGE_INTEGER DiskOffset;
    ULONG SectorCount;
    TRACK_MODE_TYPE TrackMode;
} RAW_READ_INFO, *PRAW_READ_INFO;

#ifndef IOCTL_CDROM_BASE
#    define IOCTL_CDROM_BASE FILE_DEVICE_CD_ROM
#endif
#ifndef IOCTL_CDROM_READ_TOC
#    define IOCTL_CDROM_READ_TOC CTL_CODE(IOCTL_CDROM_BASE, 0x0000, \
                                          METHOD_BUFFERED, FILE_READ_ACCESS)
#endif
#ifndef IOCTL_CDROM_RAW_READ
#define IOCTL_CDROM_RAW_READ CTL_CODE(IOCTL_CDROM_BASE, 0x000F, \
                                      METHOD_OUT_DIRECT, FILE_READ_ACCESS)
#endif

/* Win32 aspi specific */
#define WIN_NT               ( GetVersion() < 0x80000000 )
#define ASPI_HAID           0
#define ASPI_TARGET         0
#define DTYPE_CDROM         0x05

#define SENSE_LEN           0x0E
#define SC_GET_DEV_TYPE     0x01
#define SC_EXEC_SCSI_CMD    0x02
#define SC_GET_DISK_INFO    0x06
#define SS_COMP             0x01
#define SS_PENDING          0x00
#define SS_NO_ADAPTERS      0xE8
#define SRB_DIR_IN          0x08
#define SRB_DIR_OUT         0x10
#define SRB_EVENT_NOTIFY    0x40

#define SECTOR_TYPE_MODE2 0x14
#define READ_CD_USERDATA_MODE2 0x10

#define READ_TOC 0x43
#define READ_TOC_FORMAT_TOC 0x0

#pragma pack(1)

struct SRB_GetDiskInfo
{
    unsigned char   SRB_Cmd;
    unsigned char   SRB_Status;
    unsigned char   SRB_HaId;
    unsigned char   SRB_Flags;
    unsigned long   SRB_Hdr_Rsvd;
    unsigned char   SRB_Target;
    unsigned char   SRB_Lun;
    unsigned char   SRB_DriveFlags;
    unsigned char   SRB_Int13HDriveInfo;
    unsigned char   SRB_Heads;
    unsigned char   SRB_Sectors;
    unsigned char   SRB_Rsvd1[22];
};

struct SRB_GDEVBlock
{
    unsigned char SRB_Cmd;
    unsigned char SRB_Status;
    unsigned char SRB_HaId;
    unsigned char SRB_Flags;
    unsigned long SRB_Hdr_Rsvd;
    unsigned char SRB_Target;
    unsigned char SRB_Lun;
    unsigned char SRB_DeviceType;
    unsigned char SRB_Rsvd1;
};

struct SRB_ExecSCSICmd
{
    unsigned char   SRB_Cmd;
    unsigned char   SRB_Status;
    unsigned char   SRB_HaId;
    unsigned char   SRB_Flags;
    unsigned long   SRB_Hdr_Rsvd;
    unsigned char   SRB_Target;
    unsigned char   SRB_Lun;
    unsigned short  SRB_Rsvd1;
    unsigned long   SRB_BufLen;
    unsigned char   *SRB_BufPointer;
    unsigned char   SRB_SenseLen;
    unsigned char   SRB_CDBLen;
    unsigned char   SRB_HaStat;
    unsigned char   SRB_TargStat;
    unsigned long   *SRB_PostProc;
    unsigned char   SRB_Rsvd2[20];
    unsigned char   CDBByte[16];
    unsigned char   SenseArea[SENSE_LEN+2];
};

#pragma pack()

typedef struct {
  lsn_t          start_lsn;
} track_info_t;

typedef struct {
  /* Things common to all drivers like this. 
     This must be first. */
  generic_img_private_t gen; 

  HANDLE h_device_handle; /* device descriptor */
  long  hASPI;
  short i_sid;
  long  (*lpSendCommand)( void* );

  /* Track information */
  bool toc_init;                 /* if true, info below is valid. */
  track_info_t  tocent[100];     /* entry info for each track */
  track_t       total_tracks;    /* number of tracks in image */
  track_t       first_track_num; /* track number of first track */

} _img_private_t;

/* General ioctl() CD-ROM command function */
static bool 
_cdio_mciSendCommand(int id, UINT msg, DWORD flags, void *arg)
{
  MCIERROR mci_error;
  
  mci_error = mciSendCommand(id, msg, flags, (DWORD)arg);
  if ( mci_error ) {
    char error[256];
    
    mciGetErrorString(mci_error, error, 256);
    cdio_error("mciSendCommand() error: %s", error);
  }
  return(mci_error == 0);
}

static const char *
cdio_is_cdrom(const char drive_letter) {
  static char psz_win32_drive[7];
  static char root_path_name[8];
  _img_private_t obj;

  /* Initializations */
  obj.h_device_handle = NULL;
  obj.i_sid = 0;
  obj.hASPI = 0;
  obj.lpSendCommand = 0;
  
  if ( WIN_NT ) {
    sprintf( psz_win32_drive, "\\\\.\\%c:", drive_letter );
    sprintf( root_path_name, "\\\\.\\%c:\\", drive_letter );
    
    obj.h_device_handle = CreateFile( psz_win32_drive, GENERIC_READ,
				      FILE_SHARE_READ | FILE_SHARE_WRITE,
				      NULL, OPEN_EXISTING,
				      FILE_FLAG_NO_BUFFERING |
				      FILE_FLAG_RANDOM_ACCESS, NULL );
    if (obj.h_device_handle != NULL 
	&& (DRIVE_CDROM == GetDriveType(root_path_name))) {
      CloseHandle(obj.h_device_handle);
      return strdup(psz_win32_drive);
    } else {
      CloseHandle(obj.h_device_handle);
      return NULL;
    }
  } else {
    HMODULE hASPI = NULL;
    long (*lpGetSupport)( void ) = NULL;
    long (*lpSendCommand)( void* ) = NULL;
    DWORD dwSupportInfo;
    int j, i_hostadapters;
    char c_drive;
    
    hASPI = LoadLibrary( "wnaspi32.dll" );
    if( hASPI != NULL ) {
      (FARPROC) lpGetSupport = GetProcAddress( hASPI,
					       "GetASPI32SupportInfo" );
      (FARPROC) lpSendCommand = GetProcAddress( hASPI,
						"SendASPI32Command" );
    }
    
    if( hASPI == NULL || lpGetSupport == NULL || lpSendCommand == NULL ) {
      cdio_debug("Unable to load ASPI or get ASPI function pointers");
      if( hASPI ) FreeLibrary( hASPI );
      return NULL;
    }
    
    /* ASPI support seems to be there */
    
    dwSupportInfo = lpGetSupport();
    
    if( HIBYTE( LOWORD ( dwSupportInfo ) ) == SS_NO_ADAPTERS ) {
      cdio_debug("no host adapters found (ASPI)");
      FreeLibrary( hASPI );
      return NULL;
    }
    
    if( HIBYTE( LOWORD ( dwSupportInfo ) ) != SS_COMP ) {
      cdio_debug("Unable to initalize ASPI layer");
      FreeLibrary( hASPI );
      return NULL;
    }
    
    i_hostadapters = LOBYTE( LOWORD( dwSupportInfo ) );
    if( i_hostadapters == 0 ) {
      FreeLibrary( hASPI );
      return NULL;
    }
    
    c_drive = toupper(drive_letter) - 'A';
    
    for( j = 0; j < 15; j++ ) {
      struct SRB_GetDiskInfo srbDiskInfo;
      
      srbDiskInfo.SRB_Cmd         = SC_GET_DISK_INFO;
      srbDiskInfo.SRB_HaId        = 0;
      srbDiskInfo.SRB_Flags       = 0;
      srbDiskInfo.SRB_Hdr_Rsvd    = 0;
      srbDiskInfo.SRB_Target      = j;
      srbDiskInfo.SRB_Lun         = 0;
      
      lpSendCommand( (void*) &srbDiskInfo );
      
      if( (srbDiskInfo.SRB_Status == SS_COMP) &&
	  (srbDiskInfo.SRB_Int13HDriveInfo == c_drive) ) {
	/* Make sure this is a cdrom device */
	struct SRB_GDEVBlock   srbGDEVBlock;
	
	memset( &srbGDEVBlock, 0, sizeof(struct SRB_GDEVBlock) );
	srbGDEVBlock.SRB_Cmd    = SC_GET_DEV_TYPE;
	srbGDEVBlock.SRB_HaId   = 0;
	srbGDEVBlock.SRB_Target = j;
	
	lpSendCommand( (void*) &srbGDEVBlock );
	
	if( ( srbGDEVBlock.SRB_Status == SS_COMP ) &&
	    ( srbGDEVBlock.SRB_DeviceType == DTYPE_CDROM ) ) {
	  sprintf( psz_win32_drive, "%c:", drive_letter );
	  FreeLibrary( hASPI );
	  return(psz_win32_drive);
	}
      }
    }
    FreeLibrary( hASPI );
  }
  return NULL;

}

/*!
  Initialize CD device.
 */
static bool
_cdio_init_win32 (void *user_data)
{
  _img_private_t *_obj = user_data;
  if (_obj->gen.init) {
    cdio_error ("init called more than once");
    return false;
  }
  
  _obj->gen.init = true;
  _obj->toc_init = false;


  /* Initializations */
  _obj->h_device_handle = NULL;
  _obj->i_sid = 0;
  _obj->hASPI = 0;
  _obj->lpSendCommand = 0;
  
  if ( WIN_NT ) {
    char psz_win32_drive[7];
    unsigned int len=strlen(_obj->gen.source_name);
    
    cdio_debug("using winNT/2K/XP ioctl layer");

    if (cdio_is_device_win32(_obj->gen.source_name)) {
      sprintf( psz_win32_drive, "\\\\.\\%c:", _obj->gen.source_name[len-2] );
    
      _obj->h_device_handle = CreateFile( psz_win32_drive, GENERIC_READ,
					  FILE_SHARE_READ | FILE_SHARE_WRITE,
					  NULL, OPEN_EXISTING,
					  FILE_FLAG_NO_BUFFERING |
					  FILE_FLAG_RANDOM_ACCESS, NULL );
      return (_obj->h_device_handle == NULL) ? false : true;
    } else
      return false;
  } else {
    HMODULE hASPI = NULL;
    long (*lpGetSupport)( void ) = NULL;
    long (*lpSendCommand)( void* ) = NULL;
    DWORD dwSupportInfo;
    int i, j, i_hostadapters;
    char c_drive = _obj->gen.source_name[0];
    
    hASPI = LoadLibrary( "wnaspi32.dll" );
    if( hASPI != NULL ) {
      (FARPROC) lpGetSupport = GetProcAddress( hASPI,
					       "GetASPI32SupportInfo" );
      (FARPROC) lpSendCommand = GetProcAddress( hASPI,
						"SendASPI32Command" );
    }
    
    if( hASPI == NULL || lpGetSupport == NULL || lpSendCommand == NULL ) {
      cdio_debug("Unable to load ASPI or get ASPI function pointers");
      if( hASPI ) FreeLibrary( hASPI );
      return false;
    }
    
    /* ASPI support seems to be there */
    
    dwSupportInfo = lpGetSupport();
    
    if( HIBYTE( LOWORD ( dwSupportInfo ) ) == SS_NO_ADAPTERS ) {
      cdio_debug("no host adapters found (ASPI)");
      FreeLibrary( hASPI );
      return -1;
    }
    
    if( HIBYTE( LOWORD ( dwSupportInfo ) ) != SS_COMP ) {
      cdio_debug("unable to initalize ASPI layer");
      FreeLibrary( hASPI );
      return -1;
    }
    
    i_hostadapters = LOBYTE( LOWORD( dwSupportInfo ) );
    if( i_hostadapters == 0 ) {
      FreeLibrary( hASPI );
      return -1;
    }
    
    c_drive = toupper(c_drive) - 'A';
    
    for( i = 0; i < i_hostadapters; i++ ) {
      for( j = 0; j < 15; j++ ) {
	struct SRB_GetDiskInfo srbDiskInfo;
	  
	srbDiskInfo.SRB_Cmd         = SC_GET_DISK_INFO;
	srbDiskInfo.SRB_HaId        = i;
	srbDiskInfo.SRB_Flags       = 0;
	srbDiskInfo.SRB_Hdr_Rsvd    = 0;
	srbDiskInfo.SRB_Target      = j;
	srbDiskInfo.SRB_Lun         = 0;
	
	lpSendCommand( (void*) &srbDiskInfo );
	
	if( (srbDiskInfo.SRB_Status == SS_COMP) &&
	    (srbDiskInfo.SRB_Int13HDriveInfo == c_drive) ) {
	  /* Make sure this is a cdrom device */
	  struct SRB_GDEVBlock   srbGDEVBlock;
	  
	  memset( &srbGDEVBlock, 0, sizeof(struct SRB_GDEVBlock) );
	  srbGDEVBlock.SRB_Cmd    = SC_GET_DEV_TYPE;
	  srbGDEVBlock.SRB_HaId   = i;
	  srbGDEVBlock.SRB_Target = j;
	  
	  lpSendCommand( (void*) &srbGDEVBlock );
	  
	  if( ( srbGDEVBlock.SRB_Status == SS_COMP ) &&
	      ( srbGDEVBlock.SRB_DeviceType == DTYPE_CDROM ) ) {
	    _obj->i_sid = MAKEWORD( i, j );
	    _obj->hASPI = (long)hASPI;
	    _obj->lpSendCommand = lpSendCommand;
	    cdio_debug("Using ASPI layer");
	    
	    return true;
	  } else {
	    FreeLibrary( hASPI );
	    cdio_debug( "%c: is not a CD-ROM drive",
			_obj->gen.source_name[0] );
	    return false;
	  }
	}
      }
    }
    
    FreeLibrary( hASPI );
    cdio_debug( "Unable to get HaId and target (ASPI)" );
    
  }
  
  return false;
}

/*!
  Release and free resources associated with cd. 
 */
static void
_cdio_win32_free (void *user_data)
{
  _img_private_t *_obj = user_data;

  if (NULL == _obj) return;
  free (_obj->gen.source_name);

  if( _obj->h_device_handle )
    CloseHandle( _obj->h_device_handle );
  if( _obj->hASPI )
    FreeLibrary( (HMODULE)_obj->hASPI );

  free (_obj);
}

/*!
   Reads a single mode2 sector from cd device into data starting from lsn.
   Returns 0 if no error. 
 */
static int
_cdio_mmc_read_sectors (void *user_data, void *data, lsn_t lsn, 
			int sector_type, unsigned int nblocks)
{
  _img_private_t *_obj = user_data;
  unsigned char buf[CDIO_CD_FRAMESIZE_RAW] = { 0, };

  if( _obj->hASPI ) {
    HANDLE hEvent;
    struct SRB_ExecSCSICmd ssc;
    
    /* Create the transfer completion event */
    hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
    if( hEvent == NULL ) {
      return 1;
    }

    /* Data selection */

    memset( &ssc, 0, sizeof( ssc ) );
    
    ssc.SRB_Cmd         = SC_EXEC_SCSI_CMD;
    ssc.SRB_Flags       = SRB_DIR_IN | SRB_EVENT_NOTIFY;
    ssc.SRB_HaId        = LOBYTE( _obj->i_sid );
    ssc.SRB_Target      = HIBYTE( _obj->i_sid );
    ssc.SRB_SenseLen    = SENSE_LEN;
    
    ssc.SRB_PostProc = (LPVOID) hEvent;
    ssc.SRB_CDBLen      = 12;
    
    /* Operation code */
    ssc.CDBByte[ 0 ] = CDIO_MMC_GPCMD_READ_CD;

    CDIO_MMC_SET_READ_TYPE(ssc.CDBByte, sector_type);
    CDIO_MMC_SET_READ_LBA(ssc.CDBByte, lsn);
    CDIO_MMC_SET_READ_LENGTH(ssc.CDBByte, nblocks);
    CDIO_MMC_SET_MAIN_CHANNEL_SELECTION_BITS(ssc.CDBByte,
					     CDIO_MMC_MCSB_ALL_HEADERS);
    
    /* Result buffer */
    ssc.SRB_BufPointer  = buf;
    ssc.SRB_BufLen = CDIO_CD_FRAMESIZE_RAW;
    
    /* Initiate transfer */
    ResetEvent( hEvent );
    _obj->lpSendCommand( (void*) &ssc );
    
    /* If the command has still not been processed, wait until it's
     * finished */
    if( ssc.SRB_Status == SS_PENDING ) {
      WaitForSingleObject( hEvent, INFINITE );
    }
    CloseHandle( hEvent );

    /* check that the transfer went as planned */
    if( ssc.SRB_Status != SS_COMP ) {
      return 1;
    }

  } else {
    DWORD dwBytesReturned;
    RAW_READ_INFO cdrom_raw;
    
    /* Initialize CDROM_RAW_READ structure */
    cdrom_raw.DiskOffset.QuadPart = CDIO_CD_FRAMESIZE * lsn;
    cdrom_raw.SectorCount = 1;
    cdrom_raw.TrackMode = XAForm2;
    
    if( DeviceIoControl( _obj->h_device_handle,
			 IOCTL_CDROM_RAW_READ, &cdrom_raw,
			 sizeof(RAW_READ_INFO), buf,
			 sizeof(buf), &dwBytesReturned, NULL )
	== 0 ) {
	return 1;
      }
   }

  /* FIXME! remove the 8 (SUBHEADER size) below... */
  memcpy (data, buf, CDIO_CD_FRAMESIZE_RAW);

  return 0;
}

/*!
   Reads an audio device into data starting from lsn.
   Returns 0 if no error. 
 */
static int
_cdio_read_audio_sectors (void *user_data, void *data, lsn_t lsn, 
			  unsigned int nblocks) 
{
  return _cdio_mmc_read_sectors( user_data, data, lsn, 
				 CDIO_MMC_READ_TYPE_CDDA, nblocks );
}

/*!
   Reads a single mode2 sector from cd device into data starting
   from lsn. Returns 0 if no error. 
 */
static int
_cdio_read_mode2_sector (void *user_data, void *data, lsn_t lsn, 
		    bool mode2_form2)
{
  char buf[CDIO_CD_FRAMESIZE_RAW] = { 0, };
  _img_private_t *_obj = user_data;
  int ret;

  if (_obj->gen.ioctls_debugged == 75)
    cdio_debug ("only displaying every 75th ioctl from now on");

  if (_obj->gen.ioctls_debugged == 30 * 75)
    cdio_debug ("only displaying every 30*75th ioctl from now on");
  
  if (_obj->gen.ioctls_debugged < 75 
      || (_obj->gen.ioctls_debugged < (30 * 75)  
	  && _obj->gen.ioctls_debugged % 75 == 0)
      || _obj->gen.ioctls_debugged % (30 * 75) == 0)
    cdio_debug ("reading %lu", (unsigned long int) lsn);
  
  _obj->gen.ioctls_debugged++;
 
  ret = _cdio_mmc_read_sectors(user_data, buf, lsn, CDIO_MMC_READ_TYPE_ANY, 1);

  if( ret != 0 ) return ret;
  
  if (mode2_form2)
    memcpy (data, buf, M2RAW_SECTOR_SIZE);
  else
    memcpy (((char *)data), buf + CDIO_CD_SUBHEADER_SIZE, CDIO_CD_FRAMESIZE);
  
  return 0;
}

/*!
   Reads nblocks of mode2 sectors from cd device into data starting
   from lsn.
   Returns 0 if no error. 
 */
static int
_cdio_read_mode2_sectors (void *user_data, void *data, lsn_t lsn, 
		     bool mode2_form2, unsigned int nblocks)
{
  _img_private_t *_obj = user_data;
  int i;
  int retval;

  for (i = 0; i < nblocks; i++) {
    if (mode2_form2) {
      if ( (retval = _cdio_read_mode2_sector (_obj, 
					  ((char *)data) + (M2RAW_SECTOR_SIZE * i),
					  lsn + i, true)) )
	return retval;
    } else {
      char buf[M2RAW_SECTOR_SIZE] = { 0, };
      if ( (retval = _cdio_read_mode2_sector (_obj, buf, lsn + i, true)) )
	return retval;
      
      memcpy (((char *)data) + (CDIO_CD_FRAMESIZE * i), 
	      buf + CDIO_CD_SUBHEADER_SIZE, CDIO_CD_FRAMESIZE);
    }
  }
  return 0;
}

/*!
   Return the size of the CD in logical block address (LBA) units.
 */
static uint32_t 
_cdio_stat_size (void *user_data)
{
  _img_private_t *_obj = user_data;

  return _obj->tocent[_obj->total_tracks].start_lsn;
}

/*!
  Set the key "arg" to "value" in source device.
*/
static int
_cdio_set_arg (void *user_data, const char key[], const char value[])
{
  _img_private_t *_obj = user_data;

  if (!strcmp (key, "source"))
    {
      if (!value)
	return -2;

      free (_obj->gen.source_name);
      
      _obj->gen.source_name = strdup (value);
    }
  else 
    return -1;

  return 0;
}

/*! 
  Read and cache the CD's Track Table of Contents and track info.
  Return true if successful or false if an error.
*/
static bool
_cdio_read_toc (_img_private_t *_obj) 
{

  if( _obj->hASPI ) {
    HANDLE hEvent;
    struct SRB_ExecSCSICmd ssc;
    unsigned char p_tocheader[ 4 ];
    
    /* Create the transfer completion event */
    hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
    if( hEvent == NULL ) {
      return false;
    }
    
    memset( &ssc, 0, sizeof( ssc ) );
    
    ssc.SRB_Cmd         = SC_EXEC_SCSI_CMD;
    ssc.SRB_Flags       = SRB_DIR_IN | SRB_EVENT_NOTIFY;
    ssc.SRB_HaId        = LOBYTE( _obj->i_sid );
    ssc.SRB_Target      = HIBYTE( _obj->i_sid );
    ssc.SRB_SenseLen    = SENSE_LEN;
    
    ssc.SRB_PostProc = (LPVOID) hEvent;
    ssc.SRB_CDBLen      = 10;
    
    /* Operation code */
    ssc.CDBByte[ 0 ] = READ_TOC;
    
    /* Format */
    ssc.CDBByte[ 2 ] = READ_TOC_FORMAT_TOC;
    
    /* Starting track */
    ssc.CDBByte[ 6 ] = 0;
    
    /* Allocation length and buffer */
    ssc.SRB_BufLen = sizeof( p_tocheader );
    ssc.SRB_BufPointer  = p_tocheader;
    ssc.CDBByte[ 7 ] = ( ssc.SRB_BufLen >>  8 ) & 0xff;
    ssc.CDBByte[ 8 ] = ( ssc.SRB_BufLen       ) & 0xff;
    
    /* Initiate transfer */
    ResetEvent( hEvent );
    _obj->lpSendCommand( (void*) &ssc );
    
    /* If the command has still not been processed, wait until it's
     * finished */
    if( ssc.SRB_Status == SS_PENDING )
      WaitForSingleObject( hEvent, INFINITE );
    
    /* check that the transfer went as planned */
    if( ssc.SRB_Status != SS_COMP ) {
      CloseHandle( hEvent );
      return false;
    }

    _obj->first_track_num = p_tocheader[2];
    _obj->total_tracks    = p_tocheader[3] - p_tocheader[2] + 1;
    
    {
      int i, i_toclength;
      unsigned char *p_fulltoc;
      
      i_toclength = 4 /* header */ + p_tocheader[0] +
	((unsigned int)p_tocheader[1] << 8);
      
      p_fulltoc = malloc( i_toclength );
      
      if( p_fulltoc == NULL ) {
	cdio_error( "out of memory" );
	CloseHandle( hEvent );
	return false;
      }
      
      /* Allocation length and buffer */
      ssc.SRB_BufLen = i_toclength;
      ssc.SRB_BufPointer  = p_fulltoc;
      ssc.CDBByte[ 7 ] = ( ssc.SRB_BufLen >>  8 ) & 0xff;
      ssc.CDBByte[ 8 ] = ( ssc.SRB_BufLen       ) & 0xff;
      
      /* Initiate transfer */
      ResetEvent( hEvent );
      _obj->lpSendCommand( (void*) &ssc );
      
      /* If the command has still not been processed, wait until it's
       * finished */
      if( ssc.SRB_Status == SS_PENDING )
	WaitForSingleObject( hEvent, INFINITE );
      
      /* check that the transfer went as planned */
      if( ssc.SRB_Status != SS_COMP )
	_obj->total_tracks = 0;
      
      for( i = 0 ; i <= _obj->total_tracks ; i++ ) {
	int i_index = 8 + 8 * i;
	_obj->tocent[ i ].start_lsn = ((int)p_fulltoc[ i_index ] << 24) +
	  ((int)p_fulltoc[ i_index+1 ] << 16) +
	  ((int)p_fulltoc[ i_index+2 ] << 8) +
	  (int)p_fulltoc[ i_index+3 ];
	
	cdio_debug( "p_sectors: %i %lu", 
		    i, (unsigned long int) _obj->tocent[i].start_lsn );
      }
	
      free( p_fulltoc );
    }
    
    CloseHandle( hEvent );
    return true;
    
  } else {
    DWORD dwBytesReturned;
    CDROM_TOC cdrom_toc;
    int i;
    
    if( DeviceIoControl( _obj->h_device_handle,
			 IOCTL_CDROM_READ_TOC,
			 NULL, 0, &cdrom_toc, sizeof(CDROM_TOC),
			 &dwBytesReturned, NULL ) == 0 ) {
      cdio_debug( "could not read TOCHDR" );
      return false;
    }
    
    _obj->first_track_num = cdrom_toc.FirstTrack;
    _obj->total_tracks    = cdrom_toc.LastTrack - cdrom_toc.FirstTrack + 1;
    
      
    for( i = 0 ; i <= _obj->total_tracks ; i++ ) {
	_obj->tocent[ i ].start_lsn = MSF_TO_LBA2(
					 cdrom_toc.TrackData[i].Address[1],
					 cdrom_toc.TrackData[i].Address[2],
					 cdrom_toc.TrackData[i].Address[3] );
	cdio_debug("p_sectors: %i, %lu", i, 
		   (unsigned long int) (_obj->tocent[i].start_lsn));
      }
  }
  return true;
}

/*!
  Eject media. Return 1 if successful, 0 otherwise.
 */
static int 
_cdio_eject_media (void *user_data) {

  _img_private_t *_obj = user_data;


  MCI_OPEN_PARMS op;
  MCI_STATUS_PARMS st;
  DWORD i_flags;
  char psz_drive[4];
  int ret;
    
  memset( &op, 0, sizeof(MCI_OPEN_PARMS) );
  op.lpstrDeviceType = (LPCSTR)MCI_DEVTYPE_CD_AUDIO;
  strcpy( psz_drive, "X:" );
  psz_drive[0] = _obj->gen.source_name[0];
  op.lpstrElementName = psz_drive;
  
  /* Set the flags for the device type */
  i_flags = MCI_OPEN_TYPE | MCI_OPEN_TYPE_ID |
    MCI_OPEN_ELEMENT | MCI_OPEN_SHAREABLE;
  
  if( !mciSendCommand( 0, MCI_OPEN, i_flags, (unsigned long)&op ) ) {
    st.dwItem = MCI_STATUS_READY;
    /* Eject disc */
    ret = mciSendCommand( op.wDeviceID, MCI_SET, MCI_SET_DOOR_OPEN, 0 ) != 0;
    /* Release access to the device */
    mciSendCommand( op.wDeviceID, MCI_CLOSE, MCI_WAIT, 0 );
  } else 
    ret = 0;
  
  return ret;
}

/*!
  Return the value associated with the key "arg".
*/
static const char *
_cdio_get_arg (void *user_data, const char key[])
{
  _img_private_t *_obj = user_data;

  if (!strcmp (key, "source")) {
    return _obj->gen.source_name;
  } else if (!strcmp (key, "access-mode")) {
    if ( WIN_NT ) 
      return "winNT/2K/XP ioctl";
    else if (_obj->hASPI) 
      return "ASPI";
    else 
      return "undefined WIN32";
  } 
  return NULL;
}

/*!
  Return the number of of the first track. 
  CDIO_INVALID_TRACK is returned on error.
*/
static track_t
_cdio_get_first_track_num(void *user_data) 
{
  _img_private_t *_obj = user_data;
  
  if (!_obj->toc_init) _cdio_read_toc (_obj) ;

  return _obj->first_track_num;
}

/*!
  Return the number of tracks in the current medium.
  CDIO_INVALID_TRACK is returned on error.
*/
static track_t
_cdio_get_num_tracks(void *user_data) 
{
  _img_private_t *_obj = user_data;
  
  if (!_obj->toc_init) _cdio_read_toc (_obj) ;

  return _obj->total_tracks;
}

/*!  
  Get format of track. 
*/
static track_format_t
_cdio_get_track_format(void *user_data, track_t track_num) 
{
  _img_private_t *_obj = user_data;

  MCI_OPEN_PARMS op;
  MCI_STATUS_PARMS st;
  DWORD i_flags;
  int ret;

  memset( &op, 0, sizeof(MCI_OPEN_PARMS) );
  op.lpstrDeviceType = (LPCSTR)MCI_DEVTYPE_CD_AUDIO;
  op.lpstrElementName = _obj->gen.source_name;
  
  /* Set the flags for the device type */
  i_flags = MCI_OPEN_TYPE | MCI_OPEN_TYPE_ID |
    MCI_OPEN_ELEMENT | MCI_OPEN_SHAREABLE;
  
  if( !mciSendCommand( 0, MCI_OPEN, i_flags, (unsigned long)&op ) ) {
    st.dwItem  = MCI_CDA_STATUS_TYPE_TRACK;
    st.dwTrack = track_num;
    i_flags = MCI_TRACK | MCI_STATUS_ITEM ;
    ret = mciSendCommand( op.wDeviceID, MCI_STATUS, i_flags, 
			  (unsigned long) &st );

    /* Release access to the device */
    mciSendCommand( op.wDeviceID, MCI_CLOSE, MCI_WAIT, 0 );

    switch(st.dwReturn) {
    case MCI_CDA_TRACK_AUDIO:
      return TRACK_FORMAT_AUDIO;
    case MCI_CDA_TRACK_OTHER:
      return TRACK_FORMAT_DATA;
    default:
      return TRACK_FORMAT_XA;
    }
  }

  return TRACK_FORMAT_ERROR;
  
}

/*!
  Return true if we have XA data (green, mode2 form1) or
  XA data (green, mode2 form2). That is track begins:
  sync - header - subheader
  12     4      -  8

  FIXME: there's gotta be a better design for this and get_track_format?
*/
static bool
_cdio_get_track_green(void *user_data, track_t track_num) 
{
  _img_private_t *_obj = user_data;
  
  if (!_obj->toc_init) _cdio_read_toc (_obj) ;

  if (track_num == CDIO_CDROM_LEADOUT_TRACK) track_num = _obj->total_tracks+1;

  if (track_num > _obj->total_tracks+1 || track_num == 0)
    return false;

  /* FIXME! */
  return true;
}

/*!  
  Return the starting MSF (minutes/secs/frames) for track number
  track_num in obj.  Track numbers start at 1.
  The "leadout" track is specified either by
  using track_num LEADOUT_TRACK or the total tracks+1.
  False is returned if there is no track entry.
*/
static bool
_cdio_get_track_msf(void *user_data, track_t track_num, msf_t *msf)
{
  _img_private_t *_obj = user_data;

  if (NULL == msf) return false;

  if (!_obj->toc_init) _cdio_read_toc (_obj) ;

  if (track_num == CDIO_CDROM_LEADOUT_TRACK) track_num = _obj->total_tracks+1;

  if (track_num > _obj->total_tracks+1 || track_num == 0) {
    return false;
  } else {
    cdio_lsn_to_msf(_obj->tocent[track_num-1].start_lsn, msf);
    return true;
  }
}

#endif /* HAVE_WIN32_CDROM */

/*!
  Return an array of strings giving possible CD devices.
 */
char **
cdio_get_devices_win32 (void)
{
#ifndef HAVE_WIN32_CDROM
  return NULL;
#else
  char **drives = NULL;
  unsigned int num_drives=0;
  char drive_letter;
  
  /* Scan the system for CD-ROM drives.
  */

#if FINISHED
  /* Now check the currently mounted CD drives */
  if (NULL != (ret_drive = cdio_check_mounts("/etc/mtab"))) {
    cdio_add_device_list(&drives, drive, &num_drives);
  }
  
  /* Finally check possible mountable drives in /etc/fstab */
  if (NULL != (ret_drive = cdio_check_mounts("/etc/fstab"))) {
    cdio_add_device_list(&drives, drive, &num_drives);
  }
#endif

  /* Scan the system for CD-ROM drives.
     Not always 100% reliable, so use the USE_MNTENT code above first.
  */
  for (drive_letter='A'; drive_letter <= 'Z'; drive_letter++) {
    const char *drive_str=cdio_is_cdrom(drive_letter);
    if (drive_str != NULL) {
      cdio_add_device_list(&drives, drive_str, &num_drives);
    }
  }
  cdio_add_device_list(&drives, NULL, &num_drives);
  return drives;
#endif /*HAVE_WIN32_CDROM*/
}

/*!
  Return a string containing the default CD device if none is specified.
  if CdIo is NULL (we haven't initialized a specific device driver), 
  then find a suitable one and return the default device for that.
  
  NULL is returned if we couldn't get a default device.
*/
char *
cdio_get_default_device_win32(void)
{

#ifdef HAVE_WIN32_CDROM
  char drive_letter;

  for (drive_letter='A'; drive_letter <= 'Z'; drive_letter++) {
    const char *drive_str=cdio_is_cdrom(drive_letter);
    if (drive_str != NULL) {
      return strdup(drive_str);
    }
  }
#endif
  return NULL;
}

/*!  
  Return true if source_name could be a device containing a CD-ROM.
*/
bool
cdio_is_device_win32(const char *source_name)
{
  unsigned int len;
  len = strlen(source_name);

  if (NULL == source_name) return false;

#ifdef HAVE_WIN32_CDROM
  if ( WIN_NT )
    /* Really should test to see if of form: \\.\x: */
    return ((len == 6) && isalpha(source_name[len-2])
	    && (source_name[len-1] == ':'));
  else
    /* See if is of form: x: */
    return ((len == 2) && isalpha(source_name[0]) 
	    && (source_name[len-1] == ':'));
#else 
  return false;
#endif
}

/*!
  Initialization routine. This is the only thing that doesn't
  get called via a function pointer. In fact *we* are the
  ones to set that up.
 */
CdIo *
cdio_open_win32 (const char *source_name)
{

#ifdef HAVE_WIN32_CDROM
  CdIo *ret;
  _img_private_t *_data;

  cdio_funcs _funcs = {
    .eject_media        = _cdio_eject_media,
    .free               = _cdio_win32_free,
    .get_arg            = _cdio_get_arg,
    .get_default_device = cdio_get_default_device_win32,
    .get_devices        = cdio_get_devices_win32,
    .get_first_track_num= _cdio_get_first_track_num,
    .get_mcn            = NULL, 
    .get_num_tracks     = _cdio_get_num_tracks,
    .get_track_format   = _cdio_get_track_format,
    .get_track_green    = _cdio_get_track_green,
    .get_track_lba      = NULL, /* This could be implemented if need be. */
    .get_track_msf      = _cdio_get_track_msf,
    .lseek              = NULL,
    .read               = NULL,
    .read_audio_sectors = _cdio_read_audio_sectors,
    .read_mode2_sector  = _cdio_read_mode2_sector,
    .read_mode2_sectors = _cdio_read_mode2_sectors,
    .set_arg            = _cdio_set_arg,
    .stat_size          = _cdio_stat_size
  };

  _data                 = _cdio_malloc (sizeof (_img_private_t));
  _data->gen.init       = false;
  _data->gen.fd         = -1;

  _cdio_set_arg(_data, "source", (NULL == source_name) 
		? cdio_get_default_device_win32(): source_name);

  ret = cdio_new (_data, &_funcs);
  if (ret == NULL) return NULL;

  if (_cdio_init_win32(_data))
    return ret;
  else {
    _cdio_win32_free (_data);
    return NULL;
  }
  
#else 
  return NULL;
#endif /* HAVE_WIN32_CDROM */

}

bool
cdio_have_win32 (void)
{
#ifdef HAVE_WIN32_CDROM
  return true;
#else 
  return false;
#endif /* HAVE_WIN32_CDROM */
}