]> git.sesse.net Git - vlc/blob - modules/meta_engine/taglib.cpp
taglib: Support reading AlbumArtist from ID3v2 and Ogg
[vlc] / modules / meta_engine / taglib.cpp
1 /*****************************************************************************
2  * taglib.cpp: Taglib tag parser/writer
3  *****************************************************************************
4  * Copyright (C) 2003-2011 VLC authors and VideoLAN
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 it
12  * under the terms of the GNU Lesser General Public License as published by
13  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public License
22  * along with this program; if not, write to the Free Software Foundation,
23  * 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_demux.h>              /* demux_meta_t */
33 #include <vlc_strings.h>            /* vlc_b64_decode_binary */
34 #include <vlc_input.h>              /* for attachment_new */
35 #include <vlc_url.h>                /* make_path */
36 #include <vlc_mime.h>               /* mime type */
37 #include <vlc_fs.h>
38
39 #include <sys/stat.h>
40
41 #ifdef _WIN32
42 # include <vlc_charset.h>
43 # include <io.h>
44 #else
45 # include <unistd.h>
46 #endif
47
48
49 // Taglib headers
50 #ifdef _WIN32
51 # define TAGLIB_STATIC
52 #endif
53 #include <taglib.h>
54 #define VERSION_INT(a, b, c) ((a)<<16 | (b)<<8 | (c))
55 #define TAGLIB_VERSION VERSION_INT(TAGLIB_MAJOR_VERSION, \
56                                    TAGLIB_MINOR_VERSION, \
57                                    TAGLIB_PATCH_VERSION)
58
59 #include <fileref.h>
60 #include <tag.h>
61 #include <tbytevector.h>
62
63 #if TAGLIB_VERSION >= VERSION_INT(1,7,0)
64 # define TAGLIB_HAVE_APEFILE_H
65 # include <apefile.h>
66 # ifdef TAGLIB_WITH_ASF                     // ASF pictures comes with v1.7.0
67 #  define TAGLIB_HAVE_ASFPICTURE_H
68 #  include <asffile.h>
69 # endif
70 #endif
71
72 #if TAGLIB_VERSION >= VERSION_INT(1,9,0)
73 # include <opusfile.h>
74 #endif
75
76 #include <apetag.h>
77 #include <flacfile.h>
78 #include <mpcfile.h>
79 #include <mpegfile.h>
80 #include <oggfile.h>
81 #include <oggflacfile.h>
82 #include "../demux/xiph_metadata.h"
83
84 #include <aifffile.h>
85 #include <wavfile.h>
86
87 #if defined(TAGLIB_WITH_MP4)
88 # include <mp4file.h>
89 #endif
90
91 #include <speexfile.h>
92 #include <trueaudiofile.h>
93 #include <vorbisfile.h>
94 #include <wavpackfile.h>
95
96 #include <attachedpictureframe.h>
97 #include <textidentificationframe.h>
98 #include <uniquefileidentifierframe.h>
99
100 // taglib is not thread safe
101 static vlc_mutex_t taglib_lock = VLC_STATIC_MUTEX;
102
103 // Local functions
104 static int ReadMeta    ( vlc_object_t * );
105 static int WriteMeta   ( vlc_object_t * );
106
107 vlc_module_begin ()
108     set_capability( "meta reader", 1000 )
109     set_callbacks( ReadMeta, NULL )
110     add_submodule ()
111         set_capability( "meta writer", 50 )
112         set_callbacks( WriteMeta, NULL )
113 vlc_module_end ()
114
115 using namespace TagLib;
116
117 static void ExtractTrackNumberValues( vlc_meta_t* p_meta, const char *psz_value )
118 {
119     unsigned int i_trknum, i_trktot;
120     if( sscanf( psz_value, "%u/%u", &i_trknum, &i_trktot ) == 2 )
121     {
122         char psz_trck[11];
123         snprintf( psz_trck, sizeof( psz_trck ), "%u", i_trknum );
124         vlc_meta_SetTrackNum( p_meta, psz_trck );
125         snprintf( psz_trck, sizeof( psz_trck ), "%u", i_trktot );
126         vlc_meta_Set( p_meta, vlc_meta_TrackTotal, psz_trck );
127     }
128 }
129
130 /**
131  * Read meta information from APE tags
132  * @param tag: the APE tag
133  * @param p_demux_meta: the demuxer meta
134  * @param p_meta: the meta
135  */
136 static void ReadMetaFromAPE( APE::Tag* tag, demux_meta_t* p_demux_meta, vlc_meta_t* p_meta )
137 {
138     APE::ItemListMap fields ( tag->itemListMap() );
139     APE::ItemListMap::Iterator iter;
140
141     iter = fields.find("COVER ART (FRONT)");
142     if( iter != fields.end()
143         && !iter->second.isEmpty()
144         && !iter->second.type() == APE::Item::Binary)
145     {
146         input_attachment_t *p_attachment;
147
148         const ByteVector picture = iter->second.binaryData();
149         const char *p_data = picture.data();
150         unsigned i_data = picture.size();
151
152         /* Null terminated filename followed by the image data */
153         size_t desc_len = strnlen(p_data, i_data);
154         if( desc_len < i_data && IsUTF8( p_data ) )
155         {
156             const char *psz_name = p_data;
157             const char *psz_mime = vlc_mime_Ext2Mime( psz_name );
158             p_data += desc_len + 1; /* '\0' */
159             i_data -= desc_len + 1;
160
161             msg_Dbg( p_demux_meta, "Found embedded art: %s (%s) is %u bytes",
162                      psz_name, psz_mime, i_data );
163
164             p_attachment = vlc_input_attachment_New( psz_name, psz_mime,
165                                     psz_name, p_data, i_data );
166             if( p_attachment )
167             {
168                 TAB_APPEND_CAST( (input_attachment_t**),
169                                  p_demux_meta->i_attachments, p_demux_meta->attachments,
170                                  p_attachment );
171
172                 char *psz_url;
173                 if( asprintf( &psz_url, "attachment://%s", p_attachment->psz_name ) != -1 )
174                 {
175                     vlc_meta_SetArtURL( p_meta, psz_url );
176                     free( psz_url );
177                 }
178             }
179         }
180
181         fields.erase(iter);
182     }
183
184 #define SET( keyName, metaName ) \
185     iter = fields.find(keyName); \
186     if( iter != fields.end() && !iter->second.isEmpty() ) { \
187         vlc_meta_Set##metaName( p_meta, iter->second.toString().toCString( true ) ); \
188         fields.erase(iter); \
189     }
190
191 #define SET_EXTRA( keyName, metaName ) \
192     iter = fields.find( keyName ); \
193     if( iter != fields.end() && !iter->second.isEmpty() ) { \
194         vlc_meta_AddExtra( p_meta, metaName, iter->second.toString().toCString( true ) ); \
195         fields.erase(iter); \
196     }
197
198     SET( "ALBUM", Album );
199     SET( "ARTIST", Artist );
200     SET( "COMMENT", Description );
201     SET( "GENRE", Genre );
202     SET( "TITLE", Title );
203     SET( "COPYRIGHT", Copyright );
204     SET( "LANGUAGE", Language );
205     SET( "PUBLISHER", Publisher );
206     SET( "MUSICBRAINZ_TRACKID", TrackID );
207
208     SET_EXTRA( "MUSICBRAINZ_ALBUMID", VLC_META_EXTRA_MB_ALBUMID );
209
210 #undef SET
211 #undef SET_EXTRA
212
213     /* */
214     iter = fields.find( "TRACK" );
215     if( iter != fields.end() && !iter->second.isEmpty() )
216     {
217         ExtractTrackNumberValues( p_meta, iter->second.toString().toCString( true ) );
218         fields.erase( iter );
219     }
220
221     /* Remainings */
222     for( iter = fields.begin(); iter != fields.end(); ++iter )
223     {
224         if( iter->second.isEmpty() )
225             continue;
226
227         if( iter->second.type() != APE::Item::Text )
228             continue;
229
230         vlc_meta_AddExtra( p_meta,
231                            iter->first.toCString( true ),
232                            iter->second.toString().toCString( true ) );
233     }
234 }
235
236
237 /**
238  * Read meta information from ASF tags
239  * @param tag: the ASF tag
240  * @param p_demux_meta: the demuxer meta
241  * @param p_meta: the meta
242  */
243 static void ReadMetaFromASF( ASF::Tag* tag, demux_meta_t* p_demux_meta, vlc_meta_t* p_meta )
244 {
245
246     ASF::AttributeList list;
247 #define SET( keyName, metaName )                                                     \
248     if( tag->attributeListMap().contains(keyName) )                                  \
249     {                                                                                \
250         list = tag->attributeListMap()[keyName];                                     \
251         vlc_meta_Set##metaName( p_meta, list.front().toString().toCString( true ) ); \
252     }
253
254 #define SET_EXTRA( keyName, metaName )                                                     \
255     if( tag->attributeListMap().contains(keyName) )                                  \
256     {                                                                                \
257         list = tag->attributeListMap()[keyName];                                     \
258         vlc_meta_AddExtra( p_meta, metaName, list.front().toString().toCString( true ) ); \
259     }
260
261     SET("MusicBrainz/Track Id", TrackID );
262     SET_EXTRA("MusicBrainz/Album Id", VLC_META_EXTRA_MB_ALBUMID );
263
264 #undef SET
265 #undef SET_EXTRA
266
267 #ifdef TAGLIB_HAVE_ASFPICTURE_H
268     // List the pictures
269     list = tag->attributeListMap()["WM/Picture"];
270     ASF::AttributeList::Iterator iter;
271     for( iter = list.begin(); iter != list.end(); iter++ )
272     {
273         const ASF::Picture asfPicture = (*iter).toPicture();
274         const ByteVector picture = asfPicture.picture();
275         const char *psz_mime = asfPicture.mimeType().toCString();
276         const char *p_data = picture.data();
277         const unsigned i_data = picture.size();
278         char *psz_name;
279         input_attachment_t *p_attachment;
280
281         if( asfPicture.description().size() > 0 )
282             psz_name = strdup( asfPicture.description().toCString( true ) );
283         else
284         {
285             if( asprintf( &psz_name, "%i", asfPicture.type() ) == -1 )
286                 continue;
287         }
288
289         msg_Dbg( p_demux_meta, "Found embedded art: %s (%s) is %u bytes",
290                  psz_name, psz_mime, i_data );
291
292         p_attachment = vlc_input_attachment_New( psz_name, psz_mime,
293                                 psz_name, p_data, i_data );
294         if( p_attachment )
295             TAB_APPEND_CAST( (input_attachment_t**),
296                              p_demux_meta->i_attachments, p_demux_meta->attachments,
297                              p_attachment );
298         char *psz_url;
299         if( asprintf( &psz_url, "attachment://%s", psz_name ) != -1 )
300         {
301             vlc_meta_SetArtURL( p_meta, psz_url );
302             free( psz_url );
303         }
304         free( psz_name );
305     }
306 #endif
307 }
308
309
310 /**
311  * Read meta information from id3v2 tags
312  * @param tag: the id3v2 tag
313  * @param p_demux_meta: the demuxer meta
314  * @param p_meta: the meta
315  */
316 static void ReadMetaFromId3v2( ID3v2::Tag* tag, demux_meta_t* p_demux_meta, vlc_meta_t* p_meta )
317 {
318     // Get the unique file identifier
319     ID3v2::FrameList list = tag->frameListMap()["UFID"];
320     ID3v2::FrameList::Iterator iter;
321     for( iter = list.begin(); iter != list.end(); iter++ )
322     {
323         ID3v2::UniqueFileIdentifierFrame* p_ufid =
324                 dynamic_cast<ID3v2::UniqueFileIdentifierFrame*>(*iter);
325         if( !p_ufid )
326             continue;
327         const char *owner = p_ufid->owner().toCString();
328         if (!strcmp( owner, "http://musicbrainz.org" ))
329         {
330             /* ID3v2 UFID contains up to 64 bytes binary data
331              * but in our case it will be a '\0'
332              * terminated string */
333             char psz_ufid[64];
334             int max_size = __MIN( p_ufid->identifier().size(), 63);
335             strncpy( psz_ufid, p_ufid->identifier().data(), max_size );
336             psz_ufid[max_size] = '\0';
337             vlc_meta_SetTrackID( p_meta, psz_ufid );
338         }
339     }
340
341     // Get the use text
342     list = tag->frameListMap()["TXXX"];
343     for( iter = list.begin(); iter != list.end(); iter++ )
344     {
345         ID3v2::UserTextIdentificationFrame* p_txxx =
346                 dynamic_cast<ID3v2::UserTextIdentificationFrame*>(*iter);
347         if( !p_txxx )
348             continue;
349         if( !strcmp( p_txxx->description().toCString( true ), "TRACKTOTAL" ) )
350         {
351             vlc_meta_Set( p_meta, vlc_meta_TrackTotal, p_txxx->fieldList().back().toCString( true ) );
352             continue;
353         }
354         if( !strcmp( p_txxx->description().toCString( true ), "MusicBrainz Album Id" ) )
355         {
356             vlc_meta_AddExtra( p_meta, VLC_META_EXTRA_MB_ALBUMID, p_txxx->fieldList().back().toCString( true ) );
357             continue;
358         }
359         vlc_meta_AddExtra( p_meta, p_txxx->description().toCString( true ),
360                            p_txxx->fieldList().back().toCString( true ) );
361     }
362
363     // Get some more information
364 #define SET( tagName, metaName )                                               \
365     list = tag->frameListMap()[tagName];                                       \
366     if( !list.isEmpty() )                                                      \
367         vlc_meta_Set##metaName( p_meta,                                        \
368                                 (*list.begin())->toString().toCString( true ) );
369
370     SET( "TCOP", Copyright );
371     SET( "TENC", EncodedBy );
372     SET( "TLAN", Language );
373     SET( "TPUB", Publisher );
374     SET( "TPE2", AlbumArtist );
375
376 #undef SET
377
378     /* */
379     list = tag->frameListMap()["TRCK"];
380     if( !list.isEmpty() )
381     {
382         ExtractTrackNumberValues( p_meta, (*list.begin())->toString().toCString( true ) );
383     }
384
385     /* Preferred type of image
386      * The 21 types are defined in id3v2 standard:
387      * http://www.id3.org/id3v2.4.0-frames */
388     static const int pi_cover_score[] = {
389         0,  /* Other */
390         5,  /* 32x32 PNG image that should be used as the file icon */
391         4,  /* File icon of a different size or format. */
392         20, /* Front cover image of the album. */
393         19, /* Back cover image of the album. */
394         13, /* Inside leaflet page of the album. */
395         18, /* Image from the album itself. */
396         17, /* Picture of the lead artist or soloist. */
397         16, /* Picture of the artist or performer. */
398         14, /* Picture of the conductor. */
399         15, /* Picture of the band or orchestra. */
400         9,  /* Picture of the composer. */
401         8,  /* Picture of the lyricist or text writer. */
402         7,  /* Picture of the recording location or studio. */
403         10, /* Picture of the artists during recording. */
404         11, /* Picture of the artists during performance. */
405         6,  /* Picture from a movie or video related to the track. */
406         1,  /* Picture of a large, coloured fish. */
407         12, /* Illustration related to the track. */
408         3,  /* Logo of the band or performer. */
409         2   /* Logo of the publisher (record company). */
410     };
411     #define PI_COVER_SCORE_SIZE (sizeof (pi_cover_score) / sizeof (pi_cover_score[0]))
412     int i_score = -1;
413
414     // Try now to get embedded art
415     list = tag->frameListMap()[ "APIC" ];
416     if( list.isEmpty() )
417         return;
418
419     for( iter = list.begin(); iter != list.end(); iter++ )
420     {
421         ID3v2::AttachedPictureFrame* p_apic =
422             dynamic_cast<ID3v2::AttachedPictureFrame*>(*iter);
423         if( !p_apic )
424             continue;
425         input_attachment_t *p_attachment;
426
427         const char *psz_mime;
428         char *psz_name, *psz_description;
429
430         // Get the mime and description of the image.
431         // If the description is empty, take the type as a description
432         psz_mime = p_apic->mimeType().toCString( true );
433         if( p_apic->description().size() > 0 )
434             psz_description = strdup( p_apic->description().toCString( true ) );
435         else
436         {
437             if( asprintf( &psz_description, "%i", p_apic->type() ) == -1 )
438                 psz_description = NULL;
439         }
440
441         if( !psz_description )
442             continue;
443         psz_name = psz_description;
444
445         /* some old iTunes version not only sets incorrectly the mime type
446          * or the description of the image,
447          * but also embeds incorrectly the image.
448          * Recent versions seem to behave correctly */
449         if( !strncmp( psz_mime, "PNG", 3 ) ||
450             !strncmp( psz_name, "\xC2\x89PNG", 5 ) )
451         {
452             msg_Warn( p_demux_meta, "Invalid picture embedded by broken iTunes version" );
453             free( psz_description );
454             continue;
455         }
456
457         const ByteVector picture = p_apic->picture();
458         const char *p_data = picture.data();
459         const unsigned i_data = picture.size();
460
461         msg_Dbg( p_demux_meta, "Found embedded art: %s (%s) is %u bytes",
462                  psz_name, psz_mime, i_data );
463
464         p_attachment = vlc_input_attachment_New( psz_name, psz_mime,
465                                 psz_description, p_data, i_data );
466         if( !p_attachment )
467         {
468             free( psz_description );
469             continue;
470         }
471         TAB_APPEND_CAST( (input_attachment_t**),
472                          p_demux_meta->i_attachments, p_demux_meta->attachments,
473                          p_attachment );
474         free( psz_description );
475
476         unsigned i_pic_type = p_apic->type();
477         if( i_pic_type >= PI_COVER_SCORE_SIZE )
478             i_pic_type = 0; // Defaults to "Other"
479
480         if( pi_cover_score[i_pic_type] > i_score )
481         {
482             i_score = pi_cover_score[i_pic_type];
483             char *psz_url;
484             if( asprintf( &psz_url, "attachment://%s",
485                           p_attachment->psz_name ) == -1 )
486                 continue;
487             vlc_meta_SetArtURL( p_meta, psz_url );
488             free( psz_url );
489         }
490     }
491 }
492
493
494 /**
495  * Read the meta information from XiphComments
496  * @param tag: the Xiph Comment
497  * @param p_demux_meta: the demuxer meta
498  * @param p_meta: the meta
499  */
500 static void ReadMetaFromXiph( Ogg::XiphComment* tag, demux_meta_t* p_demux_meta, vlc_meta_t* p_meta )
501 {
502     StringList list;
503     bool hasTrackTotal = false;
504 #define SET( keyName, metaName )                                               \
505     list = tag->fieldListMap()[keyName];                                       \
506     if( !list.isEmpty() )                                                      \
507         vlc_meta_Set##metaName( p_meta, (*list.begin()).toCString( true ) );
508
509 #define SET_EXTRA( keyName, metaName ) \
510     list = tag->fieldListMap()[keyName]; \
511     if( !list.isEmpty() ) \
512         vlc_meta_AddExtra( p_meta, keyName, (*list.begin()).toCString( true ) );
513
514     SET( "COPYRIGHT", Copyright );
515     SET( "ORGANIZATION", Publisher );
516     SET( "DATE", Date );
517     SET( "ENCODER", EncodedBy );
518     SET( "RATING", Rating );
519     SET( "LANGUAGE", Language );
520     SET( "MUSICBRAINZ_TRACKID", TrackID );
521     SET( "ALBUMARTIST", AlbumArtist );
522
523     SET_EXTRA( "MUSICBRAINZ_ALBUMID", VLC_META_EXTRA_MB_ALBUMID );
524 #undef SET
525 #undef SET_EXTRA
526
527     list = tag->fieldListMap()["TRACKNUMBER"];
528     if( !list.isEmpty() )
529     {
530         const char *psz_value;
531         unsigned short u_track;
532         unsigned short u_total;
533         psz_value = (*list.begin()).toCString( true );
534         if( sscanf( psz_value, "%hu/%hu", &u_track, &u_total ) == 2)
535         {
536             char str[6];
537             snprintf(str, 6, "%u", u_track);
538             vlc_meta_SetTrackNum( p_meta, str);
539             snprintf(str, 6, "%u", u_total);
540             vlc_meta_SetTrackTotal( p_meta, str);
541             hasTrackTotal = true;
542         }
543         else
544             vlc_meta_SetTrackNum( p_meta, psz_value);
545     }
546     if( !hasTrackTotal )
547     {
548         list = tag->fieldListMap()["TRACKTOTAL"];
549         if( list.isEmpty() )
550             list = tag->fieldListMap()["TOTALTRACKS"];
551         if( !list.isEmpty() )
552             vlc_meta_SetTrackTotal( p_meta, (*list.begin()).toCString( true ) );
553     }
554
555     // Try now to get embedded art
556     StringList mime_list = tag->fieldListMap()[ "COVERARTMIME" ];
557     StringList art_list = tag->fieldListMap()[ "COVERART" ];
558
559     input_attachment_t *p_attachment;
560
561     if( mime_list.size() != 0 && art_list.size() != 0 )
562     {
563         // We get only the first covert art
564         if( mime_list.size() > 1 || art_list.size() > 1 )
565             msg_Warn( p_demux_meta, "Found %i embedded arts, so using only the first one",
566                     art_list.size() );
567
568         const char* psz_name = "cover";
569         const char* psz_mime = mime_list[0].toCString(true);
570         const char* psz_description = "cover";
571
572         uint8_t *p_data;
573         int i_data = vlc_b64_decode_binary( &p_data, art_list[0].toCString(true) );
574
575         msg_Dbg( p_demux_meta, "Found embedded art: %s (%s) is %i bytes",
576                 psz_name, psz_mime, i_data );
577
578         p_attachment = vlc_input_attachment_New( psz_name, psz_mime,
579                 psz_description, p_data, i_data );
580         free( p_data );
581     }
582     else
583     {
584         art_list = tag->fieldListMap()[ "METADATA_BLOCK_PICTURE" ];
585         if( art_list.size() == 0 )
586             return;
587
588         uint8_t *p_data;
589         int i_cover_score;
590         int i_cover_idx;
591         int i_data = vlc_b64_decode_binary( &p_data, art_list[0].toCString(true) );
592         i_cover_score = i_cover_idx = 0;
593         /* TODO: Use i_cover_score / i_cover_idx to select the picture. */
594         p_attachment = ParseFlacPicture( p_data, i_data, 0,
595             &i_cover_score, &i_cover_idx );
596     }
597
598     if (p_attachment) {
599         TAB_APPEND_CAST( (input_attachment_t**),
600                 p_demux_meta->i_attachments, p_demux_meta->attachments,
601                 p_attachment );
602
603         char *psz_url;
604         if( asprintf( &psz_url, "attachment://%s", p_attachment->psz_name ) != -1 ) {
605             vlc_meta_SetArtURL( p_meta, psz_url );
606             free( psz_url );
607         }
608     }
609 }
610
611
612 #if defined(TAGLIB_WITH_MP4)
613 /**
614  * Read the meta information from mp4 specific tags
615  * @param tag: the mp4 tag
616  * @param p_demux_meta: the demuxer meta
617  * @param p_meta: the meta
618  */
619 static void ReadMetaFromMP4( MP4::Tag* tag, demux_meta_t *p_demux_meta, vlc_meta_t* p_meta )
620 {
621     MP4::Item list;
622 #define SET( keyName, metaName )                                                             \
623     if( tag->itemListMap().contains(keyName) )                                               \
624     {                                                                                        \
625         list = tag->itemListMap()[keyName];                                                  \
626         vlc_meta_Set##metaName( p_meta, list.toStringList().front().toCString( true ) );     \
627     }
628 #define SET_EXTRA( keyName, metaName )                                                   \
629     if( tag->itemListMap().contains(keyName) )                                  \
630     {                                                                                \
631         list = tag->itemListMap()[keyName];                                     \
632         vlc_meta_AddExtra( p_meta, metaName, list.toStringList().front().toCString( true ) ); \
633     }
634
635     SET("----:com.apple.iTunes:MusicBrainz Track Id", TrackID );
636     SET_EXTRA("----:com.apple.iTunes:MusicBrainz Album Id", VLC_META_EXTRA_MB_ALBUMID );
637
638 #undef SET
639 #undef SET_EXTRA
640
641     if( tag->itemListMap().contains("covr") )
642     {
643         MP4::CoverArtList list = tag->itemListMap()["covr"].toCoverArtList();
644         const char *psz_format = list[0].format() == MP4::CoverArt::PNG ? "image/png" : "image/jpeg";
645
646         msg_Dbg( p_demux_meta, "Found embedded art (%s) is %i bytes",
647                  psz_format, list[0].data().size() );
648
649         input_attachment_t *p_attachment =
650                 vlc_input_attachment_New( "cover", psz_format, "cover",
651                                           list[0].data().data(), list[0].data().size() );
652         TAB_APPEND_CAST( (input_attachment_t**),
653                          p_demux_meta->i_attachments, p_demux_meta->attachments,
654                          p_attachment );
655         vlc_meta_SetArtURL( p_meta, "attachment://cover" );
656     }
657 }
658 #endif
659
660
661 /**
662  * Get the tags from the file using TagLib
663  * @param p_this: the demux object
664  * @return VLC_SUCCESS if the operation success
665  */
666 static int ReadMeta( vlc_object_t* p_this)
667 {
668     vlc_mutex_locker locker (&taglib_lock);
669     demux_meta_t*   p_demux_meta = (demux_meta_t *)p_this;
670     demux_t*        p_demux = p_demux_meta->p_demux;
671     vlc_meta_t*     p_meta;
672     FileRef f;
673
674     p_demux_meta->p_meta = NULL;
675     if( strcmp( p_demux->psz_access, "file" ) )
676         return VLC_EGENERIC;
677
678     char *psz_path = strdup( p_demux->psz_file );
679     if( !psz_path )
680         return VLC_ENOMEM;
681
682 #if defined(_WIN32)
683     wchar_t *wpath = ToWide( psz_path );
684     if( wpath == NULL )
685     {
686         free( psz_path );
687         return VLC_EGENERIC;
688     }
689     f = FileRef( wpath );
690     free( wpath );
691 #else
692     f = FileRef( psz_path );
693 #endif
694     free( psz_path );
695
696     if( f.isNull() )
697         return VLC_EGENERIC;
698     if( !f.tag() || f.tag()->isEmpty() )
699         return VLC_EGENERIC;
700
701     p_demux_meta->p_meta = p_meta = vlc_meta_New();
702     if( !p_meta )
703         return VLC_ENOMEM;
704
705
706     // Read the tags from the file
707     Tag* p_tag = f.tag();
708
709 #define SET( tag, meta )                                                       \
710     if( !p_tag->tag().isNull() && !p_tag->tag().isEmpty() )                    \
711         vlc_meta_Set##meta( p_meta, p_tag->tag().toCString(true) )
712 #define SETINT( tag, meta )                                                    \
713     if( p_tag->tag() )                                                         \
714     {                                                                          \
715         char psz_tmp[10];                                                      \
716         snprintf( psz_tmp, 10, "%d", p_tag->tag() );                           \
717         vlc_meta_Set##meta( p_meta, psz_tmp );                                 \
718     }
719
720     SET( title, Title );
721     SET( artist, Artist );
722     SET( album, Album );
723     SET( comment, Description );
724     SET( genre, Genre );
725     SETINT( year, Date );
726     SETINT( track, TrackNum );
727
728 #undef SETINT
729 #undef SET
730
731     TAB_INIT( p_demux_meta->i_attachments, p_demux_meta->attachments );
732
733     // Try now to read special tags
734 #ifdef TAGLIB_HAVE_APEFILE_H
735     if( APE::File* ape = dynamic_cast<APE::File*>(f.file()) )
736     {
737         if( ape->APETag() )
738             ReadMetaFromAPE( ape->APETag(), p_demux_meta, p_meta );
739     }
740     else
741 #endif
742 #ifdef TAGLIB_WITH_ASF
743     if( ASF::File* asf = dynamic_cast<ASF::File*>(f.file()) )
744     {
745         if( asf->tag() )
746             ReadMetaFromASF( asf->tag(), p_demux_meta, p_meta );
747     }
748     else
749 #endif
750     if( FLAC::File* flac = dynamic_cast<FLAC::File*>(f.file()) )
751     {
752         if( flac->ID3v2Tag() )
753             ReadMetaFromId3v2( flac->ID3v2Tag(), p_demux_meta, p_meta );
754         else if( flac->xiphComment() )
755             ReadMetaFromXiph( flac->xiphComment(), p_demux_meta, p_meta );
756     }
757 #if defined(TAGLIB_WITH_MP4)
758     else if( MP4::File *mp4 = dynamic_cast<MP4::File*>(f.file()) )
759     {
760         if( mp4->tag() )
761             ReadMetaFromMP4( mp4->tag(), p_demux_meta, p_meta );
762     }
763 #endif
764     else if( MPC::File* mpc = dynamic_cast<MPC::File*>(f.file()) )
765     {
766         if( mpc->APETag() )
767             ReadMetaFromAPE( mpc->APETag(), p_demux_meta, p_meta );
768     }
769     else if( MPEG::File* mpeg = dynamic_cast<MPEG::File*>(f.file()) )
770     {
771         if( mpeg->APETag() )
772             ReadMetaFromAPE( mpeg->APETag(), p_demux_meta, p_meta );
773         if( mpeg->ID3v2Tag() )
774             ReadMetaFromId3v2( mpeg->ID3v2Tag(), p_demux_meta, p_meta );
775     }
776     else if( dynamic_cast<Ogg::File*>(f.file()) )
777     {
778         if( Ogg::FLAC::File* ogg_flac = dynamic_cast<Ogg::FLAC::File*>(f.file()))
779             ReadMetaFromXiph( ogg_flac->tag(), p_demux_meta, p_meta );
780         else if( Ogg::Speex::File* ogg_speex = dynamic_cast<Ogg::Speex::File*>(f.file()) )
781             ReadMetaFromXiph( ogg_speex->tag(), p_demux_meta, p_meta );
782         else if( Ogg::Vorbis::File* ogg_vorbis = dynamic_cast<Ogg::Vorbis::File*>(f.file()) )
783             ReadMetaFromXiph( ogg_vorbis->tag(), p_demux_meta, p_meta );
784 #if defined(TAGLIB_OPUSFILE_H)
785         else if( Ogg::Opus::File* ogg_opus = dynamic_cast<Ogg::Opus::File*>(f.file()) )
786             ReadMetaFromXiph( ogg_opus->tag(), p_demux_meta, p_meta );
787 #endif
788     }
789     else if( dynamic_cast<RIFF::File*>(f.file()) )
790     {
791         if( RIFF::AIFF::File* riff_aiff = dynamic_cast<RIFF::AIFF::File*>(f.file()) )
792             ReadMetaFromId3v2( riff_aiff->tag(), p_demux_meta, p_meta );
793         else if( RIFF::WAV::File* riff_wav = dynamic_cast<RIFF::WAV::File*>(f.file()) )
794             ReadMetaFromId3v2( riff_wav->tag(), p_demux_meta, p_meta );
795     }
796     else if( TrueAudio::File* trueaudio = dynamic_cast<TrueAudio::File*>(f.file()) )
797     {
798         if( trueaudio->ID3v2Tag() )
799             ReadMetaFromId3v2( trueaudio->ID3v2Tag(), p_demux_meta, p_meta );
800     }
801     else if( WavPack::File* wavpack = dynamic_cast<WavPack::File*>(f.file()) )
802     {
803         if( wavpack->APETag() )
804             ReadMetaFromAPE( wavpack->APETag(), p_demux_meta, p_meta );
805     }
806
807     return VLC_SUCCESS;
808 }
809
810
811 /**
812  * Write meta information to APE tags
813  * @param tag: the APE tag
814  * @param p_item: the input item
815  */
816 static void WriteMetaToAPE( APE::Tag* tag, input_item_t* p_item )
817 {
818     char* psz_meta;
819 #define WRITE( metaName, keyName )                      \
820     psz_meta = input_item_Get##metaName( p_item );      \
821     if( psz_meta )                                      \
822     {                                                   \
823         String key( keyName, String::UTF8 );            \
824         String value( psz_meta, String::UTF8 );         \
825         tag->addValue( key, value, true );              \
826     }                                                   \
827     free( psz_meta );
828
829     WRITE( Copyright, "COPYRIGHT" );
830     WRITE( Language, "LANGUAGE" );
831     WRITE( Publisher, "PUBLISHER" );
832     WRITE( TrackID, "MUSICBRAINZ_TRACKID" );
833 #undef WRITE
834 }
835
836
837 /**
838  * Write meta information to id3v2 tags
839  * @param tag: the id3v2 tag
840  * @param p_input: the input item
841  */
842 static void WriteMetaToId3v2( ID3v2::Tag* tag, input_item_t* p_item )
843 {
844     char* psz_meta;
845 #define WRITE( metaName, tagName )                                            \
846     psz_meta = input_item_Get##metaName( p_item );                            \
847     if( psz_meta )                                                            \
848     {                                                                         \
849         ByteVector p_byte( tagName, 4 );                                      \
850         tag->removeFrames( p_byte );                                         \
851         ID3v2::TextIdentificationFrame* p_frame =                             \
852             new ID3v2::TextIdentificationFrame( p_byte, String::UTF8 );       \
853         p_frame->setText( psz_meta );                                         \
854         tag->addFrame( p_frame );                                             \
855     }                                                                         \
856     free( psz_meta );
857
858     WRITE( Copyright, "TCOP" );
859     WRITE( EncodedBy, "TENC" );
860     WRITE( Language,  "TLAN" );
861     WRITE( Publisher, "TPUB" );
862
863 #undef WRITE
864     /* Known TXXX frames */
865     ID3v2::FrameList list = tag->frameListMap()["TXXX"];
866
867 #define WRITETXXX( metaName, txxName )\
868     psz_meta = input_item_Get##metaName( p_item );                                       \
869     if ( psz_meta )                                                                      \
870     {                                                                                    \
871         ID3v2::UserTextIdentificationFrame *p_txxx;                                      \
872         for( ID3v2::FrameList::Iterator iter = list.begin(); iter != list.end(); iter++ )\
873         {                                                                                \
874             p_txxx = dynamic_cast<ID3v2::UserTextIdentificationFrame*>(*iter);           \
875             if( !p_txxx )                                                                \
876                 continue;                                                                \
877             if( !strcmp( p_txxx->description().toCString( true ), txxName ) )            \
878             {                                                                            \
879                 p_txxx->setText( psz_meta );                                             \
880                 FREENULL( psz_meta );                                                    \
881                 break;                                                                   \
882             }                                                                            \
883         }                                                                                \
884         if( psz_meta ) /* not found in existing custom fields */                         \
885         {                                                                                \
886             ByteVector p_byte( "TXXX", 4 );                                              \
887             p_txxx = new ID3v2::UserTextIdentificationFrame( p_byte );                   \
888             p_txxx->setDescription( txxName );                                           \
889             p_txxx->setText( psz_meta );                                                 \
890             free( psz_meta );                                                            \
891             tag->addFrame( p_txxx );                                                     \
892         }                                                                                \
893     }
894
895     WRITETXXX( TrackTotal, "TRACKTOTAL" );
896
897 #undef WRITETXXX
898
899     /* Write album art */
900     char *psz_url = input_item_GetArtworkURL( p_item );
901     if( psz_url == NULL )
902         return;
903
904     char *psz_path = make_path( psz_url );
905     free( psz_url );
906     if( psz_path == NULL )
907         return;
908
909     const char *psz_mime = vlc_mime_Ext2Mime( psz_path );
910
911     FILE *p_file = vlc_fopen( psz_path, "rb" );
912     if( p_file == NULL )
913     {
914         free( psz_path );
915         return;
916     }
917
918     struct stat st;
919     if( vlc_stat( psz_path, &st ) == -1 )
920     {
921         free( psz_path );
922         fclose( p_file );
923         return;
924     }
925     off_t file_size = st.st_size;
926
927     free( psz_path );
928
929     /* Limit picture size to 10MiB */
930     if( file_size > 10485760 )
931     {
932       fclose( p_file );
933       return;
934     }
935
936     char *p_buffer = new (std::nothrow) char[file_size];
937     if( p_buffer == NULL )
938     {
939         fclose( p_file );
940         return;
941     }
942
943     if( fread( p_buffer, 1, file_size, p_file ) != (unsigned)file_size )
944     {
945         fclose( p_file );
946         delete[] p_buffer;
947         return;
948     }
949     fclose( p_file );
950
951     ByteVector data( p_buffer, file_size );
952     delete[] p_buffer;
953
954     ID3v2::FrameList frames = tag->frameList( "APIC" );
955     ID3v2::AttachedPictureFrame *frame = NULL;
956     if( frames.isEmpty() )
957     {
958         frame = new TagLib::ID3v2::AttachedPictureFrame;
959         tag->addFrame( frame );
960     }
961     else
962     {
963         frame = static_cast<ID3v2::AttachedPictureFrame *>( frames.back() );
964     }
965
966     frame->setPicture( data );
967     frame->setMimeType( psz_mime );
968 }
969
970
971 /**
972  * Write the meta information to XiphComments
973  * @param tag: the Xiph Comment
974  * @param p_input: the input item
975  */
976 static void WriteMetaToXiph( Ogg::XiphComment* tag, input_item_t* p_item )
977 {
978     char* psz_meta;
979 #define WRITE( metaName, keyName )                      \
980     psz_meta = input_item_Get##metaName( p_item );      \
981     if( psz_meta )                                      \
982     {                                                   \
983         String key( keyName, String::UTF8 );            \
984         String value( psz_meta, String::UTF8 );         \
985         tag->addField( key, value, true );              \
986     }                                                   \
987     free( psz_meta );
988
989     WRITE( TrackNum, "TRACKNUMBER" );
990     WRITE( TrackTotal, "TRACKTOTAL" );
991     WRITE( Copyright, "COPYRIGHT" );
992     WRITE( Publisher, "ORGANIZATION" );
993     WRITE( Date, "DATE" );
994     WRITE( EncodedBy, "ENCODER" );
995     WRITE( Rating, "RATING" );
996     WRITE( Language, "LANGUAGE" );
997     WRITE( TrackID, "MUSICBRAINZ_TRACKID" );
998 #undef WRITE
999 }
1000
1001
1002 /**
1003  * Set the tags to the file using TagLib
1004  * @param p_this: the demux object
1005  * @return VLC_SUCCESS if the operation success
1006  */
1007
1008 static int WriteMeta( vlc_object_t *p_this )
1009 {
1010     vlc_mutex_locker locker (&taglib_lock);
1011     meta_export_t *p_export = (meta_export_t *)p_this;
1012     input_item_t *p_item = p_export->p_item;
1013     FileRef f;
1014
1015     if( !p_item )
1016     {
1017         msg_Err( p_this, "Can't save meta data of an empty input" );
1018         return VLC_EGENERIC;
1019     }
1020
1021 #if defined(_WIN32)
1022     wchar_t *wpath = ToWide( p_export->psz_file );
1023     if( wpath == NULL )
1024         return VLC_EGENERIC;
1025     f = FileRef( wpath );
1026     free( wpath );
1027 #else
1028     f = FileRef( p_export->psz_file );
1029 #endif
1030
1031     if( f.isNull() || !f.tag() || f.file()->readOnly() )
1032     {
1033         msg_Err( p_this, "File %s can't be opened for tag writing",
1034                  p_export->psz_file );
1035         return VLC_EGENERIC;
1036     }
1037
1038     msg_Dbg( p_this, "Writing metadata for %s", p_export->psz_file );
1039
1040     Tag *p_tag = f.tag();
1041
1042     char *psz_meta;
1043
1044 #define SET( a, b )                                             \
1045     psz_meta = input_item_Get ## a( p_item );                   \
1046     if( psz_meta )                                              \
1047     {                                                           \
1048         String tmp( psz_meta, String::UTF8 );                   \
1049         p_tag->set##b( tmp );                                   \
1050     }                                                           \
1051     free( psz_meta );
1052
1053     // Saving all common fields
1054     // If the title is empty, use the name
1055     SET( TitleFbName, Title );
1056     SET( Artist, Artist );
1057     SET( Album, Album );
1058     SET( Description, Comment );
1059     SET( Genre, Genre );
1060
1061 #undef SET
1062
1063     psz_meta = input_item_GetDate( p_item );
1064     if( !EMPTY_STR(psz_meta) ) p_tag->setYear( atoi( psz_meta ) );
1065     else p_tag->setYear( 0 );
1066     free( psz_meta );
1067
1068     psz_meta = input_item_GetTrackNum( p_item );
1069     if( !EMPTY_STR(psz_meta) ) p_tag->setTrack( atoi( psz_meta ) );
1070     else p_tag->setTrack( 0 );
1071     free( psz_meta );
1072
1073
1074     // Try now to write special tags
1075 #ifdef TAGLIB_HAVE_APEFILE_H
1076     if( APE::File* ape = dynamic_cast<APE::File*>(f.file()) )
1077     {
1078         if( ape->APETag() )
1079             WriteMetaToAPE( ape->APETag(), p_item );
1080     }
1081     else
1082 #endif
1083     if( FLAC::File* flac = dynamic_cast<FLAC::File*>(f.file()) )
1084     {
1085         if( flac->ID3v2Tag() )
1086             WriteMetaToId3v2( flac->ID3v2Tag(), p_item );
1087         else if( flac->xiphComment() )
1088             WriteMetaToXiph( flac->xiphComment(), p_item );
1089     }
1090     else if( MPC::File* mpc = dynamic_cast<MPC::File*>(f.file()) )
1091     {
1092         if( mpc->APETag() )
1093             WriteMetaToAPE( mpc->APETag(), p_item );
1094     }
1095     else if( MPEG::File* mpeg = dynamic_cast<MPEG::File*>(f.file()) )
1096     {
1097         if( mpeg->ID3v2Tag() )
1098             WriteMetaToId3v2( mpeg->ID3v2Tag(), p_item );
1099         else if( mpeg->APETag() )
1100             WriteMetaToAPE( mpeg->APETag(), p_item );
1101     }
1102     else if( dynamic_cast<Ogg::File*>(f.file()) )
1103     {
1104         if( Ogg::FLAC::File* ogg_flac = dynamic_cast<Ogg::FLAC::File*>(f.file()))
1105             WriteMetaToXiph( ogg_flac->tag(), p_item );
1106         else if( Ogg::Speex::File* ogg_speex = dynamic_cast<Ogg::Speex::File*>(f.file()) )
1107             WriteMetaToXiph( ogg_speex->tag(), p_item );
1108         else if( Ogg::Vorbis::File* ogg_vorbis = dynamic_cast<Ogg::Vorbis::File*>(f.file()) )
1109             WriteMetaToXiph( ogg_vorbis->tag(), p_item );
1110 #if defined(TAGLIB_OPUSFILE_H)
1111         else if( Ogg::Opus::File* ogg_opus = dynamic_cast<Ogg::Opus::File*>(f.file()) )
1112             WriteMetaToXiph( ogg_opus->tag(), p_item );
1113 #endif
1114     }
1115     else if( dynamic_cast<RIFF::File*>(f.file()) )
1116     {
1117         if( RIFF::AIFF::File* riff_aiff = dynamic_cast<RIFF::AIFF::File*>(f.file()) )
1118             WriteMetaToId3v2( riff_aiff->tag(), p_item );
1119         else if( RIFF::WAV::File* riff_wav = dynamic_cast<RIFF::WAV::File*>(f.file()) )
1120             WriteMetaToId3v2( riff_wav->tag(), p_item );
1121     }
1122     else if( TrueAudio::File* trueaudio = dynamic_cast<TrueAudio::File*>(f.file()) )
1123     {
1124         if( trueaudio->ID3v2Tag() )
1125             WriteMetaToId3v2( trueaudio->ID3v2Tag(), p_item );
1126     }
1127     else if( WavPack::File* wavpack = dynamic_cast<WavPack::File*>(f.file()) )
1128     {
1129         if( wavpack->APETag() )
1130             WriteMetaToAPE( wavpack->APETag(), p_item );
1131     }
1132
1133     // Save the meta data
1134     f.save();
1135
1136     return VLC_SUCCESS;
1137 }