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