]> git.sesse.net Git - vlc/blob - modules/access/cdda/access.c
First attempt to reinstate a libcdio cdda.
[vlc] / modules / access / cdda / access.c
1 /*****************************************************************************
2  * cddax.c : CD digital audio input module for vlc using libcdio
3  *****************************************************************************
4  * Copyright (C) 2000, 2003, 2004 VideoLAN
5  * $Id$
6  *
7  * Authors: Rocky Bernstein <rocky@panix.com>
8  *          Laurent Aimar <fenrir@via.ecp.fr>
9  *          Gildas Bazin <gbazin@netcourrier.com>
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., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #include <stdio.h>
30 #include <stdlib.h>
31
32 #include <vlc/vlc.h>
33 #include <vlc/input.h>
34
35 #include <sys/types.h>
36 #include <cdio/cdio.h>
37 #include <cdio/cd_types.h>
38
39 #include "codecs.h"
40 #include "vlc_keys.h"
41
42 #ifdef HAVE_UNISTD_H
43 #   include <unistd.h>
44 #endif
45
46 #ifdef HAVE_ERRNO_H
47 #   include <errno.h>
48 #endif
49
50 #include <string.h>
51
52 #include "cdda.h"
53
54 /* how many blocks Open will read in each loop */
55 #define CDDA_BLOCKS_ONCE 20
56 #define CDDA_DATA_ONCE   (CDDA_BLOCKS_ONCE * CDIO_CD_FRAMESIZE_RAW)
57
58 #define CDDA_MRL_PREFIX "cddax://"
59
60 /* FIXME: This variable is a hack. Would be nice to eliminate. */
61 static access_t *p_cdda_input = NULL;
62
63 /*****************************************************************************
64  * Local prototypes
65  *****************************************************************************/
66 static block_t *CDDABlock( access_t * p_access );
67 static int      CDDASeek( access_t * p_access, int64_t i_pos );
68 static int      CDDAControl( access_t *p_access, int i_query, 
69                              va_list args );
70 static void     CDDAMetaInfo( access_t *p_access  );
71
72 /****************************************************************************
73  * Private functions
74  ****************************************************************************/
75
76 /* process messages that originate from libcdio. */
77 static void
78 cdio_log_handler (cdio_log_level_t level, const char message[])
79 {
80   cdda_data_t *p_cdda = (cdda_data_t *)p_cdda_input->p_sys;
81   switch (level) {
82   case CDIO_LOG_DEBUG:
83   case CDIO_LOG_INFO:
84     if (p_cdda->i_debug & INPUT_DBG_CDIO)
85       msg_Dbg( p_cdda_input, message);
86     break;
87   case CDIO_LOG_WARN:
88     msg_Warn( p_cdda_input, message);
89     break;
90   case CDIO_LOG_ERROR:
91   case CDIO_LOG_ASSERT:
92     msg_Err( p_cdda_input, message);
93     break;
94   default:
95     msg_Warn( p_cdda_input, message,
96             _("The above message had unknown cdio log level"),
97             level);
98   }
99   return;
100 }
101
102
103 #ifdef HAVE_LIBCDDB
104 /*! This routine is called by libcddb routines on error.
105    Setup is done by init_input_plugin.
106 */
107 static void
108 cddb_log_handler (cddb_log_level_t level, const char message[])
109 {
110   cdda_data_t *p_cdda = (cdda_data_t *)p_cdda_input->p_sys;
111   switch (level) {
112   case CDDB_LOG_DEBUG:
113   case CDDB_LOG_INFO:
114     if (!(p_cdda->i_debug & INPUT_DBG_CDDB)) return;
115     /* Fall through if to warn case */
116   default:
117     cdio_log_handler (level, message);
118   }
119 }
120 #endif /*HAVE_LIBCDDB*/
121
122
123 /*! This routine is when xine is not fully set up (before full initialization)
124    or is not around (before finalization).
125 */
126 static void
127 uninit_log_handler (cdio_log_level_t level, const char message[])
128 {
129   cdda_data_t *p_cdda = (cdda_data_t *)p_cdda_input->p_sys;
130   switch (level) {
131   case CDIO_LOG_DEBUG:
132   case CDIO_LOG_INFO:
133     if (!(p_cdda->i_debug & (INPUT_DBG_CDIO|INPUT_DBG_CDDB)))
134       return;
135     /* Fall through if to warn case */
136   case CDIO_LOG_WARN:
137     fprintf(stderr, "WARN: %s\n", message);
138     break;
139   case CDIO_LOG_ERROR:
140     fprintf(stderr, "ERROR: %s\n", message);
141     break;
142   case CDIO_LOG_ASSERT:
143     fprintf(stderr, "ASSERT ERROR: %s\n", message);
144     break;
145   default:
146     fprintf(stderr, "UNKNOWN ERROR: %s\n%s %d\n",
147             message,
148             _("The above message had unknown cdio log level"),
149             level);
150   }
151
152   /* gl_default_cdio_log_handler (level, message); */
153 }
154
155 /*****************************************************************************
156  * CDDARead: reads CDDA_BLOCKS_ONCE from the CD-DA and returns an
157  * allocated pointer to the data. NULL is returned if no data read. It
158  * is also possible if we haven't read a RIFF header in which case one 
159  * that we creaded during Open/Initialization is returned.
160  *****************************************************************************/
161 static block_t *
162 CDDABlock( access_t * p_access )
163 {
164     block_t     *p_block;
165     cdda_data_t *p_cdda   = (cdda_data_t *) p_access->p_sys;
166     int          i_blocks = CDDA_BLOCKS_ONCE;
167
168     dbg_print((INPUT_DBG_CALL|INPUT_DBG_EXT|INPUT_DBG_LSN), "called %d", 
169               p_cdda->i_sector);
170
171     /* Check end of file */
172     if( p_access->info.b_eof ) return NULL;
173
174     if( !p_cdda->b_header )
175       {
176         /* Return only the dummy RIFF header we created in Open/Init */
177         p_block = block_New( p_access, sizeof( WAVEHEADER ) );
178         memcpy( p_block->p_buffer, &p_cdda->waveheader, sizeof(WAVEHEADER) );
179         p_cdda->b_header = VLC_TRUE;
180         return p_block;
181     }
182
183     /* Check end of track */
184     while( p_cdda->i_sector >= p_cdda->p_sectors[p_access->info.i_title + 1] )
185     {
186         if( p_access->info.i_title + 1 >= p_cdda->i_tracks )
187         {
188             p_access->info.b_eof = VLC_TRUE;
189             return NULL;
190         }
191
192         p_access->info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SIZE;
193         p_access->info.i_title++;
194         p_access->info.i_size = 
195           p_cdda->p_title[p_access->info.i_title]->i_size;
196         p_access->info.i_pos = 0;
197     }
198
199     /* Don't read after the end of a title */
200     if( p_cdda->i_sector + i_blocks >=
201         p_cdda->p_sectors[p_access->info.i_title + 1] )
202     {
203         i_blocks = p_cdda->p_sectors[p_access->info.i_title + 1 ] -
204                    p_cdda->i_sector;
205     }
206
207     /* Do the actual reading */
208     p_block = block_New( p_access, i_blocks * CDIO_CD_FRAMESIZE_RAW );
209     if( !p_block)
210     {
211         msg_Err( p_access, "cannot get a new block of size: %i",
212                  i_blocks * CDIO_CD_FRAMESIZE_RAW );
213         return NULL;
214     }
215
216     if( cdio_read_audio_sectors( p_cdda->p_cddev->cdio, p_block->p_buffer,
217                                  p_cdda->i_sector, i_blocks) != 0 )
218         {
219             msg_Err( p_access, "could not read sector %lu", 
220                      (long unsigned int) p_cdda->i_sector );
221             block_Release( p_block );
222
223             /* If we had problems above, assume the problem is with
224                the first sector of the read and set to skip it.  In
225                the future libcdio may have cdparanoia support.
226              */
227             p_cdda->i_sector++;
228             p_access->info.i_pos += CDIO_CD_FRAMESIZE_RAW;
229             return NULL;
230         }
231
232     p_cdda->i_sector     += i_blocks;
233     p_access->info.i_pos += p_block->i_buffer;
234
235     return p_block;
236 }
237
238 /****************************************************************************
239  * CDDASeek - change position for subsequent reads. For example, this
240  * can happen if the user moves a position slider bar in a GUI.
241  ****************************************************************************/
242 static int 
243 CDDASeek( access_t * p_access, int64_t i_pos )
244 {
245     cdda_data_t *p_cdda = (cdda_data_t *) p_access->p_sys;
246
247     p_cdda->i_sector = p_cdda->p_sectors[p_access->info.i_title]
248                        + i_pos / CDIO_CD_FRAMESIZE_RAW;
249     p_access->info.i_pos = i_pos;
250
251     dbg_print( (INPUT_DBG_CALL|INPUT_DBG_EXT|INPUT_DBG_SEEK),
252                "sector %lu, offset: %lld",  
253                (long unsigned int) p_cdda->i_sector, i_pos );
254     return VLC_SUCCESS;
255 }
256
257 #ifdef HAVE_LIBCDDB
258
259 #define free_and_dup(var, val) \
260   if (var) free(var);          \
261   if (val) var=strdup(val);
262
263
264 static void
265 GetCDDBInfo( access_t *p_access, cdda_data_t *p_cdda )
266 {
267
268   dbg_print( (INPUT_DBG_CALL|INPUT_DBG_EXT), "" );
269
270   if (config_GetInt( p_access, MODULE_STRING "-cddb-enabled" )) {
271     int i, i_matches;
272     cddb_conn_t  *conn = cddb_new();
273     const CdIo *p_cdio = p_cdda->p_cddev->cdio;
274
275
276     cddb_log_set_handler (uninit_log_handler);
277
278     if (!conn) {
279       msg_Warn( p_access, "unable to initialize libcddb" );
280       goto cddb_destroy;
281     }
282
283     cddb_set_email_address( conn,
284                             config_GetPsz( p_access,
285                                            MODULE_STRING "-cddb-email") );
286
287     cddb_set_server_name( conn,
288                           config_GetPsz( p_access,
289                                          MODULE_STRING "-cddb-server") );
290
291     cddb_set_server_port(conn,
292                           config_GetInt( p_access,
293                                          MODULE_STRING "-cddb-port") );
294
295     /* Set the location of the local CDDB cache directory.
296        The default location of this directory is */
297
298     if (!config_GetInt( p_access, MODULE_STRING "-cddb-enable-cache" ))
299       cddb_cache_disable(conn);
300
301     cddb_cache_set_dir(conn,
302                        config_GetPsz( p_access,
303                                       MODULE_STRING "-cddb-cachedir") );
304
305     cddb_set_timeout(conn,
306                      config_GetInt( p_access, MODULE_STRING "-cddb-timeout") );
307
308
309     if (config_GetInt( p_access, MODULE_STRING "-cddb-httpd" )) {
310       cddb_http_enable(conn);
311     } else
312       cddb_http_disable(conn);
313
314     p_cdda->cddb.disc = cddb_disc_new();
315     if (!p_cdda->cddb.disc) {
316       msg_Err( p_access, "Unable to create CDDB disc structure." );
317       goto cddb_end;
318     }
319
320     p_cdda->psz_mcn = cdio_get_mcn(p_cdio);
321
322     for(i = 1; i <= p_cdda->i_tracks; i++) {
323       cddb_track_t *t = cddb_track_new();
324       t->frame_offset = cdio_get_track_lba(p_cdio, i);
325       cddb_disc_add_track(p_cdda->cddb.disc, t);
326     }
327
328     p_cdda->cddb.disc->length =
329       cdio_get_track_lba(p_cdio, CDIO_CDROM_LEADOUT_TRACK)
330       / CDIO_CD_FRAMES_PER_SEC;
331
332     if (!cddb_disc_calc_discid(p_cdda->cddb.disc)) {
333       msg_Err( p_access, "CDDB disc calc failed" );
334       goto cddb_destroy;
335     }
336
337     i_matches = cddb_query(conn, p_cdda->cddb.disc);
338     if (i_matches > 0) {
339       if (i_matches > 1)
340         msg_Warn( p_access, "Found %d matches in CDDB. Using first one.",
341                   i_matches);
342       cddb_read(conn, p_cdda->cddb.disc);
343
344       if (p_cdda->i_debug & INPUT_DBG_CDDB)
345         cddb_disc_print(p_cdda->cddb.disc);
346
347     } else {
348       msg_Warn( p_access, "CDDB error: %s", cddb_error_str(errno));
349     }
350
351   cddb_destroy:
352     cddb_destroy(conn);
353   }
354   cddb_end: ;
355 }
356 #endif /*HAVE_LIBCDDB*/
357
358 #define add_meta_val(FIELD, VLC_META, VAL)                              \
359   if ( p_cdda->p_meta ) {                                               \
360     vlc_meta_Add( p_cdda->p_meta, VLC_META, VAL );                      \
361     dbg_print( INPUT_DBG_META, "field %s: %s\n", VLC_META, VAL );       \
362   }                                                                     \
363     
364 #define add_cddb_meta(FIELD, VLC_META)                                  \
365   add_meta_val(FIELD, VLC_META, p_cdda->cddb.disc->FIELD);
366     
367 #define add_cddb_meta_fmt(FIELD, FORMAT_SPEC, VLC_META)                 \
368   {                                                                     \
369     char psz_buf[100];                                                  \
370     snprintf( psz_buf, sizeof(psz_buf)-1, FORMAT_SPEC,                  \
371               p_cdda->cddb.disc->FIELD );                               \
372     psz_buf[sizeof(psz_buf)-1] = '\0';                                  \
373     add_meta_val(FIELD, VLC_META, psz_buf);                             \
374   }    
375
376 /*
377  Gets and saves CDDA Meta Information. In the Control routine, 
378  we handle Meta Information requests and basically copy what we've
379  saved here. 
380  */    
381 static void CDDAMetaInfo( access_t *p_access  )
382 {
383   cdda_data_t *p_cdda = (cdda_data_t *) p_access->p_sys;
384
385 #ifdef HAVE_LIBCDDB
386   if ( p_cdda && p_cdda->i_cddb_enabled ) {
387
388     GetCDDBInfo(p_access, p_cdda);
389
390     if ( p_cdda->cddb.disc ) {
391
392       p_cdda->p_meta = vlc_meta_New();
393
394       add_cddb_meta(title,    VLC_META_CDDB_TITLE);
395       add_cddb_meta(artist,   VLC_META_CDDB_ARTIST);
396       add_cddb_meta(genre,    VLC_META_CDDB_GENRE);
397       add_cddb_meta(ext_data, VLC_META_CDDB_EXT_DATA);
398
399       add_cddb_meta_fmt(year,   "%d", VLC_META_CDDB_YEAR);
400       add_cddb_meta_fmt(discid, "%x", VLC_META_CDDB_DISCID);
401     }
402   }
403
404 #endif /*HAVE_LIBCDDB*/
405 #define TITLE_MAX 30
406
407 #if UPDATE_TRACK_INFORMATION_FINISHED
408   {
409     track_t i_track = p_cdda->i_tracks;
410     char psz_buffer[MSTRTIME_MAX_SIZE];
411     mtime_t i_duration =
412       (p_cdda->p_sectors[i_track] - p_cdda->p_sectors[0])
413       / CDIO_CD_FRAMES_PER_SEC;
414
415     dbg_print( INPUT_DBG_META, "Duration %ld", (long int) i_duration );
416     input_Control( p_access, INPUT_ADD_INFO, _("General"), _("Duration"), "%s",
417                    secstotimestr( psz_buffer, i_duration ) );
418
419     for( i_track = 0 ; i_track < p_cdda->i_tracks ; i_track++ ) {
420       char track_str[TITLE_MAX];
421       mtime_t i_duration =
422         (p_cdda->p_sectors[i_track+1] - p_cdda->p_sectors[i_track])
423         / CDIO_CD_FRAMES_PER_SEC;
424       snprintf(track_str, TITLE_MAX, "%s %02d", _("Track"), i_track+1);
425       input_Control( p_access, INPUT_ADD_INFO, track_str, _("Duration"), "%s",
426                      secstotimestr( psz_buffer, i_duration ) );
427
428 #ifdef HAVE_LIBCDDB
429       if (p_cdda->i_cddb_enabled) {
430         cddb_track_t *t=cddb_disc_get_track(p_cdda->cddb.disc,
431                                             i_track);
432         if (t != NULL) {
433           if ( t->artist != NULL && strlen(t->artist) ) {
434             input_Control( p_access, INPUT_ADD_INFO, track_str,
435                            _("Artist"), "%s", t->artist );
436           }
437           if ( t->title != NULL && strlen(t->title) ) {
438             input_Control( p_access, INPUT_ADD_INFO, track_str,
439                            _("Title"), "%s",  t->title );
440           }
441           if ( t->ext_data != NULL && strlen(t->ext_data) ) {
442             input_Control( p_access, INPUT_ADD_INFO, track_str,
443                            _("Extended Data"), "%s",  t->ext_data );
444           }
445         }
446       }
447 #endif /*HAVE_LIBCDDB*/
448     }
449   }
450 #endif /* UPDATE_TRACK_INFORMATION_FINISHED */
451 }
452
453 #define add_format_str_info(val)                         \
454   {                                                      \
455     const char *str = val;                               \
456     unsigned int len;                                    \
457     if (val != NULL) {                                   \
458       len=strlen(str);                                   \
459       if (len != 0) {                                    \
460         strncat(tp, str, TEMP_STR_LEN-(tp-temp_str));    \
461         tp += len;                                       \
462       }                                                  \
463       saw_control_prefix = false;                        \
464     }                                                    \
465   }
466
467 #define add_format_num_info(val, fmt)                    \
468   {                                                      \
469     char num_str[10];                                    \
470     unsigned int len;                                    \
471     sprintf(num_str, fmt, val);                          \
472     len=strlen(num_str);                                 \
473     if (len != 0) {                                      \
474       strncat(tp, num_str, TEMP_STR_LEN-(tp-temp_str));  \
475       tp += len;                                         \
476     }                                                    \
477     saw_control_prefix = false;                          \
478   }
479
480 /*!
481    Take a format string and expand escape sequences, that is sequences that
482    begin with %, with information from the current CD.
483    The expanded string is returned. Here is a list of escape sequences:
484
485    %a : The album artist **
486    %A : The album information **
487    %C : Category **
488    %I : CDDB disk ID **
489    %G : Genre **
490    %M : The current MRL
491    %m : The CD-DA Media Catalog Number (MCN)
492    %n : The number of tracks on the CD
493    %p : The artist/performer/composer in the track **
494    %T : The track number **
495    %s : Number of seconds in this track
496    %t : The name **
497    %Y : The year 19xx or 20xx **
498    %% : a %
499 */
500 static char *
501 CDDAFormatStr( const access_t *p_access, cdda_data_t *p_cdda,
502                const char format_str[], const char *mrl, int i_track)
503 {
504 #define TEMP_STR_SIZE 256
505 #define TEMP_STR_LEN (TEMP_STR_SIZE-1)
506   static char    temp_str[TEMP_STR_SIZE];
507   size_t i;
508   char * tp = temp_str;
509   bool saw_control_prefix = false;
510   size_t format_len = strlen(format_str);
511
512   memset(temp_str, 0, TEMP_STR_SIZE);
513
514   for (i=0; i<format_len; i++) {
515
516     if (!saw_control_prefix && format_str[i] != '%') {
517       *tp++ = format_str[i];
518       saw_control_prefix = false;
519       continue;
520     }
521
522     switch(format_str[i]) {
523     case '%':
524       if (saw_control_prefix) {
525         *tp++ = '%';
526       }
527       saw_control_prefix = !saw_control_prefix;
528       break;
529 #ifdef HAVE_LIBCDDB
530     case 'a':
531       if (!p_cdda->i_cddb_enabled) goto not_special;
532       if (p_cdda->cddb.disc)
533         add_format_str_info(p_cdda->cddb.disc->artist);
534       break;
535     case 'A':
536       if (!p_cdda->i_cddb_enabled) goto not_special;
537       if (p_cdda->cddb.disc)
538         add_format_str_info(p_cdda->cddb.disc->title);
539       break;
540     case 'C':
541       if (!p_cdda->i_cddb_enabled) goto not_special;
542       if (p_cdda->cddb.disc)
543         add_format_str_info(CDDB_CATEGORY[p_cdda->cddb.disc->category]);
544       break;
545     case 'G':
546       if (!p_cdda->i_cddb_enabled) goto not_special;
547       if (p_cdda->cddb.disc)
548         add_format_str_info(p_cdda->cddb.disc->genre);
549       break;
550     case 'I':
551       if (!p_cdda->i_cddb_enabled) goto not_special;
552       if (p_cdda->cddb.disc)
553         add_format_num_info(p_cdda->cddb.disc->discid, "%x");
554       break;
555     case 'Y':
556       if (!p_cdda->i_cddb_enabled) goto not_special;
557       if (p_cdda->cddb.disc)
558         add_format_num_info(p_cdda->cddb.disc->year, "%5d");
559       break;
560     case 't':
561       if (p_cdda && p_cdda->i_cddb_enabled && p_cdda->cddb.disc) {
562         cddb_track_t *t=cddb_disc_get_track(p_cdda->cddb.disc,
563                                             i_track-1);
564         if (t != NULL && t->title != NULL)
565           add_format_str_info(t->title);
566       } else goto not_special;
567       break;
568     case 'p':
569       if (p_cdda->i_cddb_enabled && p_cdda->cddb.disc) {
570         cddb_track_t *t=cddb_disc_get_track(p_cdda->cddb.disc,
571                                             i_track-1);
572         if (t != NULL && t->artist != NULL)
573           add_format_str_info(t->artist);
574       } else goto not_special;
575       break;
576     case 'e':
577       if (p_cdda->i_cddb_enabled && p_cdda->cddb.disc) {
578         cddb_track_t *t=cddb_disc_get_track(p_cdda->cddb.disc,
579                                             i_track-1);
580         if (t != NULL && t->ext_data != NULL)
581           add_format_str_info(t->ext_data);
582       } else goto not_special;
583       break;
584 #endif
585
586     case 'M':
587       add_format_str_info(mrl);
588       break;
589
590     case 'm':
591       add_format_str_info(p_cdda->psz_mcn);
592       break;
593
594     case 'n':
595       add_format_num_info(p_cdda->i_tracks, "%d");
596       break;
597
598     case 's':
599       if (p_cdda->i_cddb_enabled) {
600         char psz_buffer[MSTRTIME_MAX_SIZE];
601         mtime_t i_duration =
602           (p_cdda->p_sectors[i_track] - p_cdda->p_sectors[i_track-1])
603           / CDIO_CD_FRAMES_PER_SEC;
604         add_format_str_info(secstotimestr( psz_buffer, i_duration ) );
605       } else goto not_special;
606       break;
607
608     case 'T':
609       add_format_num_info(i_track, "%02d");
610       break;
611 #ifdef HAVE_LIBCDDB
612     not_special:
613 #endif
614     default:
615       *tp++ = '%';
616       *tp++ = format_str[i];
617       saw_control_prefix = false;
618     }
619   }
620   return strdup(temp_str);
621 }
622
623 #ifdef TRACK_META_INFORMATION_FINISHED
624 static void
625 CDDACreatePlayListItem(const input_thread_t *p_access, cdda_data_t *p_cdda,
626                        playlist_t *p_playlist, unsigned int i_track,
627                        char *psz_mrl, int psz_mrl_max,
628                        const char *psz_source, int playlist_operation,
629                        int i_pos)
630 {
631   mtime_t i_duration =
632     (p_cdda->p_sectors[i_track] - p_cdda->p_sectors[i_track-1])
633     * (1000000 / CDIO_CD_FRAMES_PER_SEC) ;
634   char *p_author;
635   char *p_title;
636   char *config_varname = MODULE_STRING "-title-format";
637   playlist_item_t *p_item;
638
639 #ifdef HAVE_LIBCDDB
640   if (p_cdda->i_cddb_enabled) {
641     config_varname = MODULE_STRING "-cddb-title-format";
642   }
643 #endif /*HAVE_LIBCDDB*/
644
645   snprintf(psz_mrl, psz_mrl_max, "%s%s@T%u",
646            CDDA_MRL_PREFIX, psz_source, i_track);
647
648   p_title = CDDAFormatStr(p_access, p_cdda,
649                           config_GetPsz( p_access, config_varname ),
650                           psz_mrl, i_track);
651
652   dbg_print( INPUT_DBG_META, "mrl: %s, title: %s, duration, %ld, pos %d",
653              psz_mrl, p_title, (long int) i_duration / 1000000 , i_pos );
654   playlist_AddExt( p_playlist, psz_mrl, p_title, playlist_operation,
655                          i_pos, i_duration , NULL, 0);
656
657   if( i_pos == PLAYLIST_END ) i_pos = p_playlist->i_size - 1;
658
659   vlc_mutex_lock( &p_playlist->object_lock );
660   p_item = playlist_ItemGetByPos( p_playlist, i_pos );
661   vlc_mutex_unlock( &p_playlist->object_lock );
662   if( !p_item )
663       return;
664
665   vlc_mutex_lock( &p_item->input.lock );
666
667   p_author =
668     CDDAFormatStr( p_access, p_cdda,
669                    config_GetPsz( p_access, MODULE_STRING "-author-format" ),
670                    psz_mrl, i_track );
671
672   playlist_ItemAddInfo( p_item ,  _("General"),_("Author"), p_author);
673
674 #ifdef HAVE_LIBCDDB
675   if (p_cdda->i_cddb_enabled) {
676     const char *psz_general_cat = _("General");
677
678     playlist_ItemAddInfo( p_item, psz_general_cat, _("Album"),
679                       "%s", p_cdda->cddb.disc->title);
680     playlist_ItemAddInfo( p_item, psz_general_cat, _("Disc Artist(s)"),
681                       "%s", p_cdda->cddb.disc->artist);
682     playlist_ItemAddInfo( p_item, psz_general_cat,
683                         _("CDDB Disc Category"),
684                       "%s", CDDB_CATEGORY[p_cdda->cddb.disc->category]);
685     playlist_ItemAddInfo( p_item, psz_general_cat, _("Genre"),
686                       "%s", p_cdda->cddb.disc->genre);
687     if ( p_cdda->cddb.disc->discid ) {
688       playlist_ItemAddInfo( p_item, psz_general_cat, _("CDDB Disc ID"),
689                         "%x", p_cdda->cddb.disc->discid );
690     }
691     if (p_cdda->cddb.disc->year != 0) {
692       playlist_ItemAddInfo( p_item, psz_general_cat,
693                         _("Year"), "%5d", p_cdda->cddb.disc->year );
694     }
695
696     if (p_cdda->i_cddb_enabled) {
697       cddb_track_t *t=cddb_disc_get_track(p_cdda->cddb.disc,
698                                           i_track-1);
699       if (t != NULL && t->artist != NULL) {
700         playlist_ItemAddInfo( p_item, psz_general_cat,
701                           _("Track Artist"), "%s", t->artist );
702         playlist_ItemAddInfo( p_item , psz_general_cat,
703                           _("Track Title"), "%s",  t->title );
704       }
705     }
706
707   }
708 #endif /*HAVE_LIBCDDB*/
709
710   vlc_mutex_unlock( &p_item->input.lock );
711 }
712
713 static int
714 CDDAFixupPlayList( access_t *p_access, cdda_data_t *p_cdda,
715                    const char *psz_source, track_t i_track)
716 {
717   int i;
718   char       * psz_mrl;
719   unsigned int psz_mrl_max = strlen(CDDA_MRL_PREFIX) + strlen(psz_source) +
720     strlen("@T") + strlen("100") + 1;
721
722   psz_mrl = malloc( psz_mrl_max );
723
724   if( psz_mrl == NULL )
725     {
726       msg_Warn( p_access, "out of memory" );
727       return -1;
728     }
729
730   CDDAMetaInfo(p_access);
731
732   for( i = 1 ; i <= p_cdda->i_tracks ; i++ )
733     {
734       input_title_t *t = p_cdda->p_sectors[i-1] = vlc_input_title_New();
735       
736       asprintf( &t->psz_name, _("Track %i"), i );
737       t->i_size = ( p_sys->p_sectors[i] - p_sys->p_sectors[i-1] ) *
738         (int64_t)CDIO_CD_FRAMESIZE_RAW;
739
740       t->i_length = I64C(1000000) * t->i_size / 44100 / 4;
741       CDDACreatePlayListItem(p_access, p_cdda, i, psz_mrl,
742                              psz_mrl_max, psz_source, PLAYLIST_APPEND,
743                              PLAYLIST_END);
744     }
745
746   return 0;
747 }
748 #endif /* TRACK_META_INFORMATION_FINISHED*/
749
750 /****************************************************************************
751  * Public functions
752  ****************************************************************************/
753 int
754 E_(CDDADebugCB)   ( vlc_object_t *p_this, const char *psz_name,
755                     vlc_value_t oldval, vlc_value_t val, void *p_data )
756 {
757   cdda_data_t *p_cdda;
758
759   if (NULL == p_cdda_input) return VLC_EGENERIC;
760
761   p_cdda = (cdda_data_t *)p_cdda_input->p_sys;
762
763   if (p_cdda->i_debug & (INPUT_DBG_CALL|INPUT_DBG_EXT)) {
764     msg_Dbg( p_cdda_input, "Old debug (x%0x) %d, new debug (x%0x) %d",
765              p_cdda->i_debug, p_cdda->i_debug, val.i_int, val.i_int);
766   }
767   p_cdda->i_debug = val.i_int;
768   return VLC_SUCCESS;
769 }
770
771 int
772 E_(CDDBEnabledCB)   ( vlc_object_t *p_this, const char *psz_name,
773                       vlc_value_t oldval, vlc_value_t val, void *p_data )
774 {
775   cdda_data_t *p_cdda;
776
777   if (NULL == p_cdda_input) return VLC_EGENERIC;
778
779   p_cdda = (cdda_data_t *)p_cdda_input->p_sys;
780
781 #ifdef HAVE_LIBCDDB
782   if (p_cdda->i_debug & (INPUT_DBG_CALL|INPUT_DBG_EXT)) {
783     msg_Dbg( p_cdda_input, "Old CDDB Enabled (x%0x) %d, new (x%0x) %d",
784              p_cdda->i_cddb_enabled, p_cdda->i_cddb_enabled,
785              val.i_int, val.i_int);
786   }
787   p_cdda->i_cddb_enabled = val.i_int;
788 #endif
789   return VLC_SUCCESS;
790 }
791
792 /*****************************************************************************
793  * Open: open cdda device or image file and initialize structures 
794  * for subsequent operations.
795  *****************************************************************************/
796 int
797 E_(CDDAOpen)( vlc_object_t *p_this )
798 {
799     access_t               *p_access = (access_t*)p_this;
800     char *                  psz_source;
801     cdda_data_t *           p_cdda;
802     int                     i;
803     cddev_t                 *p_cddev;
804
805     /* Set where to log errors messages from libcdio. */
806     p_cdda_input = p_access;
807
808     if( !p_access->psz_path || !*p_access->psz_path )
809     {
810         /* Only when selected */
811         if( !p_this->b_force ) return VLC_EGENERIC;
812
813         psz_source = var_CreateGetString( p_this, "cd-audio" );
814
815         if( !psz_source || !*psz_source ) {
816         /* Scan for a CD-ROM drive with a CD-DA in it. */
817         char **cd_drives =
818           cdio_get_devices_with_cap(NULL,  CDIO_FS_AUDIO, false);
819         if (NULL == cd_drives) return -1;
820         if (cd_drives[0] == NULL) {
821           cdio_free_device_list(cd_drives);
822           return -1;
823         }
824         psz_source = strdup(cd_drives[0]);
825         cdio_free_device_list(cd_drives);
826       }
827     }
828     else 
829       psz_source = strdup( p_access->psz_path );
830
831     cdio_log_set_handler ( cdio_log_handler );
832
833     /* Open CDDA */
834     if( !(p_cddev = ioctl_Open( p_this, psz_source )) )
835     {
836         msg_Warn( p_access, "could not open %s", psz_source );
837         goto error2;
838     }
839
840     p_cdda = malloc( sizeof(cdda_data_t) );
841     if( p_cdda == NULL )
842     {
843         msg_Err( p_access, "out of memory" );
844         free( psz_source );
845         return VLC_ENOMEM;
846     }
847
848 #ifdef HAVE_LIBCDDB
849     cddb_log_set_handler ( cddb_log_handler );
850     p_cdda->cddb.disc = NULL;
851     p_cdda->i_cddb_enabled =
852       config_GetInt( p_access, MODULE_STRING "-cddb-enabled" );
853 #endif
854
855     p_cdda->b_header = VLC_FALSE;
856     p_cdda->p_cddev  = p_cddev;
857     p_cdda->i_debug  = config_GetInt( p_this, MODULE_STRING "-debug" );
858
859     printf("+++debug: %d\n", p_cdda->i_debug);
860
861     dbg_print( (INPUT_DBG_CALL|INPUT_DBG_EXT), "%s", psz_source );
862
863     /* We read the Table Of Content information */
864     p_cdda->i_tracks = ioctl_GetTracksMap( VLC_OBJECT(p_access),
865                               p_cdda->p_cddev->cdio, &p_cdda->p_sectors );
866     if( p_cdda->i_tracks < 0 ) {
867         msg_Err( p_access, "unable to count tracks" );
868         goto error;
869     } else if( p_cdda->i_tracks <= 0 ) {
870         msg_Err( p_access, "no audio tracks found" );
871         goto error;
872     }
873
874     /* Set up p_access */
875     p_access->pf_read    = NULL;
876     p_access->pf_block   = CDDABlock;
877     p_access->pf_control = CDDAControl;
878     p_access->pf_seek    = CDDASeek;
879
880     p_access->info.i_update    = 0;
881     p_access->info.i_size      = 0;
882     p_access->info.i_pos       = 0;
883     p_access->info.b_eof       = VLC_FALSE;
884     p_access->info.i_title     = 0;
885     p_access->info.i_seekpoint = 0;
886
887     p_access->p_sys     = (access_sys_t *) p_cdda;
888
889     CDDAMetaInfo(p_access);
890     
891     { 
892       char *psz_config_title_fmt = MODULE_STRING "-title-format";
893       const char *psz_title_fmt  = 
894         config_GetPsz( p_access, psz_config_title_fmt );
895       
896 #ifdef HAVE_LIBCDDB
897       if (p_cdda->i_cddb_enabled) {
898         psz_config_title_fmt = MODULE_STRING "-cddb-title-format";
899       }
900 #endif /*HAVE_LIBCDDB*/
901
902       for( i = 1 ; i <= p_cdda->i_tracks ; i++ )
903         {
904           char * psz_title;
905           input_title_t *t = p_cdda->p_title[i-1] = vlc_input_title_New();
906           char *psz_mrl;
907
908           asprintf(&psz_mrl, "%s%s@T%u", CDDA_MRL_PREFIX, psz_source, i);
909           
910           psz_title = CDDAFormatStr(p_access, p_cdda, psz_title_fmt,
911                                     psz_mrl, i);
912
913           t->psz_name = strdup(psz_title);
914
915           t->i_size = ( p_cdda->p_sectors[i] - p_cdda->p_sectors[i-1] ) *
916             (int64_t)CDIO_CD_FRAMESIZE_RAW;
917           
918           t->i_length = I64C(1000000) * t->i_size / 44100 / 4;
919
920           dbg_print((INPUT_DBG_MRL), "track %d, start=%d, mrl %s", 
921                     i, p_cdda->p_sectors[i-1], psz_mrl );
922           
923           free (psz_mrl);
924         }
925     }
926     
927     /* Build a WAV header to put in front of the output data. 
928        This gets sent back in the Block (read) routine.
929      */
930     memset( &p_cdda->waveheader, 0, sizeof(WAVEHEADER) );
931     SetWLE( &p_cdda->waveheader.Format, 1 ); /*WAVE_FORMAT_PCM*/
932     SetWLE( &p_cdda->waveheader.BitsPerSample, 16);
933     p_cdda->waveheader.MainChunkID = VLC_FOURCC('R', 'I', 'F', 'F');
934     p_cdda->waveheader.Length = 0;                     /* we just don't know */
935     p_cdda->waveheader.ChunkTypeID = VLC_FOURCC('W', 'A', 'V', 'E');
936     p_cdda->waveheader.SubChunkID  = VLC_FOURCC('f', 'm', 't', ' ');
937     SetDWLE( &p_cdda->waveheader.SubChunkLength, 16);
938     SetWLE( &p_cdda->waveheader.Modus, 2);
939     SetDWLE( &p_cdda->waveheader.SampleFreq, 44100);
940     SetWLE( &p_cdda->waveheader.BytesPerSample,
941             2 /*Modus*/ * 16 /*BitsPerSample*/ / 8 );
942     SetDWLE( &p_cdda->waveheader.BytesPerSec,
943              2*16/8 /*BytesPerSample*/ * 44100 /*SampleFreq*/ );
944     p_cdda->waveheader.DataChunkID = VLC_FOURCC('d', 'a', 't', 'a');
945     p_cdda->waveheader.DataLength  = 0;    /* we just don't know */
946
947     /* PTS delay */
948     var_Create( p_access, MODULE_STRING "-caching", 
949                 VLC_VAR_INTEGER|VLC_VAR_DOINHERIT );
950     return VLC_SUCCESS;
951
952  error:
953     ioctl_Close( p_cdda->p_cddev );
954     free( p_cdda );
955  error2:
956     free( psz_source );
957     return VLC_EGENERIC;
958
959 }
960
961 /*****************************************************************************
962  * CDDAClose: closes cdda and frees any resources associded with it.
963  *****************************************************************************/
964 void
965 E_(CDDAClose)( vlc_object_t *p_this )
966 {
967     access_t    *p_access = (access_t *) p_this;
968     cdda_data_t *p_cdda   = (cdda_data_t *) p_access->p_sys;
969     track_t      i;
970
971     dbg_print( (INPUT_DBG_CALL|INPUT_DBG_EXT), "" );
972
973     /* Remove playlist titles */
974     for( i = 0; i < p_cdda->i_tracks; i++ )
975     {
976         vlc_input_title_Delete( p_cdda->p_title[i] );
977     }
978
979     ioctl_Close( p_cdda->p_cddev );
980
981     cdio_log_set_handler (uninit_log_handler);
982
983 #ifdef HAVE_LIBCDDB
984     cddb_log_set_handler (uninit_log_handler);
985     if (p_cdda->i_cddb_enabled)
986       cddb_disc_destroy(p_cdda->cddb.disc);
987 #endif
988
989     free( p_cdda->p_sectors );
990     if (p_cdda->psz_mcn) free( p_cdda->psz_mcn );
991     free( p_cdda );
992     p_cdda_input = NULL;
993 }
994
995 /*****************************************************************************
996  * Control: The front-end or vlc engine calls here to ether get
997  * information such as meta information or plugin capabilities or to
998  * issue miscellaneous "set" requests.
999  *****************************************************************************/
1000 static int CDDAControl( access_t *p_access, int i_query, va_list args )
1001 {
1002     cdda_data_t  *p_cdda = (cdda_data_t *) p_access->p_sys;
1003     vlc_bool_t   *pb_bool;
1004     int          *pi_int;
1005     int i;
1006
1007     dbg_print( (INPUT_DBG_CALL|INPUT_DBG_EXT|INPUT_DBG_EVENT),
1008                "query %d", i_query );
1009
1010     switch( i_query )
1011     {
1012         /* Pass back a copy of meta information that was gathered when we
1013            during the Open/Initialize call.
1014          */
1015         case ACCESS_GET_META:
1016           { 
1017             vlc_meta_t **pp_meta;
1018             pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
1019             dbg_print( INPUT_DBG_META, "Meta copied");
1020             *pp_meta = vlc_meta_Duplicate( p_cdda->p_meta );
1021             return VLC_SUCCESS;
1022           }
1023           return VLC_EGENERIC;
1024
1025         case ACCESS_CAN_SEEK:
1026         case ACCESS_CAN_FASTSEEK:
1027         case ACCESS_CAN_PAUSE:
1028         case ACCESS_CAN_CONTROL_PACE:
1029             pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t* );
1030             *pb_bool = VLC_TRUE;
1031             break;
1032
1033         /* */
1034         case ACCESS_GET_MTU:
1035             pi_int = (int*)va_arg( args, int * );
1036             *pi_int = CDDA_DATA_ONCE;
1037             break;
1038
1039         case ACCESS_GET_PTS_DELAY:
1040           { 
1041             int64_t      *pi_64;
1042             pi_64 = (int64_t*)va_arg( args, int64_t * );
1043             *pi_64 = 1000 * var_GetInteger( p_access, 
1044                                             MODULE_STRING "-caching" );
1045             break;
1046           }
1047
1048         /* */
1049         case ACCESS_SET_PAUSE_STATE:
1050             break;
1051
1052         case ACCESS_GET_TITLE_INFO:
1053           { input_title_t ***ppp_title;
1054             ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1055             pi_int    = (int*)va_arg( args, int* );
1056             *((int*)va_arg( args, int* )) = 1; /* Title offset */
1057
1058             /* Duplicate track info */
1059             *pi_int = p_cdda->i_tracks;
1060             *ppp_title = malloc(sizeof( input_title_t **) * p_cdda->i_tracks );
1061             for( i = 0; i < p_cdda->i_tracks; i++ )
1062             {
1063                 (*ppp_title)[i] = 
1064                   vlc_input_title_Duplicate( p_cdda->p_title[i] );
1065             }
1066           }
1067           break;
1068
1069         case ACCESS_SET_TITLE:
1070             i = (int)va_arg( args, int );
1071             if( i != p_access->info.i_title )
1072             {
1073                 /* Update info */
1074                 p_access->info.i_update |=
1075                     INPUT_UPDATE_TITLE|INPUT_UPDATE_SIZE;
1076                 p_access->info.i_title = i;
1077                 p_access->info.i_size = p_cdda->p_title[i]->i_size;
1078                 p_access->info.i_pos = 0;
1079
1080                 /* Next sector to read */
1081                 p_cdda->i_sector = p_cdda->p_sectors[i];
1082             }
1083             break;
1084
1085         case ACCESS_SET_SEEKPOINT:
1086         case ACCESS_SET_PRIVATE_ID_STATE:
1087             return VLC_EGENERIC;
1088         default:
1089             msg_Warn( p_access, "unimplemented query in control" );
1090             return VLC_EGENERIC;
1091
1092     }
1093     return VLC_SUCCESS;
1094 }