]> git.sesse.net Git - vlc/blob - modules/meta_engine/taglib.cpp
Taglib: cleaning and better use of the tag library.
[vlc] / modules / meta_engine / taglib.cpp
1 /*****************************************************************************
2  * taglib.cpp: Taglib tag parser/writer
3  *****************************************************************************
4  * Copyright (C) 2003-2008 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Clément Stenac <zorglub@videolan.org>
8  *          Rafaël Carré <funman@videolanorg>
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 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #include <vlc_common.h>
30 #include <vlc_plugin.h>
31 #include <vlc_playlist.h>
32 #include <vlc_meta.h>
33 #include <vlc_demux.h>
34 #include <vlc_strings.h>
35 #include <vlc_charset.h>
36
37 #ifdef WIN32
38 # include <io.h>
39 #else
40 # include <unistd.h>
41 #endif
42
43 #include <fileref.h>
44
45 #include <tag.h>
46 #include <id3v2tag.h>
47 #include <xiphcomment.h>
48 #include <apetag.h>
49
50 #include <flacfile.h>
51 #include <mpcfile.h>
52 #include <mpegfile.h>
53 #include <oggfile.h>
54 #include <oggflacfile.h>
55 #include <speexfile.h>
56 #include <vorbisfile.h>
57 #include <trueaudiofile.h>
58 #include <wavpackfile.h>
59
60 #include <tstring.h>
61 #include <textidentificationframe.h>
62 #include <tbytevector.h>
63 #include <attachedpictureframe.h>
64 //#include <oggflacfile.h> /* ogg flac files aren't auto-casted by TagLib */
65 #include <flacproperties.h>
66 #include <vorbisfile.h>
67 #include <vorbisproperties.h>
68 #include <uniquefileidentifierframe.h>
69 #include <textidentificationframe.h>
70 //#include <relativevolumeframe.h> /* parse the tags without TagLib helpers? */
71
72 static int  ReadMeta    ( vlc_object_t * );
73 static int  DownloadArt ( vlc_object_t * );
74 static int  WriteMeta   ( vlc_object_t * );
75
76 vlc_module_begin ()
77     set_capability( "meta reader", 1000 )
78     set_callbacks( ReadMeta, NULL )
79     add_submodule ()
80         set_capability( "art downloader", 50 )
81         set_callbacks( DownloadArt, NULL )
82     add_submodule ()
83         set_capability( "meta writer", 50 )
84         set_callbacks( WriteMeta, NULL )
85 vlc_module_end ()
86
87 using namespace TagLib;
88
89
90
91 /* Try detecting embedded art */
92 static void DetectImage( FileRef f, demux_t *p_demux )
93 {
94     demux_meta_t        *p_demux_meta   = (demux_meta_t *)p_demux->p_private;
95     vlc_meta_t          *p_meta         = p_demux_meta->p_meta;
96     int                 i_score         = -1;
97
98     /* Preferred type of image
99      * The 21 types are defined in id3v2 standard:
100      * http://www.id3.org/id3v2.4.0-frames */
101     static const int pi_cover_score[] = {
102         0,  /* Other */
103         5,  /* 32x32 PNG image that should be used as the file icon */
104         4,  /* File icon of a different size or format. */
105         20, /* Front cover image of the album. */
106         19, /* Back cover image of the album. */
107         13, /* Inside leaflet page of the album. */
108         18, /* Image from the album itself. */
109         17, /* Picture of the lead artist or soloist. */
110         16, /* Picture of the artist or performer. */
111         14, /* Picture of the conductor. */
112         15, /* Picture of the band or orchestra. */
113         9,  /* Picture of the composer. */
114         8,  /* Picture of the lyricist or text writer. */
115         7,  /* Picture of the recording location or studio. */
116         10, /* Picture of the artists during recording. */
117         11, /* Picture of the artists during performance. */
118         6,  /* Picture from a movie or video related to the track. */
119         1,  /* Picture of a large, coloured fish. */
120         12, /* Illustration related to the track. */
121         3,  /* Logo of the band or performer. */
122         2   /* Logo of the publisher (record company). */
123     };
124
125     if( MPEG::File *mpeg = dynamic_cast<MPEG::File *>(f.file() ) )
126     {
127         ID3v2::Tag  *p_tag = mpeg->ID3v2Tag();
128         if( !p_tag )
129             return;
130         ID3v2::FrameList list = p_tag->frameListMap()[ "APIC" ];
131         if( list.isEmpty() )
132             return;
133         ID3v2::AttachedPictureFrame *p_apic;
134
135         TAB_INIT( p_demux_meta->i_attachments, p_demux_meta->attachments );
136         for( ID3v2::FrameList::Iterator iter = list.begin();
137                 iter != list.end(); iter++ )
138         {
139             p_apic = dynamic_cast<ID3v2::AttachedPictureFrame*>(*iter);
140             input_attachment_t *p_attachment;
141
142             const char *psz_name, *psz_mime, *psz_description;
143             ByteVector p_data_taglib; const char *p_data; int i_data;
144
145             psz_mime = p_apic->mimeType().toCString(true);
146             psz_description = psz_name = p_apic->description().toCString(true);
147
148             /* some old iTunes version not only sets incorrectly the mime type
149              * or the description of the image,
150              * but also embeds incorrectly the image.
151              * Recent versions seem to behave correctly */
152             if( !strncmp( psz_mime, "PNG", 3 ) ||
153                 !strncmp( psz_name, "\xC2\x89PNG", 5 ) )
154             {
155                 msg_Warn( p_demux,
156                     "%s: Invalid picture embedded by broken iTunes version, "
157                     "you really shouldn't use this crappy software.",
158                     (const char *)f.file()->name() );
159                 break;
160             }
161
162             p_data_taglib = p_apic->picture();
163             p_data = p_data_taglib.data();
164             i_data = p_data_taglib.size();
165
166             msg_Dbg( p_demux, "Found embedded art: %s (%s) is %i bytes",
167                     psz_name, psz_mime, i_data );
168
169             p_attachment = vlc_input_attachment_New( psz_name, psz_mime,
170                     psz_description, p_data, i_data );
171             TAB_APPEND_CAST( (input_attachment_t**),
172                     p_demux_meta->i_attachments, p_demux_meta->attachments,
173                     p_attachment );
174
175             if( pi_cover_score[p_apic->type()] > i_score )
176             {
177                 i_score = pi_cover_score[p_apic->type()];
178                 char *psz_url;
179                 if( asprintf( &psz_url, "attachment://%s",
180                         p_attachment->psz_name ) == -1 )
181                     return;
182                 vlc_meta_SetArtURL( p_meta, psz_url );
183                 free( psz_url );
184             }
185         }
186     }
187     else
188     if( Ogg::Vorbis::File *oggv = dynamic_cast<Ogg::Vorbis::File *>(f.file() ) )
189     {
190         Ogg::XiphComment *p_tag = oggv->tag();
191         if( !p_tag )
192             return;
193
194         StringList mime_list = p_tag->fieldListMap()[ "COVERARTMIME" ];
195         StringList art_list = p_tag->fieldListMap()[ "COVERART" ];
196
197         /* we support only one cover in ogg/vorbis */
198         if( mime_list.size() != 1 || art_list.size() != 1 )
199             return;
200
201         input_attachment_t *p_attachment;
202
203         const char *psz_name, *psz_mime, *psz_description;
204         uint8_t *p_data;
205         int i_data;
206
207         psz_name = "cover";
208         psz_mime = mime_list[0].toCString(true);
209         psz_description = "cover";
210
211         i_data = vlc_b64_decode_binary( &p_data, art_list[0].toCString(true) );
212
213         msg_Dbg( p_demux, "Found embedded art: %s (%s) is %i bytes",
214                     psz_name, psz_mime, i_data );
215
216         TAB_INIT( p_demux_meta->i_attachments, p_demux_meta->attachments );
217         p_attachment = vlc_input_attachment_New( psz_name, psz_mime,
218                 psz_description, p_data, i_data );
219         free( p_data );
220
221         TAB_APPEND_CAST( (input_attachment_t**),
222                 p_demux_meta->i_attachments, p_demux_meta->attachments,
223                 p_attachment );
224
225         vlc_meta_SetArtURL( p_meta, "attachment://cover" );
226     }
227
228 #if 0
229     //flac embedded images are extracted in the flac demuxer
230     else if( FLAC::File *flac =
231              dynamic_cast<FLAC::File *>(f.file() ) )
232     {
233         p_tag = flac->ID3v2Tag();
234         if( p_tag )
235             return;
236         ID3v2::FrameList l = p_tag->frameListMap()[ "APIC" ];
237         if( l.isEmpty() )
238             return;
239             vlc_meta_SetArtURL( p_meta, "APIC" );
240     }
241 #endif
242 #if 0
243 /* TagLib doesn't support MP4 file yet */
244     else if( MP4::File *mp4 =
245                dynamic_cast<MP4::File *>( f.file() ) )
246     {
247         MP4::Tag *mp4tag =
248                 dynamic_cast<MP4::Tag *>( mp4->tag() );
249         if( mp4tag && mp4tag->cover().size() )
250             vlc_meta_SetArtURL( p_meta, "MP4C" );
251     }
252 #endif
253 }
254
255
256
257 /**
258  * Read meta informations from APE tags
259  * @param tag: the APE tag
260  * @param p_meta: the meta
261  * @return VLC_SUCCESS if everything goes ok
262  */
263 static int ReadMetaFromAPE( APE::Tag* tag, vlc_meta_t* p_meta )
264 {
265     return VLC_SUCCESS;
266 }
267
268
269
270 /**
271  * read meta information from id3v2 tags
272  * @param tag: the id3v2 tag
273  * @param p_meta: the meta
274  * @return VLC_SUCCESS if everything goes ok
275  */
276 static int ReadMetaFromId2v2( ID3v2::Tag* tag, vlc_meta_t* p_meta )
277 {
278     // Get the unique file identifier
279     ID3v2::FrameList list = tag->frameListMap()["UFID"];
280     ID3v2::FrameList::Iterator iter;
281     for( iter = list.begin(); iter != list.end(); iter++ )
282     {
283         ID3v2::UniqueFileIdentifierFrame* p_ufid =
284                 dynamic_cast<ID3v2::UniqueFileIdentifierFrame*>(*iter);
285         const char *owner = p_ufid->owner().toCString();
286         if (!strcmp( owner, "http://musicbrainz.org" ))
287         {
288             /* ID3v2 UFID contains up to 64 bytes binary data
289              * but in our case it will be a '\0'
290              * terminated string */
291             char psz_ufid[64];
292             int j = 0;
293             while( ( j < 63 ) &&
294                    ( j < p_ufid->identifier().size() ) )
295                 psz_ufid[j] = p_ufid->identifier()[j++];
296             psz_ufid[j] = '\0';
297             vlc_meta_SetTrackID( p_meta, psz_ufid );
298         }
299     }
300
301     // Get the use text
302     list = tag->frameListMap()["TXXX"];
303     for( iter = list.begin(); iter != list.end(); iter++ )
304     {
305         ID3v2::UserTextIdentificationFrame* p_txxx =
306                 dynamic_cast<ID3v2::UserTextIdentificationFrame*>(*iter);
307         vlc_meta_AddExtra( p_meta, p_txxx->description().toCString( true ),
308                            p_txxx->fieldList().toString().toCString( true ) );
309     }
310
311     // Get some more informations
312 #define SET( tagName, metaName )                                               \
313     list = tag->frameListMap()[tagName];                                       \
314     if( !list.isEmpty() )                                                      \
315         vlc_meta_Set##metaName( p_meta,                                        \
316                                 (*list.begin())->toString().toCString( true ) );
317
318     SET( "TCOP", Copyright );
319     SET( "TENC", EncodedBy );
320     SET( "TLAN", Language );
321     SET( "TPUB", Publisher );
322
323 #undef SET
324     return VLC_SUCCESS;
325 }
326
327
328
329 /**
330  * Read the meta informations from XiphComments
331  * @param tag: the Xiph Comment
332  * @param p_meta: the meta
333  * @return VLC_SUCCESS if everything goes ok
334  */
335 static int ReadMetaFromXiph( Ogg::XiphComment* tag, vlc_meta_t* p_meta )
336 {
337     return VLC_SUCCESS;
338 }
339
340
341
342 /**
343  * Get the tags from the file using TagLib
344  * @param p_this: the demux object
345  * @return VLC_SUCCESS if the operation success
346  */
347 static int ReadMeta( vlc_object_t* p_this)
348 {
349     demux_t*        p_demux = (demux_t*)p_this;
350     demux_meta_t*   p_demux_meta = (demux_meta_t*)p_demux->p_private;
351     vlc_meta_t*     p_meta;
352     TagLib::FileRef f;
353
354     p_demux_meta->p_meta = NULL;
355     const char* local_name = ToLocale( p_demux->psz_path );
356     if( !local_name )
357         return VLC_EGENERIC;
358     f = FileRef( local_name );
359     LocaleFree( local_name );
360
361     if( f.isNull() )
362         return VLC_EGENERIC;
363     if( !f.tag() || f.tag()->isEmpty() )
364         return VLC_EGENERIC;
365
366     p_demux_meta->p_meta = p_meta = vlc_meta_New();
367     if( !p_meta )
368         return VLC_ENOMEM;
369
370
371     // Read the tags from the file
372     Tag* p_tag = f.tag();
373
374 #define SET( meta, tag )                                                       \
375     if( !p_tag->tag().isNull() && !p_tag->tag().isEmpty() )                    \
376         vlc_meta_Set##meta( p_meta, p_tag->tag().toCString(true) )
377 #define SETINT( meta, tag )                                                    \
378     if( p_tag->tag() )                                                         \
379     {                                                                          \
380         char psz_tmp[10];                                                      \
381         snprintf( psz_tmp, 10, "%d", p_tag->tag() );                           \
382         vlc_meta_Set##meta( p_meta, psz_tmp );                                 \
383     }
384
385     SET( Title, title );
386     SET( Artist, artist );
387     SET( Album, album );
388     SET( Description, comment );
389     SET( Genre, genre );
390     SETINT( Date, year );
391     SETINT( Tracknum, track );
392
393 #undef SETINT
394 #undef SET
395
396
397     // Try now to read special tags
398     if( FLAC::File* flac = dynamic_cast<FLAC::File*>(f.file()) )
399     {
400         if( flac->ID3v2Tag() )
401             ReadMetaFromId2v2( flac->ID3v2Tag(), p_meta );
402         else if( flac->xiphComment() )
403             ReadMetaFromXiph( flac->xiphComment(), p_meta );
404     }
405     else if( MPC::File* mpc = dynamic_cast<MPC::File*>(f.file()) )
406     {
407         if( mpc->APETag() )
408             ReadMetaFromAPE( mpc->APETag(), p_meta );
409     }
410     else if( MPEG::File* mpeg = dynamic_cast<MPEG::File*>(f.file()) )
411     {
412         if( mpeg->ID3v2Tag() )
413             ReadMetaFromId2v2( mpeg->ID3v2Tag(), p_meta );
414         else if( mpeg->APETag() )
415             ReadMetaFromAPE( mpeg->APETag(), p_meta );
416     }
417     else if( Ogg::File* ogg = dynamic_cast<Ogg::File*>(f.file()) )
418     {
419         if( Ogg::FLAC::File* ogg_flac = dynamic_cast<Ogg::FLAC::File*>(f.file()))
420             ReadMetaFromXiph( ogg_flac->tag(), p_meta );
421         else if( Ogg::Speex::File* ogg_speex = dynamic_cast<Ogg::Speex::File*>(f.file()) )
422             ReadMetaFromXiph( ogg_speex->tag(), p_meta );
423         else if( Ogg::Vorbis::File* ogg_vorbis = dynamic_cast<Ogg::Vorbis::File*>(f.file()) )
424             ReadMetaFromXiph( ogg_vorbis->tag(), p_meta );
425     }
426     else if( TrueAudio::File* trueaudio = dynamic_cast<TrueAudio::File*>(f.file()) )
427     {
428         if( trueaudio->ID3v2Tag() )
429             ReadMetaFromId2v2( trueaudio->ID3v2Tag(), p_meta );
430     }
431     else if( WavPack::File* wavpack = dynamic_cast<WavPack::File*>(f.file()) )
432     {
433         if( wavpack->APETag() )
434             ReadMetaFromAPE( wavpack->APETag(), p_meta );
435     }
436
437     // Try now to find a image
438     DetectImage( f, p_demux );
439
440     return VLC_SUCCESS;
441 }
442
443
444 static int WriteMeta( vlc_object_t *p_this )
445 {
446     playlist_t *p_playlist = (playlist_t *)p_this;
447     meta_export_t *p_export = (meta_export_t *)p_playlist->p_private;
448     input_item_t *p_item = p_export->p_item;
449
450     if( p_item == NULL )
451     {
452         msg_Err( p_this, "Can't save meta data of an empty input" );
453         return VLC_EGENERIC;
454     }
455
456     FileRef f( p_export->psz_file );
457     if( f.isNull() || !f.tag() || f.file()->readOnly() )
458     {
459         msg_Err( p_this, "File %s can't be opened for tag writing\n",
460             p_export->psz_file );
461         return VLC_EGENERIC;
462     }
463
464     msg_Dbg( p_this, "Writing metadata for %s", p_export->psz_file );
465
466     Tag *p_tag = f.tag();
467
468     char *psz_meta;
469
470 #define SET(a,b) \
471         if(b) { \
472             String *psz_##a = new String( b, \
473                 String::UTF8 ); \
474             p_tag->set##a( *psz_##a ); \
475             delete psz_##a; \
476         }
477
478
479     psz_meta = input_item_GetArtist( p_item );
480     SET( Artist, psz_meta );
481     free( psz_meta );
482
483     psz_meta = input_item_GetTitle( p_item );
484     if( !psz_meta ) psz_meta = input_item_GetName( p_item );
485     String *psz_title = new String( psz_meta,
486         String::UTF8 );
487     p_tag->setTitle( *psz_title );
488     delete psz_title;
489     free( psz_meta );
490
491     psz_meta = input_item_GetAlbum( p_item );
492     SET( Album, psz_meta );
493     free( psz_meta );
494
495     psz_meta = input_item_GetGenre( p_item );
496     SET( Genre, psz_meta );
497     free( psz_meta );
498
499 #undef SET
500
501     psz_meta = input_item_GetDate( p_item );
502     if( psz_meta ) p_tag->setYear( atoi( psz_meta ) );
503     free( psz_meta );
504
505     psz_meta = input_item_GetTrackNum( p_item );
506     if( psz_meta ) p_tag->setTrack( atoi( psz_meta ) );
507     free( psz_meta );
508
509     if( ID3v2::Tag *p_id3tag =
510         dynamic_cast<ID3v2::Tag *>(p_tag) )
511     {
512 #define WRITE( foo, bar ) \
513         psz_meta = input_item_Get##foo( p_item ); \
514         if( psz_meta ) \
515         { \
516             ByteVector p_byte( bar, 4 ); \
517             ID3v2::TextIdentificationFrame p_frame( p_byte ); \
518             p_frame.setText( psz_meta ); \
519             p_id3tag->addFrame( &p_frame ); \
520             free( psz_meta ); \
521         } \
522
523         WRITE( Publisher, "TPUB" );
524         WRITE( Copyright, "TCOP" );
525         WRITE( EncodedBy, "TENC" );
526         WRITE( Language, "TLAN" );
527
528 #undef WRITE
529     }
530
531     f.save();
532     return VLC_SUCCESS;
533 }
534
535 static int DownloadArt( vlc_object_t *p_this )
536 {
537     /* We need to be passed the file name
538      * Fetch the thing from the file, save it to the cache folder
539      */
540     return VLC_EGENERIC;
541 }
542