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