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