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