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