b246ad67c781a4dcbec171c16d4aa503f42b3a5b
[vlc.git] / modules / access / cdda.c
1 /*****************************************************************************
2  * cdda.c : CD digital audio input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2000, 2003 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Gildas Bazin <gbazin@netcourrier.com>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /**
26  * Todo:
27  *   - Improve CDDB support (non-blocking, cache, ...)
28  *   - Fix tracknumber in MRL
29  */
30
31 /*****************************************************************************
32  * Preamble
33  *****************************************************************************/
34
35 #include <vlc/vlc.h>
36 #include <vlc_input.h>
37 #include <vlc_access.h>
38
39 #include <vlc_codecs.h> /* For WAVEHEADER */
40 #include "vcd/cdrom.h"
41
42 #include <vlc_playlist.h>
43
44 #ifdef HAVE_LIBCDDB
45 #include <cddb/cddb.h>
46 #endif
47
48 #ifdef HAVE_ERRNO_H
49 #include <errno.h>
50 #endif
51
52 /*****************************************************************************
53  * Module descriptior
54  *****************************************************************************/
55 static int  Open ( vlc_object_t * );
56 static void Close( vlc_object_t * );
57
58 #define CACHING_TEXT N_("Caching value in ms")
59 #define CACHING_LONGTEXT N_( \
60     "Default caching value for Audio CDs. This " \
61     "value should be set in milliseconds." )
62
63 vlc_module_begin();
64     set_shortname( _("Audio CD"));
65     set_description( _("Audio CD input") );
66     set_capability( "access2", 10 );
67     set_category( CAT_INPUT );
68     set_subcategory( SUBCAT_INPUT_ACCESS );
69     set_callbacks( Open, Close );
70
71     add_usage_hint( N_("[cdda:][device][@[track]]") );
72     add_integer( "cdda-caching", DEFAULT_PTS_DELAY / 1000, NULL, CACHING_TEXT,
73                  CACHING_LONGTEXT, VLC_TRUE );
74
75     add_integer( "cdda-track", -1 , NULL, NULL, NULL, VLC_TRUE );
76         change_internal();
77     add_integer( "cdda-first-sector", -1, NULL, NULL, NULL, VLC_TRUE );
78         change_internal();
79     add_integer( "cdda-last-sector", -1, NULL, NULL, NULL, VLC_TRUE );
80         change_internal();
81
82     add_string( "cddb-server", "freedb.freedb.org", NULL,
83                 N_( "CDDB Server" ), N_( "Address of the CDDB server to use." ),
84                 VLC_TRUE );
85     add_integer( "cddb-port", 8880, NULL,
86                 N_( "CDDB port" ), N_( "CDDB Server port to use." ),
87                 VLC_TRUE );
88     add_shortcut( "cdda" );
89     add_shortcut( "cddasimple" );
90 vlc_module_end();
91
92
93 /* how many blocks VCDRead will read in each loop */
94 #define CDDA_BLOCKS_ONCE 20
95 #define CDDA_DATA_ONCE   (CDDA_BLOCKS_ONCE * CDDA_DATA_SIZE)
96
97 /*****************************************************************************
98  * Access: local prototypes
99  *****************************************************************************/
100 struct access_sys_t
101 {
102     vcddev_t    *vcddev;                            /* vcd device descriptor */
103
104     /* Current position */
105     int         i_sector;                                  /* Current Sector */
106     int *       p_sectors;                                  /* Track sectors */
107
108     /* Wave header for the output data */
109     WAVEHEADER  waveheader;
110     vlc_bool_t  b_header;
111
112     int         i_track;
113     int         i_first_sector;
114     int         i_last_sector;
115
116 #ifdef HAVE_LIBCDDB
117     cddb_disc_t *p_disc;
118 #endif
119 };
120
121 static block_t *Block( access_t * );
122 static int      Seek( access_t *, int64_t );
123 static int      Control( access_t *, int, va_list );
124
125 static int GetTracks( access_t *p_access, playlist_t *p_playlist,
126                       playlist_item_t *p_parent );
127
128 #ifdef HAVE_LIBCDDB
129 static void GetCDDBInfo( access_t *p_access, int i_titles, int *p_sectors );
130 #endif
131
132 /*****************************************************************************
133  * Open: open cdda
134  *****************************************************************************/
135 static int Open( vlc_object_t *p_this )
136 {
137     access_t     *p_access = (access_t*)p_this;
138     access_sys_t *p_sys;
139     vcddev_t *vcddev;
140     char *psz_name;
141     int i_mrl_tracknum = -1;
142     int i_ret;
143
144     if( !p_access->psz_path || !*p_access->psz_path )
145     {
146         /* Only when selected */
147         if( !p_this->b_force ) return VLC_EGENERIC;
148
149         psz_name = var_CreateGetString( p_this, "cd-audio" );
150         if( !psz_name || !*psz_name )
151         {
152             if( psz_name ) free( psz_name );
153             return VLC_EGENERIC;
154         }
155     }
156     else psz_name = strdup( p_access->psz_path );
157
158 #ifdef WIN32
159     if( psz_name[0] && psz_name[1] == ':' &&
160         psz_name[2] == '\\' && psz_name[3] == '\0' ) psz_name[2] = '\0';
161 #endif
162
163     /* Open CDDA */
164     if( (vcddev = ioctl_Open( VLC_OBJECT(p_access), psz_name )) == NULL )
165     {
166         msg_Warn( p_access, "could not open %s", psz_name );
167         free( psz_name );
168         return VLC_EGENERIC;
169     }
170     free( psz_name );
171
172     /* Set up p_access */
173     STANDARD_BLOCK_ACCESS_INIT
174     p_sys->vcddev = vcddev;
175
176    /* Do we play a single track ? */
177    p_sys->i_track = var_CreateGetInteger( p_access, "cdda-track" );
178
179    if( p_sys->i_track < 0 && i_mrl_tracknum <= 0 )
180    {
181         /* We only do separate items if the whole disc is requested */
182         playlist_t *p_playlist = pl_Yield( p_access );
183
184         i_ret = -1;
185         if( p_playlist )
186         {
187             input_thread_t *p_input = (input_thread_t*)vlc_object_find( p_access, VLC_OBJECT_INPUT, FIND_PARENT );
188             if( p_input )
189             {
190                 input_item_t *p_current = input_GetItem( p_input );
191                 playlist_item_t *p_item;
192
193                 if( p_playlist->status.p_item->p_input == p_current )
194                     p_item = p_playlist->status.p_item;
195                 else
196                     p_item = playlist_ItemGetByInput( p_playlist, p_current, VLC_FALSE );
197
198                 if( p_item )
199                     i_ret = GetTracks( p_access, p_playlist, p_item );
200                 else
201                     msg_Dbg( p_playlist, "unable to find item in playlist");
202                 vlc_object_release( p_input );
203             }
204             vlc_object_release( p_playlist );
205         }
206         if( i_ret < 0 )
207             goto error;
208     }
209     else
210     {
211         /* Build a WAV header for the output data */
212         memset( &p_sys->waveheader, 0, sizeof(WAVEHEADER) );
213         SetWLE( &p_sys->waveheader.Format, 1 ); /*WAVE_FORMAT_PCM*/
214         SetWLE( &p_sys->waveheader.BitsPerSample, 16);
215         p_sys->waveheader.MainChunkID = VLC_FOURCC('R', 'I', 'F', 'F');
216         p_sys->waveheader.Length = 0;               /* we just don't know */
217         p_sys->waveheader.ChunkTypeID = VLC_FOURCC('W', 'A', 'V', 'E');
218         p_sys->waveheader.SubChunkID = VLC_FOURCC('f', 'm', 't', ' ');
219         SetDWLE( &p_sys->waveheader.SubChunkLength, 16);
220         SetWLE( &p_sys->waveheader.Modus, 2);
221         SetDWLE( &p_sys->waveheader.SampleFreq, 44100);
222         SetWLE( &p_sys->waveheader.BytesPerSample,
223                     2 /*Modus*/ * 16 /*BitsPerSample*/ / 8 );
224         SetDWLE( &p_sys->waveheader.BytesPerSec,
225                     2*16/8 /*BytesPerSample*/ * 44100 /*SampleFreq*/ );
226         p_sys->waveheader.DataChunkID = VLC_FOURCC('d', 'a', 't', 'a');
227         p_sys->waveheader.DataLength = 0;           /* we just don't know */
228
229         p_sys->i_first_sector = var_CreateGetInteger( p_access,
230                                                       "cdda-first-sector" );
231         p_sys->i_last_sector  = var_CreateGetInteger( p_access,
232                                                       "cdda-last-sector" );
233         /* Tracknumber in MRL */
234         if( p_sys->i_first_sector < 0 || p_sys->i_last_sector < 0 )
235         {
236             int i_titles;
237             if( i_mrl_tracknum <= 0 )
238             {
239                 msg_Err( p_access, "wrong sector information" );
240                 goto error;
241             }
242             i_titles = ioctl_GetTracksMap( VLC_OBJECT(p_access),
243                                             p_sys->vcddev, &p_sys->p_sectors );
244         }
245
246
247         p_sys->i_sector = p_sys->i_first_sector;
248         p_access->info.i_size = (p_sys->i_last_sector - p_sys->i_first_sector)
249                                      * (int64_t)CDDA_DATA_SIZE;
250     }
251
252     /* PTS delay */
253     var_Create( p_access, "cdda-caching", VLC_VAR_INTEGER|VLC_VAR_DOINHERIT );
254
255     return VLC_SUCCESS;
256
257 error:
258     ioctl_Close( VLC_OBJECT(p_access), p_sys->vcddev );
259     free( p_sys );
260     return VLC_EGENERIC;
261 }
262
263 /*****************************************************************************
264  * Close: closes cdda
265  *****************************************************************************/
266 static void Close( vlc_object_t *p_this )
267 {
268     access_t     *p_access = (access_t *)p_this;
269     access_sys_t *p_sys = p_access->p_sys;
270     ioctl_Close( p_this, p_sys->vcddev );
271     free( p_sys );
272 }
273
274 /*****************************************************************************
275  * Block: read data (CDDA_DATA_ONCE)
276  *****************************************************************************/
277 static block_t *Block( access_t *p_access )
278 {
279     access_sys_t *p_sys = p_access->p_sys;
280     int i_blocks = CDDA_BLOCKS_ONCE;
281     block_t *p_block;
282
283     if( p_sys->i_track < 0 ) p_access->info.b_eof = VLC_TRUE;
284
285     /* Check end of file */
286     if( p_access->info.b_eof ) return NULL;
287
288     if( !p_sys->b_header )
289     {
290         /* Return only the header */
291         p_block = block_New( p_access, sizeof( WAVEHEADER ) );
292         memcpy( p_block->p_buffer, &p_sys->waveheader, sizeof(WAVEHEADER) );
293         p_sys->b_header = VLC_TRUE;
294         return p_block;
295     }
296
297     if( p_sys->i_sector >= p_sys->i_last_sector )
298     {
299         p_access->info.b_eof = VLC_TRUE;
300         return NULL;
301     }
302
303     /* Don't read too far */
304     if( p_sys->i_sector + i_blocks >= p_sys->i_last_sector )
305         i_blocks = p_sys->i_last_sector - p_sys->i_sector;
306
307     /* Do the actual reading */
308     if( !( p_block = block_New( p_access, i_blocks * CDDA_DATA_SIZE ) ) )
309     {
310         msg_Err( p_access, "cannot get a new block of size: %i",
311                  i_blocks * CDDA_DATA_SIZE );
312         return NULL;
313     }
314
315     if( ioctl_ReadSectors( VLC_OBJECT(p_access), p_sys->vcddev,
316             p_sys->i_sector, p_block->p_buffer, i_blocks, CDDA_TYPE ) < 0 )
317     {
318         msg_Err( p_access, "cannot read sector %i", p_sys->i_sector );
319         block_Release( p_block );
320
321         /* Try to skip one sector (in case of bad sectors) */
322         p_sys->i_sector++;
323         p_access->info.i_pos += CDDA_DATA_SIZE;
324         return NULL;
325     }
326
327     /* Update a few values */
328     p_sys->i_sector += i_blocks;
329     p_access->info.i_pos += p_block->i_buffer;
330
331     return p_block;
332 }
333
334 /****************************************************************************
335  * Seek
336  ****************************************************************************/
337 static int Seek( access_t *p_access, int64_t i_pos )
338 {
339     access_sys_t *p_sys = p_access->p_sys;
340
341     /* Next sector to read */
342     p_sys->i_sector = p_sys->i_first_sector + i_pos / CDDA_DATA_SIZE;
343     p_access->info.i_pos = i_pos;
344
345     return VLC_SUCCESS;
346 }
347
348 /*****************************************************************************
349  * Control:
350  *****************************************************************************/
351 static int Control( access_t *p_access, int i_query, va_list args )
352 {
353     vlc_bool_t   *pb_bool;
354     int          *pi_int;
355     int64_t      *pi_64;
356
357     switch( i_query )
358     {
359         case ACCESS_CAN_SEEK:
360         case ACCESS_CAN_FASTSEEK:
361         case ACCESS_CAN_PAUSE:
362         case ACCESS_CAN_CONTROL_PACE:
363             pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t* );
364             *pb_bool = VLC_TRUE;
365             break;
366
367         case ACCESS_GET_MTU:
368             pi_int = (int*)va_arg( args, int * );
369             *pi_int = CDDA_DATA_ONCE;
370             break;
371
372         case ACCESS_GET_PTS_DELAY:
373             pi_64 = (int64_t*)va_arg( args, int64_t * );
374             *pi_64 = var_GetInteger( p_access, "cdda-caching" ) * 1000;
375             break;
376
377         case ACCESS_SET_PAUSE_STATE:
378         case ACCESS_GET_TITLE_INFO:
379         case ACCESS_SET_TITLE:
380         case ACCESS_GET_META:
381         case ACCESS_SET_SEEKPOINT:
382         case ACCESS_SET_PRIVATE_ID_STATE:
383             return VLC_EGENERIC;
384
385         default:
386             msg_Warn( p_access, "unimplemented query in control" );
387             return VLC_EGENERIC;
388
389     }
390     return VLC_SUCCESS;
391 }
392
393 static int GetTracks( access_t *p_access,
394                       playlist_t *p_playlist, playlist_item_t *p_parent )
395 {
396     access_sys_t *p_sys = p_access->p_sys;
397     int i, i_titles;
398     input_item_t *p_input_item;
399     playlist_item_t *p_item_in_category;
400     char *psz_name;
401     i_titles = ioctl_GetTracksMap( VLC_OBJECT(p_access),
402                                    p_sys->vcddev, &p_sys->p_sectors );
403     if( i_titles < 0 )
404     {
405         msg_Err( p_access, "unable to count tracks" );
406         return VLC_EGENERIC;;
407     }
408     else if( i_titles <= 0 )
409     {
410         msg_Err( p_access, "no audio tracks found" );
411         return VLC_EGENERIC;
412     }
413
414     p_item_in_category = playlist_ItemToNode( p_playlist, p_parent, VLC_FALSE );
415     playlist_ItemSetName( p_parent, "Audio CD" );
416     var_SetInteger( p_playlist, "item-change", p_parent->p_input->i_id );
417
418 #ifdef HAVE_LIBCDDB
419     GetCDDBInfo( p_access, i_titles, p_sys->p_sectors );
420     if( p_sys->p_disc )
421     {
422         if( cddb_disc_get_title( p_sys->p_disc ) )
423         {
424             const char *psz_name = cddb_disc_get_title( p_sys->p_disc );
425             playlist_ItemSetName( p_parent, psz_name );
426             var_SetInteger( p_playlist, "item-change",
427                             p_parent->p_input->i_id );
428         }
429     }
430 #endif
431
432     /* Build title table */
433     for( i = 0; i < i_titles; i++ )
434     {
435         msg_Dbg( p_access, "track[%d] start=%d", i, p_sys->p_sectors[i] );
436         char *psz_uri, *psz_opt, *psz_first, *psz_last;
437         int i_path_len = p_access->psz_path ? strlen( p_access->psz_path ) : 0;
438
439         psz_name = (char*)malloc( strlen( _("Audio CD - Track ") ) + 5 );
440         psz_opt = (char*)malloc( strlen( "cdda-track=" ) + 3 );
441         psz_first = (char*)malloc( strlen( "cdda-first-sector=" ) + 7 );
442         psz_last = (char*)malloc( strlen( "cdda-last-sector=" ) + 7 );
443         psz_uri = (char*)malloc( i_path_len + 13 );
444
445         snprintf( psz_uri, i_path_len + 13, "cdda://%s",
446                            p_access->psz_path ? p_access->psz_path : "" );
447         sprintf( psz_opt, "cdda-track=%i", i+1 );
448         sprintf( psz_first, "cdda-first-sector=%i",p_sys->p_sectors[i] );
449
450 //        if( i != i_titles -1 )
451             sprintf( psz_last, "cdda-last-sector=%i", p_sys->p_sectors[i+1] );
452 //         else
453 //            sprintf( psz_last, "cdda-last-sector=%i", 1242 /* FIXME */);
454
455         /* Define a "default name" */
456         sprintf( psz_name, _("Audio CD - Track %i"), (i+1) );
457
458         /* Create playlist items */
459         p_input_item = input_ItemNewWithType( VLC_OBJECT( p_playlist ),
460                                               psz_uri, psz_name, 0, NULL, -1,
461                                               ITEM_TYPE_DISC );
462         input_ItemAddOption( p_input_item, psz_first );
463         input_ItemAddOption( p_input_item, psz_last );
464         input_ItemAddOption( p_input_item, psz_opt );
465
466 #ifdef HAVE_LIBCDDB
467         /* If we have CDDB info, change the name */
468         if( p_sys->p_disc )
469         {
470             const char *psz_result;
471             cddb_track_t *t = cddb_disc_get_track( p_sys->p_disc, i );
472             if( t!= NULL )
473             {
474                 if( cddb_track_get_title( t )  != NULL )
475                 {
476                     input_ItemAddInfo( p_input_item, _(VLC_META_INFO_CAT),
477                                             _(VLC_META_TITLE),
478                                             "%s", cddb_track_get_title( t ) );
479                     if( p_input_item->psz_name )
480                         free( p_input_item->psz_name );
481                     p_input_item->psz_name = strdup( cddb_track_get_title( t ) );
482                 }
483                 psz_result = cddb_track_get_artist( t );
484                 if( psz_result )
485                 {
486                     input_ItemAddInfo( p_input_item, _(VLC_META_INFO_CAT),
487                                        _(VLC_META_ARTIST), "%s", psz_result );
488                 }
489             }
490         }
491 #endif
492         playlist_BothAddInput( p_playlist, p_input_item, p_item_in_category,
493                                PLAYLIST_APPEND, PLAYLIST_END, NULL, NULL,
494                                VLC_FALSE );
495         free( psz_uri ); free( psz_opt ); free( psz_name );
496         free( psz_first ); free( psz_last );
497     }
498     return VLC_SUCCESS;
499 }
500
501 #ifdef HAVE_LIBCDDB
502 static void GetCDDBInfo( access_t *p_access, int i_titles, int *p_sectors )
503 {
504     int i, i_matches;
505     int64_t  i_length = 0, i_size = 0;
506     cddb_conn_t  *p_cddb = cddb_new();
507
508     if( !p_cddb )
509     {
510         msg_Warn( p_access, "unable to use CDDB" );
511         goto cddb_destroy;
512     }
513
514     cddb_set_email_address( p_cddb, "vlc@videolan.org" );
515     cddb_set_server_name( p_cddb, config_GetPsz( p_access, "cddb-server" ) );
516     cddb_set_server_port( p_cddb, config_GetInt( p_access, "cddb-port" ) );
517
518     /// \todo
519     cddb_cache_disable( p_cddb );
520
521 //    cddb_cache_set_dir( p_cddb,
522 //                     config_GetPsz( p_access,
523 //                                    MODULE_STRING "-cddb-cachedir") );
524
525     cddb_set_timeout( p_cddb, 10 );
526
527     /// \todo
528     cddb_http_disable( p_cddb);
529
530     p_access->p_sys->p_disc = cddb_disc_new();
531
532     if(! p_access->p_sys->p_disc )
533     {
534         msg_Err( p_access, "unable to create CDDB disc structure." );
535         goto cddb_end;
536     }
537
538     for(i = 0; i < i_titles ; i++ )
539     {
540         cddb_track_t *t = cddb_track_new();
541         cddb_track_set_frame_offset(t, p_sectors[i] );
542         cddb_disc_add_track( p_access->p_sys->p_disc, t );
543         i_size = ( p_sectors[i+1] - p_sectors[i] ) *
544                    (int64_t)CDDA_DATA_SIZE;
545         i_length += I64C(1000000) * i_size / 44100 / 4  ;
546     }
547
548     cddb_disc_set_length( p_access->p_sys->p_disc, (int)(i_length/1000000) );
549
550     if (!cddb_disc_calc_discid(p_access->p_sys->p_disc ))
551     {
552         msg_Err( p_access, "CDDB disc ID calculation failed" );
553         goto cddb_destroy;
554     }
555
556     i_matches = cddb_query( p_cddb, p_access->p_sys->p_disc);
557
558     if (i_matches > 0)
559     {
560         if (i_matches > 1)
561              msg_Warn( p_access, "found %d matches in CDDB. Using first one.",
562                                  i_matches);
563         cddb_read( p_cddb, p_access->p_sys->p_disc );
564     }
565     else
566         msg_Warn( p_access, "CDDB error: %s", cddb_error_str(errno));
567
568 cddb_destroy:
569     cddb_destroy( p_cddb);
570
571 cddb_end: ;
572 }
573 #endif /*HAVE_LIBCDDB*/