]> git.sesse.net Git - vlc/blob - modules/access/vcd/cdrom.c
Avoid ?: GCC-ism
[vlc] / modules / access / vcd / cdrom.c
1 /****************************************************************************
2  * cdrom.c: cdrom tools
3  *****************************************************************************
4  * Copyright (C) 1998-2001 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Johan Bilien <jobi@via.ecp.fr>
8  *          Gildas Bazin <gbazin@netcourrier.com>
9  *          Jon Lech Johansen <jon-vl@nanocrew.net>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_access.h>
35 #include <limits.h>
36
37 #ifdef HAVE_UNISTD_H
38 #   include <unistd.h>
39 #endif
40
41 #include <errno.h>
42 #ifdef HAVE_SYS_TYPES_H
43 #   include <sys/types.h>
44 #endif
45 #ifdef HAVE_SYS_STAT_H
46 #   include <sys/stat.h>
47 #endif
48 #ifdef HAVE_FCNTL_H
49 #   include <fcntl.h>
50 #endif
51
52 #if defined( SYS_BSDI )
53 #   include <dvd.h>
54 #elif defined ( __APPLE__ )
55 #   include <CoreFoundation/CFBase.h>
56 #   include <IOKit/IOKitLib.h>
57 #   include <IOKit/storage/IOCDTypes.h>
58 #   include <IOKit/storage/IOCDMedia.h>
59 #   include <IOKit/storage/IOCDMediaBSDClient.h>
60 #elif defined( HAVE_SCSIREQ_IN_SYS_SCSIIO_H )
61 #   include <inttypes.h>
62 #   include <sys/cdio.h>
63 #   include <sys/scsiio.h>
64 #elif defined( HAVE_IOC_TOC_HEADER_IN_SYS_CDIO_H )
65 #   include <sys/cdio.h>
66 #   include <sys/cdrio.h>
67 #elif defined( WIN32 )
68 #   include <windows.h>
69 #   include <winioctl.h>
70 #elif defined (__linux__)
71 #   include <sys/ioctl.h>
72 #   include <linux/cdrom.h>
73 #else
74 #   error FIXME
75 #endif
76
77 #include "cdrom_internals.h"
78 #include "cdrom.h"
79 #include <vlc_charset.h>
80 #include <vlc_meta.h>
81
82 /*****************************************************************************
83  * ioctl_Open: Opens a VCD device or file and returns an opaque handle
84  *****************************************************************************/
85 vcddev_t *ioctl_Open( vlc_object_t *p_this, const char *psz_dev )
86 {
87     int i_ret;
88     int b_is_file;
89     vcddev_t *p_vcddev;
90 #ifndef WIN32
91     struct stat fileinfo;
92 #endif
93
94     if( !psz_dev ) return NULL;
95
96     /*
97      *  Initialize structure with default values
98      */
99     p_vcddev = malloc( sizeof(*p_vcddev) );
100     if( p_vcddev == NULL )
101         return NULL;
102     p_vcddev->i_vcdimage_handle = -1;
103     p_vcddev->psz_dev = NULL;
104     b_is_file = 1;
105
106     /*
107      *  Check if we are dealing with a device or a file (vcd image)
108      */
109 #ifdef WIN32
110     if( (strlen( psz_dev ) == 2 && psz_dev[1] == ':') )
111     {
112         b_is_file = 0;
113     }
114
115 #else
116     if( stat( psz_dev, &fileinfo ) < 0 )
117     {
118         free( p_vcddev );
119         return NULL;
120     }
121
122     /* Check if this is a block/char device */
123     if( S_ISBLK( fileinfo.st_mode ) || S_ISCHR( fileinfo.st_mode ) )
124         b_is_file = 0;
125 #endif
126
127     if( b_is_file )
128     {
129         i_ret = OpenVCDImage( p_this, psz_dev, p_vcddev );
130     }
131     else
132     {
133         /*
134          *  open the vcd device
135          */
136
137 #ifdef WIN32
138         i_ret = win32_vcd_open( p_this, psz_dev, p_vcddev );
139 #else
140         p_vcddev->i_device_handle = -1;
141         p_vcddev->i_device_handle = open( psz_dev, O_RDONLY | O_NONBLOCK );
142         i_ret = (p_vcddev->i_device_handle == -1) ? -1 : 0;
143 #endif
144     }
145
146     if( i_ret == 0 )
147     {
148         p_vcddev->psz_dev = (char *)strdup( psz_dev );
149     }
150     else
151     {
152         free( p_vcddev );
153         p_vcddev = NULL;
154     }
155
156     return p_vcddev;
157 }
158
159 /*****************************************************************************
160  * ioctl_Close: Closes an already opened VCD device or file.
161  *****************************************************************************/
162 void ioctl_Close( vlc_object_t * p_this, vcddev_t *p_vcddev )
163 {
164     free( p_vcddev->psz_dev );
165
166     if( p_vcddev->i_vcdimage_handle != -1 )
167     {
168         /*
169          *  vcd image mode
170          */
171
172         CloseVCDImage( p_this, p_vcddev );
173         return;
174     }
175
176     /*
177      *  vcd device mode
178      */
179
180 #ifdef WIN32
181     if( p_vcddev->h_device_handle )
182         CloseHandle( p_vcddev->h_device_handle );
183     if( p_vcddev->hASPI )
184         FreeLibrary( (HMODULE)p_vcddev->hASPI );
185 #else
186     if( p_vcddev->i_device_handle != -1 )
187         close( p_vcddev->i_device_handle );
188 #endif
189     free( p_vcddev );
190 }
191
192 /*****************************************************************************
193  * ioctl_GetTracksMap: Read the Table of Content, fill in the pp_sectors map
194  *                     if pp_sectors is not null and return the number of
195  *                     tracks available.
196  *****************************************************************************/
197 int ioctl_GetTracksMap( vlc_object_t *p_this, const vcddev_t *p_vcddev,
198                         int **pp_sectors )
199 {
200     int i_tracks = 0;
201
202     if( p_vcddev->i_vcdimage_handle != -1 )
203     {
204         /*
205          *  vcd image mode
206          */
207
208         i_tracks = p_vcddev->i_tracks;
209
210         if( pp_sectors )
211         {
212             *pp_sectors = calloc( i_tracks + 1, sizeof(**pp_sectors) );
213             if( *pp_sectors == NULL )
214                 return 0;
215             memcpy( *pp_sectors, p_vcddev->p_sectors,
216                     (i_tracks + 1) * sizeof(**pp_sectors) );
217         }
218
219         return i_tracks;
220     }
221     else
222     {
223
224         /*
225          *  vcd device mode
226          */
227
228 #if defined( __APPLE__ )
229
230         CDTOC *pTOC;
231         int i_descriptors;
232
233         if( ( pTOC = darwin_getTOC( p_this, p_vcddev ) ) == NULL )
234         {
235             msg_Err( p_this, "failed to get the TOC" );
236             return 0;
237         }
238
239         i_descriptors = CDTOCGetDescriptorCount( pTOC );
240         i_tracks = darwin_getNumberOfTracks( pTOC, i_descriptors );
241
242         if( pp_sectors )
243         {
244             int i, i_leadout = -1;
245             CDTOCDescriptor *pTrackDescriptors;
246             u_char track;
247
248             *pp_sectors = calloc( i_tracks + 1, sizeof(**pp_sectors) );
249             if( *pp_sectors == NULL )
250             {
251                 darwin_freeTOC( pTOC );
252                 return 0;
253             }
254
255             pTrackDescriptors = pTOC->descriptors;
256
257             for( i_tracks = 0, i = 0; i < i_descriptors; i++ )
258             {
259                 track = pTrackDescriptors[i].point;
260
261                 if( track == 0xA2 )
262                     i_leadout = i;
263
264                 if( track > CD_MAX_TRACK_NO || track < CD_MIN_TRACK_NO )
265                     continue;
266
267                 (*pp_sectors)[i_tracks++] =
268                     CDConvertMSFToLBA( pTrackDescriptors[i].p );
269             }
270
271             if( i_leadout == -1 )
272             {
273                 msg_Err( p_this, "leadout not found" );
274                 free( *pp_sectors );
275                 darwin_freeTOC( pTOC );
276                 return 0;
277             }
278
279             /* set leadout sector */
280             (*pp_sectors)[i_tracks] =
281                 CDConvertMSFToLBA( pTrackDescriptors[i_leadout].p );
282         }
283
284         darwin_freeTOC( pTOC );
285
286 #elif defined( WIN32 )
287         if( p_vcddev->hASPI )
288         {
289             HANDLE hEvent;
290             struct SRB_ExecSCSICmd ssc;
291             uint8_t p_tocheader[ 4 ];
292
293             /* Create the transfer completion event */
294             hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
295             if( hEvent == NULL )
296             {
297                 return -1;
298             }
299
300             memset( &ssc, 0, sizeof( ssc ) );
301
302             ssc.SRB_Cmd         = SC_EXEC_SCSI_CMD;
303             ssc.SRB_Flags       = SRB_DIR_IN | SRB_EVENT_NOTIFY;
304             ssc.SRB_HaId        = LOBYTE( p_vcddev->i_sid );
305             ssc.SRB_Target      = HIBYTE( p_vcddev->i_sid );
306             ssc.SRB_SenseLen    = SENSE_LEN;
307
308             ssc.SRB_PostProc = (LPVOID) hEvent;
309             ssc.SRB_CDBLen      = 10;
310
311             /* Operation code */
312             ssc.CDBByte[ 0 ] = READ_TOC;
313
314             /* Format */
315             ssc.CDBByte[ 2 ] = READ_TOC_FORMAT_TOC;
316
317             /* Starting track */
318             ssc.CDBByte[ 6 ] = 0;
319
320             /* Allocation length and buffer */
321             ssc.SRB_BufLen = sizeof( p_tocheader );
322             ssc.SRB_BufPointer  = p_tocheader;
323             ssc.CDBByte[ 7 ] = ( ssc.SRB_BufLen >>  8 ) & 0xff;
324             ssc.CDBByte[ 8 ] = ( ssc.SRB_BufLen       ) & 0xff;
325
326             /* Initiate transfer */
327             ResetEvent( hEvent );
328             p_vcddev->lpSendCommand( (void*) &ssc );
329
330             /* If the command has still not been processed, wait until it's
331              * finished */
332             if( ssc.SRB_Status == SS_PENDING )
333                 WaitForSingleObject( hEvent, INFINITE );
334
335             /* check that the transfer went as planned */
336             if( ssc.SRB_Status != SS_COMP )
337             {
338                 CloseHandle( hEvent );
339                 return 0;
340             }
341
342             i_tracks = p_tocheader[3] - p_tocheader[2] + 1;
343
344             if( pp_sectors )
345             {
346                 int i, i_toclength;
347                 uint8_t *p_fulltoc;
348
349                 i_toclength = 4 /* header */ + p_tocheader[0] +
350                               ((unsigned int)p_tocheader[1] << 8);
351
352                 p_fulltoc = malloc( i_toclength );
353                 *pp_sectors = calloc( i_tracks + 1, sizeof(**pp_sectors) );
354
355                 if( *pp_sectors == NULL || p_fulltoc == NULL )
356                 {
357                     free( *pp_sectors );
358                     free( p_fulltoc );
359                     CloseHandle( hEvent );
360                     return 0;
361                 }
362
363                 /* Allocation length and buffer */
364                 ssc.SRB_BufLen = i_toclength;
365                 ssc.SRB_BufPointer  = p_fulltoc;
366                 ssc.CDBByte[ 7 ] = ( ssc.SRB_BufLen >>  8 ) & 0xff;
367                 ssc.CDBByte[ 8 ] = ( ssc.SRB_BufLen       ) & 0xff;
368
369                 /* Initiate transfer */
370                 ResetEvent( hEvent );
371                 p_vcddev->lpSendCommand( (void*) &ssc );
372
373                 /* If the command has still not been processed, wait until it's
374                  * finished */
375                 if( ssc.SRB_Status == SS_PENDING )
376                     WaitForSingleObject( hEvent, INFINITE );
377
378                 /* check that the transfer went as planned */
379                 if( ssc.SRB_Status != SS_COMP )
380                     i_tracks = 0;
381
382                 for( i = 0 ; i <= i_tracks ; i++ )
383                 {
384                     int i_index = 8 + 8 * i;
385                     (*pp_sectors)[ i ] = ((int)p_fulltoc[ i_index ] << 24) +
386                                          ((int)p_fulltoc[ i_index+1 ] << 16) +
387                                          ((int)p_fulltoc[ i_index+2 ] << 8) +
388                                          (int)p_fulltoc[ i_index+3 ];
389
390                     msg_Dbg( p_this, "p_sectors: %i, %i", i, (*pp_sectors)[i]);
391                 }
392
393                 free( p_fulltoc );
394             }
395
396             CloseHandle( hEvent );
397
398         }
399         else
400         {
401             DWORD dwBytesReturned;
402             CDROM_TOC cdrom_toc;
403
404             if( DeviceIoControl( p_vcddev->h_device_handle,
405                                  IOCTL_CDROM_READ_TOC,
406                                  NULL, 0, &cdrom_toc, sizeof(CDROM_TOC),
407                                  &dwBytesReturned, NULL ) == 0 )
408             {
409                 msg_Err( p_this, "could not read TOCHDR" );
410                 return 0;
411             }
412
413             i_tracks = cdrom_toc.LastTrack - cdrom_toc.FirstTrack + 1;
414
415             if( pp_sectors )
416             {
417                 int i;
418
419                 *pp_sectors = calloc( i_tracks + 1, sizeof(**pp_sectors) );
420                 if( *pp_sectors == NULL )
421                     return 0;
422
423                 for( i = 0 ; i <= i_tracks ; i++ )
424                 {
425                     (*pp_sectors)[ i ] = MSF_TO_LBA2(
426                                            cdrom_toc.TrackData[i].Address[1],
427                                            cdrom_toc.TrackData[i].Address[2],
428                                            cdrom_toc.TrackData[i].Address[3] );
429                     msg_Dbg( p_this, "p_sectors: %i, %i", i, (*pp_sectors)[i]);
430                 }
431             }
432         }
433
434 #elif defined( HAVE_IOC_TOC_HEADER_IN_SYS_CDIO_H ) \
435        || defined( HAVE_SCSIREQ_IN_SYS_SCSIIO_H )
436         struct ioc_toc_header tochdr;
437         struct ioc_read_toc_entry toc_entries;
438
439         if( ioctl( p_vcddev->i_device_handle, CDIOREADTOCHEADER, &tochdr )
440             == -1 )
441         {
442             msg_Err( p_this, "could not read TOCHDR" );
443             return 0;
444         }
445
446         i_tracks = tochdr.ending_track - tochdr.starting_track + 1;
447
448         if( pp_sectors )
449         {
450              int i;
451
452              *pp_sectors = calloc( i_tracks + 1, sizeof(**pp_sectors) );
453              if( *pp_sectors == NULL )
454                  return 0;
455
456              toc_entries.address_format = CD_LBA_FORMAT;
457              toc_entries.starting_track = 0;
458              toc_entries.data_len = ( i_tracks + 1 ) *
459                                         sizeof( struct cd_toc_entry );
460              toc_entries.data = (struct cd_toc_entry *)
461                                     malloc( toc_entries.data_len );
462              if( toc_entries.data == NULL )
463              {
464                  free( *pp_sectors );
465                  return 0;
466              }
467
468              /* Read the TOC */
469              if( ioctl( p_vcddev->i_device_handle, CDIOREADTOCENTRYS,
470                         &toc_entries ) == -1 )
471              {
472                  msg_Err( p_this, "could not read the TOC" );
473                  free( *pp_sectors );
474                  free( toc_entries.data );
475                  return 0;
476              }
477
478              /* Fill the p_sectors structure with the track/sector matches */
479              for( i = 0 ; i <= i_tracks ; i++ )
480              {
481 #if defined( HAVE_SCSIREQ_IN_SYS_SCSIIO_H )
482                  /* FIXME: is this ok? */
483                  (*pp_sectors)[ i ] = toc_entries.data[i].addr.lba;
484 #else
485                  (*pp_sectors)[ i ] = ntohl( toc_entries.data[i].addr.lba );
486 #endif
487              }
488         }
489 #else
490         struct cdrom_tochdr   tochdr;
491         struct cdrom_tocentry tocent;
492
493         /* First we read the TOC header */
494         if( ioctl( p_vcddev->i_device_handle, CDROMREADTOCHDR, &tochdr )
495             == -1 )
496         {
497             msg_Err( p_this, "could not read TOCHDR" );
498             return 0;
499         }
500
501         i_tracks = tochdr.cdth_trk1 - tochdr.cdth_trk0 + 1;
502
503         if( pp_sectors )
504         {
505             int i;
506
507             *pp_sectors = calloc( i_tracks + 1, sizeof(**pp_sectors) );
508             if( *pp_sectors == NULL )
509                 return 0;
510
511             /* Fill the p_sectors structure with the track/sector matches */
512             for( i = 0 ; i <= i_tracks ; i++ )
513             {
514                 tocent.cdte_format = CDROM_LBA;
515                 tocent.cdte_track =
516                     ( i == i_tracks ) ? CDROM_LEADOUT : tochdr.cdth_trk0 + i;
517
518                 if( ioctl( p_vcddev->i_device_handle, CDROMREADTOCENTRY,
519                            &tocent ) == -1 )
520                 {
521                     msg_Err( p_this, "could not read TOCENTRY" );
522                     free( *pp_sectors );
523                     return 0;
524                 }
525
526                 (*pp_sectors)[ i ] = tocent.cdte_addr.lba;
527             }
528         }
529 #endif
530
531         return i_tracks;
532     }
533 }
534
535 /****************************************************************************
536  * ioctl_ReadSector: Read VCD or CDDA sectors
537  ****************************************************************************/
538 int ioctl_ReadSectors( vlc_object_t *p_this, const vcddev_t *p_vcddev,
539                        int i_sector, uint8_t *p_buffer, int i_nb, int i_type )
540 {
541     uint8_t *p_block;
542     int i;
543
544     if( i_type == VCD_TYPE )
545         p_block = malloc( VCD_SECTOR_SIZE * i_nb );
546     else
547         p_block = p_buffer;
548
549     if( p_vcddev->i_vcdimage_handle != -1 )
550     {
551         /*
552          *  vcd image mode
553          */
554         if( lseek( p_vcddev->i_vcdimage_handle, i_sector * VCD_SECTOR_SIZE,
555                    SEEK_SET ) == -1 )
556         {
557             msg_Err( p_this, "Could not lseek to sector %d", i_sector );
558             if( i_type == VCD_TYPE ) free( p_block );
559             return -1;
560         }
561
562         if( read( p_vcddev->i_vcdimage_handle, p_block, VCD_SECTOR_SIZE * i_nb)
563             == -1 )
564         {
565             msg_Err( p_this, "Could not read sector %d", i_sector );
566             if( i_type == VCD_TYPE ) free( p_block );
567             return -1;
568         }
569
570     }
571     else
572     {
573
574         /*
575          *  vcd device mode
576          */
577
578 #if defined( __APPLE__ )
579         dk_cd_read_t cd_read;
580
581         memset( &cd_read, 0, sizeof(cd_read) );
582
583         cd_read.offset = i_sector * VCD_SECTOR_SIZE;
584         cd_read.sectorArea = kCDSectorAreaSync | kCDSectorAreaHeader |
585                              kCDSectorAreaSubHeader | kCDSectorAreaUser |
586                              kCDSectorAreaAuxiliary;
587         cd_read.sectorType = kCDSectorTypeUnknown;
588
589         cd_read.buffer = p_block;
590         cd_read.bufferLength = VCD_SECTOR_SIZE * i_nb;
591
592         if( ioctl( p_vcddev->i_device_handle, DKIOCCDREAD, &cd_read ) == -1 )
593         {
594             msg_Err( p_this, "could not read block %d", i_sector );
595             if( i_type == VCD_TYPE ) free( p_block );
596             return -1;
597         }
598
599 #elif defined( WIN32 )
600         if( p_vcddev->hASPI )
601         {
602             HANDLE hEvent;
603             struct SRB_ExecSCSICmd ssc;
604
605             /* Create the transfer completion event */
606             hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
607             if( hEvent == NULL )
608             {
609                 if( i_type == VCD_TYPE ) free( p_block );
610                 return -1;
611             }
612
613             memset( &ssc, 0, sizeof( ssc ) );
614
615             ssc.SRB_Cmd         = SC_EXEC_SCSI_CMD;
616             ssc.SRB_Flags       = SRB_DIR_IN | SRB_EVENT_NOTIFY;
617             ssc.SRB_HaId        = LOBYTE( p_vcddev->i_sid );
618             ssc.SRB_Target      = HIBYTE( p_vcddev->i_sid );
619             ssc.SRB_SenseLen    = SENSE_LEN;
620
621             ssc.SRB_PostProc = (LPVOID) hEvent;
622             ssc.SRB_CDBLen      = 12;
623
624             /* Operation code */
625             ssc.CDBByte[ 0 ] = READ_CD;
626
627             /* Sector type */
628             ssc.CDBByte[ 1 ] = i_type == VCD_TYPE ? SECTOR_TYPE_MODE2_FORM2 :
629                                                     SECTOR_TYPE_CDDA;
630
631             /* Start of LBA */
632             ssc.CDBByte[ 2 ] = ( i_sector >> 24 ) & 0xff;
633             ssc.CDBByte[ 3 ] = ( i_sector >> 16 ) & 0xff;
634             ssc.CDBByte[ 4 ] = ( i_sector >>  8 ) & 0xff;
635             ssc.CDBByte[ 5 ] = ( i_sector       ) & 0xff;
636
637             /* Transfer length */
638             ssc.CDBByte[ 6 ] = ( i_nb >> 16 ) & 0xff;
639             ssc.CDBByte[ 7 ] = ( i_nb >> 8  ) & 0xff;
640             ssc.CDBByte[ 8 ] = ( i_nb       ) & 0xff;
641
642             /* Data selection */
643             ssc.CDBByte[ 9 ] = i_type == VCD_TYPE ? READ_CD_RAW_MODE2 :
644                                                     READ_CD_USERDATA;
645
646             /* Result buffer */
647             ssc.SRB_BufPointer  = p_block;
648             ssc.SRB_BufLen = VCD_SECTOR_SIZE * i_nb;
649
650             /* Initiate transfer */
651             ResetEvent( hEvent );
652             p_vcddev->lpSendCommand( (void*) &ssc );
653
654             /* If the command has still not been processed, wait until it's
655              * finished */
656             if( ssc.SRB_Status == SS_PENDING )
657             {
658                 WaitForSingleObject( hEvent, INFINITE );
659             }
660             CloseHandle( hEvent );
661
662             /* check that the transfer went as planned */
663             if( ssc.SRB_Status != SS_COMP )
664             {
665                 if( i_type == VCD_TYPE ) free( p_block );
666                 return -1;
667             }
668         }
669         else
670         {
671             DWORD dwBytesReturned;
672             RAW_READ_INFO cdrom_raw;
673
674             /* Initialize CDROM_RAW_READ structure */
675             cdrom_raw.DiskOffset.QuadPart = CD_SECTOR_SIZE * i_sector;
676             cdrom_raw.SectorCount = i_nb;
677             cdrom_raw.TrackMode =  i_type == VCD_TYPE ? XAForm2 : CDDA;
678
679             if( DeviceIoControl( p_vcddev->h_device_handle,
680                                  IOCTL_CDROM_RAW_READ, &cdrom_raw,
681                                  sizeof(RAW_READ_INFO), p_block,
682                                  VCD_SECTOR_SIZE * i_nb, &dwBytesReturned,
683                                  NULL ) == 0 )
684             {
685                 if( i_type == VCD_TYPE )
686                 {
687                     /* Retry in YellowMode2 */
688                     cdrom_raw.TrackMode = YellowMode2;
689                     if( DeviceIoControl( p_vcddev->h_device_handle,
690                                  IOCTL_CDROM_RAW_READ, &cdrom_raw,
691                                  sizeof(RAW_READ_INFO), p_block,
692                                  VCD_SECTOR_SIZE * i_nb, &dwBytesReturned,
693                                  NULL ) == 0 )
694                     {
695                         free( p_block );
696                         return -1;
697                     }
698                 }
699                 else return -1;
700             }
701         }
702
703 #elif defined( HAVE_SCSIREQ_IN_SYS_SCSIIO_H )
704         struct scsireq  sc;
705         int i_ret;
706
707         memset( &sc, 0, sizeof(sc) );
708         sc.cmd[0] = 0xBE;
709         sc.cmd[1] = i_type == VCD_TYPE ? SECTOR_TYPE_MODE2_FORM2:
710                                          SECTOR_TYPE_CDDA;
711         sc.cmd[2] = (i_sector >> 24) & 0xff;
712         sc.cmd[3] = (i_sector >> 16) & 0xff;
713         sc.cmd[4] = (i_sector >>  8) & 0xff;
714         sc.cmd[5] = (i_sector >>  0) & 0xff;
715         sc.cmd[6] = (i_nb >> 16) & 0xff;
716         sc.cmd[7] = (i_nb >>  8) & 0xff;
717         sc.cmd[8] = (i_nb      ) & 0xff;
718         sc.cmd[9] = i_type == VCD_TYPE ? READ_CD_RAW_MODE2 : READ_CD_USERDATA;
719         sc.cmd[10] = 0; /* sub channel */
720         sc.cmdlen = 12;
721         sc.databuf = (caddr_t)p_block;
722         sc.datalen = VCD_SECTOR_SIZE * i_nb;
723         sc.senselen = sizeof( sc.sense );
724         sc.flags = SCCMD_READ;
725         sc.timeout = 10000;
726
727         i_ret = ioctl( p_vcddev->i_device_handle, SCIOCCOMMAND, &sc );
728         if( i_ret == -1 )
729         {
730             msg_Err( p_this, "SCIOCCOMMAND failed" );
731             if( i_type == VCD_TYPE ) free( p_block );
732             return -1;
733         }
734         if( sc.retsts || sc.error )
735         {
736             msg_Err( p_this, "SCSI command failed: status %d error %d",
737                              sc.retsts, sc.error );
738             if( i_type == VCD_TYPE ) free( p_block );
739            return -1;
740         }
741
742 #elif defined( HAVE_IOC_TOC_HEADER_IN_SYS_CDIO_H )
743         int i_size = VCD_SECTOR_SIZE;
744
745         if( ioctl( p_vcddev->i_device_handle, CDRIOCSETBLOCKSIZE, &i_size )
746             == -1 )
747         {
748             msg_Err( p_this, "Could not set block size" );
749             if( i_type == VCD_TYPE ) free( p_block );
750             return( -1 );
751         }
752
753         if( lseek( p_vcddev->i_device_handle,
754                    i_sector * VCD_SECTOR_SIZE, SEEK_SET ) == -1 )
755         {
756             msg_Err( p_this, "Could not lseek to sector %d", i_sector );
757             if( i_type == VCD_TYPE ) free( p_block );
758             return( -1 );
759         }
760
761         if( read( p_vcddev->i_device_handle,
762                   p_block, VCD_SECTOR_SIZE * i_nb ) == -1 )
763         {
764             msg_Err( p_this, "Could not read sector %d", i_sector );
765             if( i_type == VCD_TYPE ) free( p_block );
766             return( -1 );
767         }
768
769 #else
770         for( i = 0; i < i_nb; i++ )
771         {
772             int i_dummy = i_sector + i + 2 * CD_FRAMES;
773
774 #define p_msf ((struct cdrom_msf0 *)(p_block + i * VCD_SECTOR_SIZE))
775             p_msf->minute =   i_dummy / (CD_FRAMES * CD_SECS);
776             p_msf->second = ( i_dummy % (CD_FRAMES * CD_SECS) ) / CD_FRAMES;
777             p_msf->frame =  ( i_dummy % (CD_FRAMES * CD_SECS) ) % CD_FRAMES;
778 #undef p_msf
779
780             if( ioctl( p_vcddev->i_device_handle, CDROMREADRAW,
781                        p_block + i * VCD_SECTOR_SIZE ) == -1 )
782             {
783                 msg_Err( p_this, "could not read block %i from disc",
784                          i_sector );
785
786                 if( i == 0 )
787                 {
788                     if( i_type == VCD_TYPE ) free( p_block );
789                     return( -1 );
790                 }
791                 else break;
792             }
793         }
794 #endif
795     }
796
797     /* For VCDs, we don't want to keep the header and footer of the
798      * sectors read */
799     if( i_type == VCD_TYPE )
800     {
801         for( i = 0; i < i_nb; i++ )
802         {
803             memcpy( p_buffer + i * VCD_DATA_SIZE,
804                     p_block + i * VCD_SECTOR_SIZE + VCD_DATA_START,
805                     VCD_DATA_SIZE );
806         }
807         free( p_block );
808     }
809
810     return( 0 );
811 }
812
813 /****************************************************************************
814  * Private functions
815  ****************************************************************************/
816
817 /****************************************************************************
818  * OpenVCDImage: try to open a vcd image from a .cue file
819  ****************************************************************************/
820 static int OpenVCDImage( vlc_object_t * p_this, const char *psz_dev,
821                          vcddev_t *p_vcddev )
822 {
823     int i_ret = -1;
824     char *p_pos;
825     char *psz_vcdfile = NULL;
826     char *psz_cuefile = NULL;
827     FILE *cuefile     = NULL;
828     int *p_sectors    = NULL;
829     char line[1024];
830     bool b_found      = false;
831
832     /* Check if we are dealing with a .cue file */
833     p_pos = strrchr( psz_dev, '.' );
834     if( p_pos && !strcmp( p_pos, ".cue" ) )
835     {
836         /* psz_dev must be the cue file. Let's assume there's a .bin
837          * file with the same filename */
838         psz_vcdfile = malloc( p_pos - psz_dev + 5 /* ".bin" */ );
839         strncpy( psz_vcdfile, psz_dev, p_pos - psz_dev );
840         strcpy( psz_vcdfile + (p_pos - psz_dev), ".bin");
841         psz_cuefile = strdup( psz_dev );
842     }
843     else
844     {
845         /* psz_dev must be the actual vcd file. Let's assume there's a .cue
846          * file with the same filename */
847         if( p_pos )
848         {
849             psz_cuefile = malloc( p_pos - psz_dev + 5 /* ".cue" */ );
850             strncpy( psz_cuefile, psz_dev, p_pos - psz_dev );
851             strcpy( psz_cuefile + (p_pos - psz_dev), ".cue");
852         }
853         else
854         {
855             if( asprintf( &psz_cuefile, "%s.cue", psz_dev ) == -1 )
856                 psz_cuefile = NULL;
857         }
858         /* If we need to look up the .cue file, then we don't have to look for the vcd */
859         psz_vcdfile = strdup( psz_dev );
860     }
861
862     /* Open the cue file and try to parse it */
863     msg_Dbg( p_this,"trying .cue file: %s", psz_cuefile );
864     cuefile = utf8_fopen( psz_cuefile, "rt" );
865     if( cuefile == NULL )
866     {
867         msg_Dbg( p_this, "could not find .cue file" );
868         goto error;
869     }
870
871     msg_Dbg( p_this,"guessing vcd image file: %s", psz_vcdfile );
872     p_vcddev->i_vcdimage_handle = utf8_open( psz_vcdfile,
873                                     O_RDONLY | O_NONBLOCK | O_BINARY, 0666 );
874  
875     while( fgets( line, 1024, cuefile ) && !b_found )
876     {
877         /* We have a cue file, but no valid vcd file yet */
878         char filename[1024];
879         char type[16];
880         int i_temp = sscanf( line, "FILE \"%1023[^\"]\" %15s", filename, type );
881         *p_pos = 0;
882         switch( i_temp )
883         {
884             case 2:
885                 msg_Dbg( p_this, "the cue file says the data file is %s", type );
886                 if( strcasecmp( type, "BINARY" ) )
887                     goto error; /* Error if not binary, otherwise treat as case 1 */
888             case 1:
889                 if( p_vcddev->i_vcdimage_handle == -1 )
890                 {
891                     msg_Dbg( p_this, "we could not find the data file, but we found a new path" );
892                     free( psz_vcdfile);
893                     if( *filename != '/' && ((p_pos = strrchr( psz_cuefile, '/' ))
894                         || (p_pos = strrchr( psz_cuefile, '\\' ) )) )
895                     {
896                         psz_vcdfile = malloc( strlen(filename) +
897                                       (p_pos - psz_cuefile + 1) + 1 );
898                         strncpy( psz_vcdfile, psz_cuefile, (p_pos - psz_cuefile + 1) );
899                         strcpy( psz_vcdfile + (p_pos - psz_cuefile + 1), filename );
900                     } else psz_vcdfile = strdup( filename );
901                     msg_Dbg( p_this,"using vcd image file: %s", psz_vcdfile );
902                     p_vcddev->i_vcdimage_handle = utf8_open( psz_vcdfile,
903                                         O_RDONLY | O_NONBLOCK | O_BINARY, 0666 );
904                 }
905                 b_found = true;
906             default:
907                 break;
908         }
909     }
910
911     if( p_vcddev->i_vcdimage_handle == -1)
912         goto error;
913
914     /* Try to parse the i_tracks and p_sectors info so we can just forget
915      * about the cuefile */
916     size_t i_tracks = 0;
917
918     while( fgets( line, 1024, cuefile ) && i_tracks < INT_MAX-1 )
919     {
920         /* look for a TRACK line */
921         char psz_dummy[9];
922         if( !sscanf( line, "%9s", psz_dummy ) || strcmp(psz_dummy, "TRACK") )
923             continue;
924
925         /* look for an INDEX line */
926         while( fgets( line, 1024, cuefile ) )
927         {
928             int i_num, i_min, i_sec, i_frame;
929
930             if( (sscanf( line, "%*9s %2u %2u:%2u:%2u", &i_num,
931                          &i_min, &i_sec, &i_frame ) != 4) || (i_num != 1) )
932                 continue;
933
934             int *buf = realloc (p_sectors, (i_tracks + 1) * sizeof (*buf));
935             if (buf == NULL)
936                 goto error;
937             p_sectors = buf;
938             p_sectors[i_tracks] = MSF_TO_LBA(i_min, i_sec, i_frame);
939             msg_Dbg( p_this, "vcd track %i begins at sector:%i",
940                      (int)i_tracks, (int)p_sectors[i_tracks] );
941             i_tracks++;
942             break;
943         }
944     }
945
946     /* fill in the last entry */
947     int *buf = realloc (p_sectors, (i_tracks + 1) * sizeof (*buf));
948     if (buf == NULL)
949         goto error;
950     p_sectors = buf;
951     p_sectors[i_tracks] = lseek(p_vcddev->i_vcdimage_handle, 0, SEEK_END)
952                                  / VCD_SECTOR_SIZE;
953     msg_Dbg( p_this, "vcd track %i, begins at sector:%i",
954              (int)i_tracks, (int)p_sectors[i_tracks] );
955     p_vcddev->i_tracks = ++i_tracks;
956     p_vcddev->p_sectors = p_sectors;
957     i_ret = 0;
958
959 error:
960     if( cuefile ) fclose( cuefile );
961     free( p_sectors );
962     free( psz_cuefile );
963     free( psz_vcdfile );
964
965     return i_ret;
966 }
967
968 /****************************************************************************
969  * CloseVCDImage: closes a vcd image opened by OpenVCDImage
970  ****************************************************************************/
971 static void CloseVCDImage( vlc_object_t * p_this, vcddev_t *p_vcddev )
972 {
973     VLC_UNUSED( p_this );
974     if( p_vcddev->i_vcdimage_handle != -1 )
975         close( p_vcddev->i_vcdimage_handle );
976     else
977         return;
978
979     free( p_vcddev->p_sectors );
980 }
981
982 #if defined( __APPLE__ )
983 /****************************************************************************
984  * darwin_getTOC: get the TOC
985  ****************************************************************************/
986 static CDTOC *darwin_getTOC( vlc_object_t * p_this, const vcddev_t *p_vcddev )
987 {
988     mach_port_t port;
989     char *psz_devname;
990     kern_return_t ret;
991     CDTOC *pTOC = NULL;
992     io_iterator_t iterator;
993     io_registry_entry_t service;
994     CFMutableDictionaryRef properties;
995     CFDataRef data;
996
997     /* get the device name */
998     if( ( psz_devname = strrchr( p_vcddev->psz_dev, '/') ) != NULL )
999         ++psz_devname;
1000     else
1001         psz_devname = p_vcddev->psz_dev;
1002
1003     /* unraw the device name */
1004     if( *psz_devname == 'r' )
1005         ++psz_devname;
1006
1007     /* get port for IOKit communication */
1008     if( ( ret = IOMasterPort( MACH_PORT_NULL, &port ) ) != KERN_SUCCESS )
1009     {
1010         msg_Err( p_this, "IOMasterPort: 0x%08x", ret );
1011         return( NULL );
1012     }
1013
1014     /* get service iterator for the device */
1015     if( ( ret = IOServiceGetMatchingServices(
1016                     port, IOBSDNameMatching( port, 0, psz_devname ),
1017                     &iterator ) ) != KERN_SUCCESS )
1018     {
1019         msg_Err( p_this, "IOServiceGetMatchingServices: 0x%08x", ret );
1020         return( NULL );
1021     }
1022
1023     /* first service */
1024     service = IOIteratorNext( iterator );
1025     IOObjectRelease( iterator );
1026
1027     /* search for kIOCDMediaClass */
1028     while( service && !IOObjectConformsTo( service, kIOCDMediaClass ) )
1029     {
1030         if( ( ret = IORegistryEntryGetParentIterator( service,
1031                         kIOServicePlane, &iterator ) ) != KERN_SUCCESS )
1032         {
1033             msg_Err( p_this, "IORegistryEntryGetParentIterator: 0x%08x", ret );
1034             IOObjectRelease( service );
1035             return( NULL );
1036         }
1037
1038         IOObjectRelease( service );
1039         service = IOIteratorNext( iterator );
1040         IOObjectRelease( iterator );
1041     }
1042
1043     if( service == NULL )
1044     {
1045         msg_Err( p_this, "search for kIOCDMediaClass came up empty" );
1046         return( NULL );
1047     }
1048
1049     /* create a CF dictionary containing the TOC */
1050     if( ( ret = IORegistryEntryCreateCFProperties( service, &properties,
1051                     kCFAllocatorDefault, kNilOptions ) ) != KERN_SUCCESS )
1052     {
1053         msg_Err( p_this, "IORegistryEntryCreateCFProperties: 0x%08x", ret );
1054         IOObjectRelease( service );
1055         return( NULL );
1056     }
1057
1058     /* get the TOC from the dictionary */
1059     if( ( data = (CFDataRef) CFDictionaryGetValue( properties,
1060                                     CFSTR(kIOCDMediaTOCKey) ) ) != NULL )
1061     {
1062         CFRange range;
1063         CFIndex buf_len;
1064
1065         buf_len = CFDataGetLength( data ) + 1;
1066         range = CFRangeMake( 0, buf_len );
1067
1068         if( ( pTOC = malloc( buf_len ) ) != NULL )
1069         {
1070             CFDataGetBytes( data, range, (u_char *)pTOC );
1071         }
1072     }
1073     else
1074     {
1075         msg_Err( p_this, "CFDictionaryGetValue failed" );
1076     }
1077
1078     CFRelease( properties );
1079     IOObjectRelease( service );
1080
1081     return( pTOC );
1082 }
1083
1084 /****************************************************************************
1085  * darwin_getNumberOfTracks: get number of tracks in TOC
1086  ****************************************************************************/
1087 static int darwin_getNumberOfTracks( CDTOC *pTOC, int i_descriptors )
1088 {
1089     u_char track;
1090     int i, i_tracks = 0;
1091     CDTOCDescriptor *pTrackDescriptors = NULL;
1092
1093     pTrackDescriptors = (CDTOCDescriptor *)pTOC->descriptors;
1094
1095     for( i = i_descriptors; i > 0; i-- )
1096     {
1097         track = pTrackDescriptors[i].point;
1098
1099         if( track > CD_MAX_TRACK_NO || track < CD_MIN_TRACK_NO )
1100             continue;
1101
1102         i_tracks++;
1103     }
1104
1105     return( i_tracks );
1106 }
1107 #endif /* __APPLE__ */
1108
1109 #if defined( WIN32 )
1110 /*****************************************************************************
1111  * win32_vcd_open: open vcd drive
1112  *****************************************************************************
1113  * Load and use aspi if it is available, otherwise use IOCTLs on WinNT/2K/XP.
1114  *****************************************************************************/
1115 static int win32_vcd_open( vlc_object_t * p_this, const char *psz_dev,
1116                            vcddev_t *p_vcddev )
1117 {
1118     /* Initializations */
1119     p_vcddev->h_device_handle = NULL;
1120     p_vcddev->i_sid = 0;
1121     p_vcddev->hASPI = 0;
1122     p_vcddev->lpSendCommand = 0;
1123
1124     if( WIN_NT )
1125     {
1126         char psz_win32_drive[7];
1127
1128         msg_Dbg( p_this, "using winNT/2K/XP ioctl layer" );
1129
1130         sprintf( psz_win32_drive, "\\\\.\\%c:", psz_dev[0] );
1131
1132         p_vcddev->h_device_handle = CreateFile( psz_win32_drive, GENERIC_READ,
1133                                             FILE_SHARE_READ | FILE_SHARE_WRITE,
1134                                             NULL, OPEN_EXISTING,
1135                                             FILE_FLAG_NO_BUFFERING |
1136                                             FILE_FLAG_RANDOM_ACCESS, NULL );
1137         return (p_vcddev->h_device_handle == NULL) ? -1 : 0;
1138     }
1139     else
1140     {
1141         HMODULE hASPI = NULL;
1142         long (*lpGetSupport)( void ) = NULL;
1143         long (*lpSendCommand)( void* ) = NULL;
1144         DWORD dwSupportInfo;
1145         int i, j, i_hostadapters;
1146         char c_drive = psz_dev[0];
1147
1148         hASPI = LoadLibrary( "wnaspi32.dll" );
1149         if( hASPI != NULL )
1150         {
1151             lpGetSupport = (void *)GetProcAddress( hASPI, "GetASPI32SupportInfo" );
1152             lpSendCommand = (void *)GetProcAddress( hASPI, "SendASPI32Command" );
1153         }
1154
1155         if( hASPI == NULL || lpGetSupport == NULL || lpSendCommand == NULL )
1156         {
1157             msg_Dbg( p_this,
1158                      "unable to load aspi or get aspi function pointers" );
1159             if( hASPI ) FreeLibrary( hASPI );
1160             return -1;
1161         }
1162
1163         /* ASPI support seems to be there */
1164
1165         dwSupportInfo = lpGetSupport();
1166
1167         if( HIBYTE( LOWORD ( dwSupportInfo ) ) == SS_NO_ADAPTERS )
1168         {
1169             msg_Dbg( p_this, "no host adapters found (aspi)" );
1170             FreeLibrary( hASPI );
1171             return -1;
1172         }
1173
1174         if( HIBYTE( LOWORD ( dwSupportInfo ) ) != SS_COMP )
1175         {
1176             msg_Dbg( p_this, "unable to initalize aspi layer" );
1177             FreeLibrary( hASPI );
1178             return -1;
1179         }
1180
1181         i_hostadapters = LOBYTE( LOWORD( dwSupportInfo ) );
1182         if( i_hostadapters == 0 )
1183         {
1184             FreeLibrary( hASPI );
1185             return -1;
1186         }
1187
1188         c_drive = c_drive > 'Z' ? c_drive - 'a' : c_drive - 'A';
1189
1190         for( i = 0; i < i_hostadapters; i++ )
1191         {
1192           for( j = 0; j < 15; j++ )
1193           {
1194               struct SRB_GetDiskInfo srbDiskInfo;
1195
1196               srbDiskInfo.SRB_Cmd         = SC_GET_DISK_INFO;
1197               srbDiskInfo.SRB_HaId        = i;
1198               srbDiskInfo.SRB_Flags       = 0;
1199               srbDiskInfo.SRB_Hdr_Rsvd    = 0;
1200               srbDiskInfo.SRB_Target      = j;
1201               srbDiskInfo.SRB_Lun         = 0;
1202
1203               lpSendCommand( (void*) &srbDiskInfo );
1204
1205               if( (srbDiskInfo.SRB_Status == SS_COMP) &&
1206                   (srbDiskInfo.SRB_Int13HDriveInfo == c_drive) )
1207               {
1208                   /* Make sure this is a cdrom device */
1209                   struct SRB_GDEVBlock   srbGDEVBlock;
1210
1211                   memset( &srbGDEVBlock, 0, sizeof(struct SRB_GDEVBlock) );
1212                   srbGDEVBlock.SRB_Cmd    = SC_GET_DEV_TYPE;
1213                   srbGDEVBlock.SRB_HaId   = i;
1214                   srbGDEVBlock.SRB_Target = j;
1215
1216                   lpSendCommand( (void*) &srbGDEVBlock );
1217
1218                   if( ( srbGDEVBlock.SRB_Status == SS_COMP ) &&
1219                       ( srbGDEVBlock.SRB_DeviceType == DTYPE_CDROM ) )
1220                   {
1221                       p_vcddev->i_sid = MAKEWORD( i, j );
1222                       p_vcddev->hASPI = (long)hASPI;
1223                       p_vcddev->lpSendCommand = lpSendCommand;
1224                       msg_Dbg( p_this, "using aspi layer" );
1225
1226                       return 0;
1227                   }
1228                   else
1229                   {
1230                       FreeLibrary( hASPI );
1231                       msg_Dbg( p_this, "%c: is not a cdrom drive",
1232                                psz_dev[0] );
1233                       return -1;
1234                   }
1235               }
1236           }
1237         }
1238
1239         FreeLibrary( hASPI );
1240         msg_Dbg( p_this, "unable to get haid and target (aspi)" );
1241
1242     }
1243
1244     return -1;
1245 }
1246
1247 #endif /* WIN32 */
1248
1249 /* */
1250 static void astrcat( char **ppsz_dst, char *psz_src )
1251 {
1252     char *psz_old = *ppsz_dst;
1253
1254     if( !psz_old )
1255     {
1256         *ppsz_dst = strdup( psz_src );
1257     }
1258     else if( psz_src )
1259     {
1260         if( asprintf( ppsz_dst, "%s%s", psz_old, psz_src ) < 0 )
1261             *ppsz_dst = psz_old;
1262         else
1263             free( psz_old );
1264     }
1265 }
1266
1267 /* */
1268 static int CdTextParse( vlc_meta_t ***ppp_tracks, int *pi_tracks,
1269                         const uint8_t *p_buffer, int i_buffer )
1270 {
1271     char *pppsz_info[128][0x10];
1272     int i_track_last = -1;
1273     if( i_buffer < 4 )
1274         return -1;
1275
1276     memset( pppsz_info, 0, sizeof(pppsz_info) );
1277
1278     for( int i = 0; i < (i_buffer-4)/18; i++ )
1279     {
1280         const uint8_t *p_block = &p_buffer[4 + 18*i];
1281         char psz_text[12+1];
1282
1283         const int i_pack_type = p_block[0];
1284         if( i_pack_type < 0x80 || i_pack_type > 0x8f )
1285             continue;
1286
1287         const int i_track_number = (p_block[1] >> 0)&0x7f;
1288         const int i_extension_flag = ( p_block[1] >> 7)& 0x01;
1289         if( i_extension_flag )
1290             continue;
1291
1292         //const int i_sequence_number = p_block[2];
1293         //const int i_charater_position = (p_block[3] >> 0) &0x0f;
1294         //const int i_block_number = (p_block[3] >> 4) &0x07;
1295         /* TODO unicode support
1296          * I need a sample */
1297         //const int i_unicode = ( p_block[3] >> 7)&0x01;
1298         //const int i_crc = (p_block[4+12] << 8) | (p_block[4+13] << 0);
1299
1300         /* */
1301         memcpy( psz_text, &p_block[4], 12 );
1302         psz_text[12] = '\0';
1303
1304         /* */
1305         int i_track =  i_track_number;
1306         char *psz_track = &psz_text[0];
1307         while( i_track <= 127 && psz_track < &psz_text[12] )
1308         {
1309             //fprintf( stderr, "t=%d psz_track=%p end=%p", i_track, psz_track, &psz_text[12] );
1310             if( *psz_track )
1311             {
1312                 astrcat( &pppsz_info[i_track][i_pack_type-0x80], psz_track );
1313                 i_track_last = __MAX( i_track_last, i_track );
1314             }
1315
1316             i_track++;
1317             psz_track += 1 + strlen(psz_track);
1318         }
1319     }
1320
1321     if( i_track_last < 0 )
1322         return -1;
1323
1324     vlc_meta_t **pp_tracks = calloc( i_track_last+1, sizeof(*pp_tracks) );
1325     if( !pp_tracks )
1326         goto exit;
1327
1328     for( int j = 0; j < 0x10; j++ )
1329     {
1330         for( int i = 0; i <= i_track_last; i++ )
1331         {
1332             /* */
1333             if( pppsz_info[i][j] )
1334                 EnsureUTF8( pppsz_info[i][j] );
1335
1336             /* */
1337             const char *psz_default = pppsz_info[0][j];
1338             const char *psz_value = pppsz_info[i][j];
1339
1340             if( !psz_value && !psz_default )
1341                 continue;
1342             vlc_meta_t *p_track = pp_tracks[i];
1343             if( !p_track )
1344             {
1345                 p_track = pp_tracks[i] = vlc_meta_New();
1346                 if( !p_track )
1347                     continue;
1348             }
1349             switch( j )
1350             {
1351             case 0x00: /* Album/Title */
1352                 if( i == 0 )
1353                 {
1354                     vlc_meta_SetAlbum( p_track, psz_value );
1355                 }
1356                 else
1357                 {
1358                     if( psz_value )
1359                         vlc_meta_SetTitle( p_track, psz_value );
1360                     if( psz_default )
1361                         vlc_meta_SetAlbum( p_track, psz_default );
1362                 }
1363                 break;
1364             case 0x01: /* Performer */
1365                 vlc_meta_SetArtist( p_track,
1366                                     psz_value ? psz_value : psz_default );
1367                 break;
1368             case 0x05: /* Messages */
1369                 vlc_meta_SetDescription( p_track,
1370                                          psz_value ? psz_value : psz_default );
1371                 break;
1372             case 0x07: /* Genre */
1373                 vlc_meta_SetGenre( p_track,
1374                                    psz_value ? psz_value : psz_default );
1375                 break;
1376             /* FIXME unsupported:
1377              * 0x02: songwriter
1378              * 0x03: composer
1379              * 0x04: arrenger
1380              * 0x06: disc id */
1381             }
1382         }
1383     }
1384     /* */
1385 exit:
1386     for( int j = 0; j < 0x10; j++ )
1387         for( int i = 0; i <= i_track_last; i++ )
1388             free( pppsz_info[i][j] );
1389
1390     *ppp_tracks = pp_tracks;
1391     *pi_tracks = i_track_last+1;
1392     return pp_tracks ? 0 : -1;
1393 }
1394
1395 #if defined( __APPLE__ ) || \
1396     defined( HAVE_IOC_TOC_HEADER_IN_SYS_CDIO_H ) || \
1397     defined( HAVE_SCSIREQ_IN_SYS_SCSIIO_H )
1398 static int CdTextRead( vlc_object_t *p_object, const vcddev_t *p_vcddev,
1399                        uint8_t **pp_buffer, int *pi_buffer )
1400 {
1401     VLC_UNUSED( p_object );
1402     return -1;
1403 }
1404 #elif defined( WIN32 )
1405 static int CdTextRead( vlc_object_t *p_object, const vcddev_t *p_vcddev,
1406                        uint8_t **pp_buffer, int *pi_buffer )
1407 {
1408     if( p_vcddev->hASPI )
1409     {
1410         msg_Err( p_object, "mode ASPI unsupported for CD-TEXT" );
1411         return -1;
1412     }
1413
1414     CDROM_READ_TOC_EX TOCEx;
1415     memset(&TOCEx, 0, sizeof(TOCEx));
1416     TOCEx.Format = CDROM_READ_TOC_EX_FORMAT_CDTEXT;
1417
1418     const int i_header_size = __MAX( 4, MINIMUM_CDROM_READ_TOC_EX_SIZE );
1419     uint8_t header[i_header_size];
1420     DWORD i_read;
1421     if( !DeviceIoControl( p_vcddev->h_device_handle, IOCTL_CDROM_READ_TOC_EX,
1422                           &TOCEx, sizeof(TOCEx), header, i_header_size, &i_read, 0 ) )
1423         return -1;
1424
1425     const int i_text = 2 + (header[0] << 8) + header[1];
1426     if( i_text <= 4 )
1427         return -1;
1428
1429     /* Read complete CD-TEXT */
1430     uint8_t *p_text = calloc( 1, i_text );
1431     if( !p_text )
1432         return VLC_EGENERIC;
1433
1434     if( !DeviceIoControl( p_vcddev->h_device_handle, IOCTL_CDROM_READ_TOC_EX,
1435                           &TOCEx, sizeof(TOCEx), p_text, i_text, &i_read, 0 ) )
1436     {
1437         free( p_text );
1438         return VLC_EGENERIC;
1439     }
1440
1441     /* */
1442     *pp_buffer = p_text;
1443     *pi_buffer = i_text;
1444     return VLC_SUCCESS;
1445 }
1446 #else
1447 static int CdTextRead( vlc_object_t *p_object, const vcddev_t *p_vcddev,
1448                        uint8_t **pp_buffer, int *pi_buffer )
1449 {
1450     VLC_UNUSED( p_object );
1451
1452     if( p_vcddev->i_device_handle == -1 )
1453         return -1;
1454
1455     struct cdrom_generic_command gc;
1456     uint8_t header[4];
1457
1458     /* Read CD-TEXT size */
1459     memset( header, 0, sizeof(header) );
1460     memset( &gc, 0, sizeof(gc) );
1461     gc.cmd[0] = 0x43;   /* Read TOC */
1462     gc.cmd[1] = 0x02;   /* MSF */
1463     gc.cmd[2] = 5;      /* CD-Text */
1464     gc.cmd[7] = ( sizeof(header) >> 8 ) & 0xff;
1465     gc.cmd[8] = ( sizeof(header) >> 0 ) & 0xff;
1466
1467     gc.buflen = sizeof(header);
1468     gc.buffer = header;
1469     gc.data_direction = CGC_DATA_READ;
1470     gc.timeout = 1000;
1471
1472     if( ioctl( p_vcddev->i_device_handle, CDROM_SEND_PACKET, &gc ) == -1 )
1473         return VLC_EGENERIC;
1474
1475     /* If the size is less than 4 it is an error, if it 4 then
1476      * it means no text data */
1477     const int i_text = 2 + (header[0] << 8) + header[1];
1478     if( i_text <= 4 )
1479         return VLC_EGENERIC;
1480
1481     /* Read complete CD-TEXT */
1482     uint8_t *p_text = calloc( 1, i_text );
1483     if( !p_text )
1484         return VLC_EGENERIC;
1485
1486     memset( &gc, 0, sizeof(gc) );
1487     gc.cmd[0] = 0x43;   /* Read TOC */
1488     gc.cmd[1] = 0x02;   /* MSF */
1489     gc.cmd[2] = 5;      /* CD-Text */
1490     gc.cmd[7] = ( i_text >> 8 ) & 0xff;
1491     gc.cmd[8] = ( i_text >> 0 ) & 0xff;
1492
1493     gc.buflen = i_text;
1494     gc.buffer = p_text;
1495     gc.data_direction = CGC_DATA_READ;
1496     gc.timeout = 1000;
1497
1498     if( ioctl( p_vcddev->i_device_handle, CDROM_SEND_PACKET, &gc ) == -1 )
1499     {
1500         free( p_text );
1501         return VLC_EGENERIC;
1502     }
1503
1504     /* */
1505     *pp_buffer = p_text;
1506     *pi_buffer = i_text;
1507     return VLC_SUCCESS;
1508 }
1509 #endif
1510
1511 int ioctl_GetCdText( vlc_object_t *p_object, const vcddev_t *p_vcddev,
1512                      vlc_meta_t ***ppp_tracks, int *pi_tracks )
1513 {
1514     uint8_t *p_text;
1515     int i_text;
1516
1517     if( p_vcddev->i_vcdimage_handle != -1 )
1518         return -1;
1519
1520     if( CdTextRead( p_object, p_vcddev, &p_text, &i_text ) )
1521         return -1;
1522
1523     CdTextParse( ppp_tracks, pi_tracks, p_text, i_text );
1524     free( p_text );
1525     return 0;
1526 }
1527