]> git.sesse.net Git - vlc/blob - modules/meta_engine/taglib.cpp
taglib: cleanup the header and add myslef to the authors.
[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     return VLC_SUCCESS;
336 }
337
338
339
340 /**
341  * Get the tags from the file using TagLib
342  * @param p_this: the demux object
343  * @return VLC_SUCCESS if the operation success
344  */
345 static int ReadMeta( vlc_object_t* p_this)
346 {
347     demux_t*        p_demux = (demux_t*)p_this;
348     demux_meta_t*   p_demux_meta = (demux_meta_t*)p_demux->p_private;
349     vlc_meta_t*     p_meta;
350     TagLib::FileRef f;
351
352     p_demux_meta->p_meta = NULL;
353     const char* local_name = ToLocale( p_demux->psz_path );
354     if( !local_name )
355         return VLC_EGENERIC;
356     f = FileRef( local_name );
357     LocaleFree( local_name );
358
359     if( f.isNull() )
360         return VLC_EGENERIC;
361     if( !f.tag() || f.tag()->isEmpty() )
362         return VLC_EGENERIC;
363
364     p_demux_meta->p_meta = p_meta = vlc_meta_New();
365     if( !p_meta )
366         return VLC_ENOMEM;
367
368
369     // Read the tags from the file
370     Tag* p_tag = f.tag();
371
372 #define SET( meta, tag )                                                       \
373     if( !p_tag->tag().isNull() && !p_tag->tag().isEmpty() )                    \
374         vlc_meta_Set##meta( p_meta, p_tag->tag().toCString(true) )
375 #define SETINT( meta, tag )                                                    \
376     if( p_tag->tag() )                                                         \
377     {                                                                          \
378         char psz_tmp[10];                                                      \
379         snprintf( psz_tmp, 10, "%d", p_tag->tag() );                           \
380         vlc_meta_Set##meta( p_meta, psz_tmp );                                 \
381     }
382
383     SET( Title, title );
384     SET( Artist, artist );
385     SET( Album, album );
386     SET( Description, comment );
387     SET( Genre, genre );
388     SETINT( Date, year );
389     SETINT( Tracknum, track );
390
391 #undef SETINT
392 #undef SET
393
394
395     // Try now to read special tags
396     if( FLAC::File* flac = dynamic_cast<FLAC::File*>(f.file()) )
397     {
398         if( flac->ID3v2Tag() )
399             ReadMetaFromId2v2( flac->ID3v2Tag(), p_meta );
400         else if( flac->xiphComment() )
401             ReadMetaFromXiph( flac->xiphComment(), p_meta );
402     }
403     else if( MPC::File* mpc = dynamic_cast<MPC::File*>(f.file()) )
404     {
405         if( mpc->APETag() )
406             ReadMetaFromAPE( mpc->APETag(), p_meta );
407     }
408     else if( MPEG::File* mpeg = dynamic_cast<MPEG::File*>(f.file()) )
409     {
410         if( mpeg->ID3v2Tag() )
411             ReadMetaFromId2v2( mpeg->ID3v2Tag(), p_meta );
412         else if( mpeg->APETag() )
413             ReadMetaFromAPE( mpeg->APETag(), p_meta );
414     }
415     else if( Ogg::File* ogg = dynamic_cast<Ogg::File*>(f.file()) )
416     {
417         if( Ogg::FLAC::File* ogg_flac = dynamic_cast<Ogg::FLAC::File*>(f.file()))
418             ReadMetaFromXiph( ogg_flac->tag(), p_meta );
419         else if( Ogg::Speex::File* ogg_speex = dynamic_cast<Ogg::Speex::File*>(f.file()) )
420             ReadMetaFromXiph( ogg_speex->tag(), p_meta );
421         else if( Ogg::Vorbis::File* ogg_vorbis = dynamic_cast<Ogg::Vorbis::File*>(f.file()) )
422             ReadMetaFromXiph( ogg_vorbis->tag(), p_meta );
423     }
424     else if( TrueAudio::File* trueaudio = dynamic_cast<TrueAudio::File*>(f.file()) )
425     {
426         if( trueaudio->ID3v2Tag() )
427             ReadMetaFromId2v2( trueaudio->ID3v2Tag(), p_meta );
428     }
429     else if( WavPack::File* wavpack = dynamic_cast<WavPack::File*>(f.file()) )
430     {
431         if( wavpack->APETag() )
432             ReadMetaFromAPE( wavpack->APETag(), p_meta );
433     }
434
435     // Try now to find a image
436     DetectImage( f, p_demux );
437
438     return VLC_SUCCESS;
439 }
440
441
442
443 /**
444  * Write meta informations to APE tags
445  * @param tag: the APE tag
446  * @param p_input: the input item
447  * @return VLC_SUCCESS if everything goes ok
448  */
449 static int WriteMetaToAPE( APE::Tag* tag, input_item_t* p_input )
450 {
451     return VLC_SUCCESS;
452 }
453
454
455
456 /**
457  * Write meta information to id3v2 tags
458  * @param tag: the id3v2 tag
459  * @param p_input: the input item
460  * @return VLC_SUCCESS if everything goes ok
461  */
462 static int WriteMetaToId2v2( ID3v2::Tag* tag, input_item_t* p_item )
463 {
464     char* psz_meta;
465 #define WRITE( metaName, tagName )                                            \
466     psz_meta = input_item_Get##metaName( p_item );                            \
467     if( psz_meta )                                                            \
468     {                                                                         \
469         ByteVector p_byte( tagName, 4 );                                      \
470         tag->removeFrames( p_byte );                                         \
471         ID3v2::TextIdentificationFrame* p_frame =                             \
472             new ID3v2::TextIdentificationFrame( p_byte, String::UTF8 );       \
473         p_frame->setText( psz_meta );                                         \
474         tag->addFrame( p_frame );                                             \
475     }                                                                         \
476     free( psz_meta );
477
478     WRITE( Copyright, "TCOP" );
479     WRITE( EncodedBy, "TENC" );
480     WRITE( Language,  "TLAN" );
481     WRITE( Publisher, "TPUB" );
482
483 #undef WRITE
484     return VLC_SUCCESS;
485 }
486
487
488
489 /**
490  * Write the meta informations to XiphComments
491  * @param tag: the Xiph Comment
492  * @param p_input: the input item
493  * @return VLC_SUCCESS if everything goes ok
494  */
495 static int WriteMetaToXiph( Ogg::XiphComment* tag, input_item_t* p_item )
496 {
497     char* psz_meta;
498 #define WRITE( metaName, keyName )                      \
499     psz_meta = input_item_Get##metaName( p_item );      \
500     if( psz_meta )                                      \
501     {                                                   \
502         String key( keyName, String::UTF8 );            \
503         String value( psz_meta, String::UTF8 );         \
504         tag->addField( key, value, true );              \
505     }                                                   \
506     free( psz_meta );
507
508     WRITE( Copyright, "COPYRIGHT" );
509
510 #undef WRITE
511     return VLC_SUCCESS;
512 }
513
514
515
516 /**
517  * Set the tags to the file using TagLib
518  * @param p_this: the demux object
519  * @return VLC_SUCCESS if the operation success
520  */
521
522 static int WriteMeta( vlc_object_t *p_this )
523 {
524     playlist_t *p_playlist = (playlist_t *)p_this;
525     meta_export_t *p_export = (meta_export_t *)p_playlist->p_private;
526     input_item_t *p_item = p_export->p_item;
527
528     if( !p_item )
529     {
530         msg_Err( p_this, "Can't save meta data of an empty input" );
531         return VLC_EGENERIC;
532     }
533
534     FileRef f( p_export->psz_file );
535     if( f.isNull() || !f.tag() || f.file()->readOnly() )
536     {
537         msg_Err( p_this, "File %s can't be opened for tag writing\n",
538             p_export->psz_file );
539         return VLC_EGENERIC;
540     }
541
542     msg_Dbg( p_this, "Writing metadata for %s", p_export->psz_file );
543
544     Tag *p_tag = f.tag();
545
546     char *psz_meta;
547
548 #define SET( a, b )                                         \
549     if( b )                                                 \
550     {                                                       \
551         String* psz_tmp = new String( b, String::UTF8 );    \
552         p_tag->set##a( *psz_tmp );                          \
553         delete psz_tmp;                                     \
554     }
555
556     // Saving all common fields
557     // If the title is empty, use the name
558     psz_meta = input_item_GetTitle( p_item );
559     if( !psz_meta ) psz_meta = input_item_GetName( p_item );
560     SET( Title, psz_meta );
561     free( psz_meta );
562
563     psz_meta = input_item_GetArtist( p_item );
564     SET( Artist, psz_meta );
565     free( psz_meta );
566
567     psz_meta = input_item_GetAlbum( p_item );
568     SET( Album, psz_meta );
569     free( psz_meta );
570
571     psz_meta = input_item_GetDescription( p_item );
572     SET( Comment, psz_meta );
573     free( psz_meta );
574
575     psz_meta = input_item_GetGenre( p_item );
576     SET( Genre, psz_meta );
577     free( psz_meta );
578
579 #undef SET
580
581     psz_meta = input_item_GetDate( p_item );
582     if( psz_meta ) p_tag->setYear( atoi( psz_meta ) );
583     free( psz_meta );
584
585     psz_meta = input_item_GetTrackNum( p_item );
586     if( psz_meta ) p_tag->setTrack( atoi( psz_meta ) );
587     free( psz_meta );
588
589
590     // Try now to write special tags
591     if( FLAC::File* flac = dynamic_cast<FLAC::File*>(f.file()) )
592     {
593         if( flac->ID3v2Tag() )
594             WriteMetaToId2v2( flac->ID3v2Tag(), p_item );
595         else if( flac->xiphComment() )
596             WriteMetaToXiph( flac->xiphComment(), p_item );
597     }
598     else if( MPC::File* mpc = dynamic_cast<MPC::File*>(f.file()) )
599     {
600         if( mpc->APETag() )
601             WriteMetaToAPE( mpc->APETag(), p_item );
602     }
603     else if( MPEG::File* mpeg = dynamic_cast<MPEG::File*>(f.file()) )
604     {
605         if( mpeg->ID3v2Tag() )
606             WriteMetaToId2v2( mpeg->ID3v2Tag(), p_item );
607         else if( mpeg->APETag() )
608             WriteMetaToAPE( mpeg->APETag(), p_item );
609     }
610     else if( Ogg::File* ogg = dynamic_cast<Ogg::File*>(f.file()) )
611     {
612         if( Ogg::FLAC::File* ogg_flac = dynamic_cast<Ogg::FLAC::File*>(f.file()))
613             WriteMetaToXiph( ogg_flac->tag(), p_item );
614         else if( Ogg::Speex::File* ogg_speex = dynamic_cast<Ogg::Speex::File*>(f.file()) )
615             WriteMetaToXiph( ogg_speex->tag(), p_item );
616         else if( Ogg::Vorbis::File* ogg_vorbis = dynamic_cast<Ogg::Vorbis::File*>(f.file()) )
617             WriteMetaToXiph( ogg_vorbis->tag(), p_item );
618     }
619     else if( TrueAudio::File* trueaudio = dynamic_cast<TrueAudio::File*>(f.file()) )
620     {
621         if( trueaudio->ID3v2Tag() )
622             WriteMetaToId2v2( trueaudio->ID3v2Tag(), p_item );
623     }
624     else if( WavPack::File* wavpack = dynamic_cast<WavPack::File*>(f.file()) )
625     {
626         if( wavpack->APETag() )
627             WriteMetaToAPE( wavpack->APETag(), p_item );
628     }
629
630     // Save the meta data
631     f.save();
632
633     return VLC_SUCCESS;
634 }
635
636
637
638 static int DownloadArt( vlc_object_t *p_this )
639 {
640     /* We need to be passed the file name
641      * Fetch the thing from the file, save it to the cache folder
642      */
643     return VLC_EGENERIC;
644 }
645