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