]> git.sesse.net Git - vlc/blob - modules/meta_engine/taglib.cpp
taglib: do not ignore mpeg ape tags
[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
375 #undef SET
376
377     /* */
378     list = tag->frameListMap()["TRCK"];
379     if( !list.isEmpty() )
380     {
381         ExtractTrackNumberValues( p_meta, (*list.begin())->toString().toCString( true ) );
382     }
383
384     /* Preferred type of image
385      * The 21 types are defined in id3v2 standard:
386      * http://www.id3.org/id3v2.4.0-frames */
387     static const int pi_cover_score[] = {
388         0,  /* Other */
389         5,  /* 32x32 PNG image that should be used as the file icon */
390         4,  /* File icon of a different size or format. */
391         20, /* Front cover image of the album. */
392         19, /* Back cover image of the album. */
393         13, /* Inside leaflet page of the album. */
394         18, /* Image from the album itself. */
395         17, /* Picture of the lead artist or soloist. */
396         16, /* Picture of the artist or performer. */
397         14, /* Picture of the conductor. */
398         15, /* Picture of the band or orchestra. */
399         9,  /* Picture of the composer. */
400         8,  /* Picture of the lyricist or text writer. */
401         7,  /* Picture of the recording location or studio. */
402         10, /* Picture of the artists during recording. */
403         11, /* Picture of the artists during performance. */
404         6,  /* Picture from a movie or video related to the track. */
405         1,  /* Picture of a large, coloured fish. */
406         12, /* Illustration related to the track. */
407         3,  /* Logo of the band or performer. */
408         2   /* Logo of the publisher (record company). */
409     };
410     #define PI_COVER_SCORE_SIZE (sizeof (pi_cover_score) / sizeof (pi_cover_score[0]))
411     int i_score = -1;
412
413     // Try now to get embedded art
414     list = tag->frameListMap()[ "APIC" ];
415     if( list.isEmpty() )
416         return;
417
418     for( iter = list.begin(); iter != list.end(); iter++ )
419     {
420         ID3v2::AttachedPictureFrame* p_apic =
421             dynamic_cast<ID3v2::AttachedPictureFrame*>(*iter);
422         if( !p_apic )
423             continue;
424         input_attachment_t *p_attachment;
425
426         const char *psz_mime;
427         char *psz_name, *psz_description;
428
429         // Get the mime and description of the image.
430         // If the description is empty, take the type as a description
431         psz_mime = p_apic->mimeType().toCString( true );
432         if( p_apic->description().size() > 0 )
433             psz_description = strdup( p_apic->description().toCString( true ) );
434         else
435         {
436             if( asprintf( &psz_description, "%i", p_apic->type() ) == -1 )
437                 psz_description = NULL;
438         }
439
440         if( !psz_description )
441             continue;
442         psz_name = psz_description;
443
444         /* some old iTunes version not only sets incorrectly the mime type
445          * or the description of the image,
446          * but also embeds incorrectly the image.
447          * Recent versions seem to behave correctly */
448         if( !strncmp( psz_mime, "PNG", 3 ) ||
449             !strncmp( psz_name, "\xC2\x89PNG", 5 ) )
450         {
451             msg_Warn( p_demux_meta, "Invalid picture embedded by broken iTunes version" );
452             free( psz_description );
453             continue;
454         }
455
456         const ByteVector picture = p_apic->picture();
457         const char *p_data = picture.data();
458         const unsigned i_data = picture.size();
459
460         msg_Dbg( p_demux_meta, "Found embedded art: %s (%s) is %u bytes",
461                  psz_name, psz_mime, i_data );
462
463         p_attachment = vlc_input_attachment_New( psz_name, psz_mime,
464                                 psz_description, p_data, i_data );
465         if( !p_attachment )
466         {
467             free( psz_description );
468             continue;
469         }
470         TAB_APPEND_CAST( (input_attachment_t**),
471                          p_demux_meta->i_attachments, p_demux_meta->attachments,
472                          p_attachment );
473         free( psz_description );
474
475         unsigned i_pic_type = p_apic->type();
476         if( i_pic_type >= PI_COVER_SCORE_SIZE )
477             i_pic_type = 0; // Defaults to "Other"
478
479         if( pi_cover_score[i_pic_type] > i_score )
480         {
481             i_score = pi_cover_score[i_pic_type];
482             char *psz_url;
483             if( asprintf( &psz_url, "attachment://%s",
484                           p_attachment->psz_name ) == -1 )
485                 continue;
486             vlc_meta_SetArtURL( p_meta, psz_url );
487             free( psz_url );
488         }
489     }
490 }
491
492
493 /**
494  * Read the meta information from XiphComments
495  * @param tag: the Xiph Comment
496  * @param p_demux_meta: the demuxer meta
497  * @param p_meta: the meta
498  */
499 static void ReadMetaFromXiph( Ogg::XiphComment* tag, demux_meta_t* p_demux_meta, vlc_meta_t* p_meta )
500 {
501     StringList list;
502     bool hasTrackTotal = false;
503 #define SET( keyName, metaName )                                               \
504     list = tag->fieldListMap()[keyName];                                       \
505     if( !list.isEmpty() )                                                      \
506         vlc_meta_Set##metaName( p_meta, (*list.begin()).toCString( true ) );
507
508 #define SET_EXTRA( keyName, metaName ) \
509     list = tag->fieldListMap()[keyName]; \
510     if( !list.isEmpty() ) \
511         vlc_meta_AddExtra( p_meta, keyName, (*list.begin()).toCString( true ) );
512
513     SET( "COPYRIGHT", Copyright );
514     SET( "ORGANIZATION", Publisher );
515     SET( "DATE", Date );
516     SET( "ENCODER", EncodedBy );
517     SET( "RATING", Rating );
518     SET( "LANGUAGE", Language );
519     SET( "MUSICBRAINZ_TRACKID", TrackID );
520
521     SET_EXTRA( "MUSICBRAINZ_ALBUMID", VLC_META_EXTRA_MB_ALBUMID );
522 #undef SET
523 #undef SET_EXTRA
524
525     list = tag->fieldListMap()["TRACKNUMBER"];
526     if( !list.isEmpty() )
527     {
528         const char *psz_value;
529         unsigned short u_track;
530         unsigned short u_total;
531         psz_value = (*list.begin()).toCString( true );
532         if( sscanf( psz_value, "%hu/%hu", &u_track, &u_total ) == 2)
533         {
534             char str[6];
535             snprintf(str, 6, "%u", u_track);
536             vlc_meta_SetTrackNum( p_meta, str);
537             snprintf(str, 6, "%u", u_total);
538             vlc_meta_SetTrackTotal( p_meta, str);
539             hasTrackTotal = true;
540         }
541         else
542             vlc_meta_SetTrackNum( p_meta, psz_value);
543     }
544     if( !hasTrackTotal )
545     {
546         list = tag->fieldListMap()["TRACKTOTAL"];
547         if( list.isEmpty() )
548             list = tag->fieldListMap()["TOTALTRACKS"];
549         if( !list.isEmpty() )
550             vlc_meta_SetTrackTotal( p_meta, (*list.begin()).toCString( true ) );
551     }
552
553     // Try now to get embedded art
554     StringList mime_list = tag->fieldListMap()[ "COVERARTMIME" ];
555     StringList art_list = tag->fieldListMap()[ "COVERART" ];
556
557     input_attachment_t *p_attachment;
558
559     if( mime_list.size() != 0 && art_list.size() != 0 )
560     {
561         // We get only the first covert art
562         if( mime_list.size() > 1 || art_list.size() > 1 )
563             msg_Warn( p_demux_meta, "Found %i embedded arts, so using only the first one",
564                     art_list.size() );
565
566         const char* psz_name = "cover";
567         const char* psz_mime = mime_list[0].toCString(true);
568         const char* psz_description = "cover";
569
570         uint8_t *p_data;
571         int i_data = vlc_b64_decode_binary( &p_data, art_list[0].toCString(true) );
572
573         msg_Dbg( p_demux_meta, "Found embedded art: %s (%s) is %i bytes",
574                 psz_name, psz_mime, i_data );
575
576         p_attachment = vlc_input_attachment_New( psz_name, psz_mime,
577                 psz_description, p_data, i_data );
578         free( p_data );
579     }
580     else
581     {
582         art_list = tag->fieldListMap()[ "METADATA_BLOCK_PICTURE" ];
583         if( art_list.size() == 0 )
584             return;
585
586         uint8_t *p_data;
587         int i_cover_score;
588         int i_cover_idx;
589         int i_data = vlc_b64_decode_binary( &p_data, art_list[0].toCString(true) );
590         i_cover_score = i_cover_idx = 0;
591         /* TODO: Use i_cover_score / i_cover_idx to select the picture. */
592         p_attachment = ParseFlacPicture( p_data, i_data, 0,
593             &i_cover_score, &i_cover_idx );
594     }
595
596     if (p_attachment) {
597         TAB_APPEND_CAST( (input_attachment_t**),
598                 p_demux_meta->i_attachments, p_demux_meta->attachments,
599                 p_attachment );
600
601         char *psz_url;
602         if( asprintf( &psz_url, "attachment://%s", p_attachment->psz_name ) != -1 ) {
603             vlc_meta_SetArtURL( p_meta, psz_url );
604             free( psz_url );
605         }
606     }
607 }
608
609
610 #if defined(TAGLIB_WITH_MP4)
611 /**
612  * Read the meta information from mp4 specific tags
613  * @param tag: the mp4 tag
614  * @param p_demux_meta: the demuxer meta
615  * @param p_meta: the meta
616  */
617 static void ReadMetaFromMP4( MP4::Tag* tag, demux_meta_t *p_demux_meta, vlc_meta_t* p_meta )
618 {
619     MP4::Item list;
620 #define SET( keyName, metaName )                                                             \
621     if( tag->itemListMap().contains(keyName) )                                               \
622     {                                                                                        \
623         list = tag->itemListMap()[keyName];                                                  \
624         vlc_meta_Set##metaName( p_meta, list.toStringList().front().toCString( true ) );     \
625     }
626 #define SET_EXTRA( keyName, metaName )                                                   \
627     if( tag->itemListMap().contains(keyName) )                                  \
628     {                                                                                \
629         list = tag->itemListMap()[keyName];                                     \
630         vlc_meta_AddExtra( p_meta, metaName, list.toStringList().front().toCString( true ) ); \
631     }
632
633     SET("----:com.apple.iTunes:MusicBrainz Track Id", TrackID );
634     SET_EXTRA("----:com.apple.iTunes:MusicBrainz Album Id", VLC_META_EXTRA_MB_ALBUMID );
635
636 #undef SET
637 #undef SET_EXTRA
638
639     if( tag->itemListMap().contains("covr") )
640     {
641         MP4::CoverArtList list = tag->itemListMap()["covr"].toCoverArtList();
642         const char *psz_format = list[0].format() == MP4::CoverArt::PNG ? "image/png" : "image/jpeg";
643
644         msg_Dbg( p_demux_meta, "Found embedded art (%s) is %i bytes",
645                  psz_format, list[0].data().size() );
646
647         input_attachment_t *p_attachment =
648                 vlc_input_attachment_New( "cover", psz_format, "cover",
649                                           list[0].data().data(), list[0].data().size() );
650         TAB_APPEND_CAST( (input_attachment_t**),
651                          p_demux_meta->i_attachments, p_demux_meta->attachments,
652                          p_attachment );
653         vlc_meta_SetArtURL( p_meta, "attachment://cover" );
654     }
655 }
656 #endif
657
658
659 /**
660  * Get the tags from the file using TagLib
661  * @param p_this: the demux object
662  * @return VLC_SUCCESS if the operation success
663  */
664 static int ReadMeta( vlc_object_t* p_this)
665 {
666     vlc_mutex_locker locker (&taglib_lock);
667     demux_meta_t*   p_demux_meta = (demux_meta_t *)p_this;
668     demux_t*        p_demux = p_demux_meta->p_demux;
669     vlc_meta_t*     p_meta;
670     FileRef f;
671
672     p_demux_meta->p_meta = NULL;
673     if( strcmp( p_demux->psz_access, "file" ) )
674         return VLC_EGENERIC;
675
676     char *psz_path = strdup( p_demux->psz_file );
677     if( !psz_path )
678         return VLC_ENOMEM;
679
680 #if defined(_WIN32)
681     wchar_t *wpath = ToWide( psz_path );
682     if( wpath == NULL )
683     {
684         free( psz_path );
685         return VLC_EGENERIC;
686     }
687     f = FileRef( wpath );
688     free( wpath );
689 #else
690     f = FileRef( psz_path );
691 #endif
692     free( psz_path );
693
694     if( f.isNull() )
695         return VLC_EGENERIC;
696     if( !f.tag() || f.tag()->isEmpty() )
697         return VLC_EGENERIC;
698
699     p_demux_meta->p_meta = p_meta = vlc_meta_New();
700     if( !p_meta )
701         return VLC_ENOMEM;
702
703
704     // Read the tags from the file
705     Tag* p_tag = f.tag();
706
707 #define SET( tag, meta )                                                       \
708     if( !p_tag->tag().isNull() && !p_tag->tag().isEmpty() )                    \
709         vlc_meta_Set##meta( p_meta, p_tag->tag().toCString(true) )
710 #define SETINT( tag, meta )                                                    \
711     if( p_tag->tag() )                                                         \
712     {                                                                          \
713         char psz_tmp[10];                                                      \
714         snprintf( psz_tmp, 10, "%d", p_tag->tag() );                           \
715         vlc_meta_Set##meta( p_meta, psz_tmp );                                 \
716     }
717
718     SET( title, Title );
719     SET( artist, Artist );
720     SET( album, Album );
721     SET( comment, Description );
722     SET( genre, Genre );
723     SETINT( year, Date );
724     SETINT( track, TrackNum );
725
726 #undef SETINT
727 #undef SET
728
729     TAB_INIT( p_demux_meta->i_attachments, p_demux_meta->attachments );
730
731     // Try now to read special tags
732 #ifdef TAGLIB_HAVE_APEFILE_H
733     if( APE::File* ape = dynamic_cast<APE::File*>(f.file()) )
734     {
735         if( ape->APETag() )
736             ReadMetaFromAPE( ape->APETag(), p_demux_meta, p_meta );
737     }
738     else
739 #endif
740 #ifdef TAGLIB_WITH_ASF
741     if( ASF::File* asf = dynamic_cast<ASF::File*>(f.file()) )
742     {
743         if( asf->tag() )
744             ReadMetaFromASF( asf->tag(), p_demux_meta, p_meta );
745     }
746     else
747 #endif
748     if( FLAC::File* flac = dynamic_cast<FLAC::File*>(f.file()) )
749     {
750         if( flac->ID3v2Tag() )
751             ReadMetaFromId3v2( flac->ID3v2Tag(), p_demux_meta, p_meta );
752         else if( flac->xiphComment() )
753             ReadMetaFromXiph( flac->xiphComment(), p_demux_meta, p_meta );
754     }
755 #if defined(TAGLIB_WITH_MP4)
756     else if( MP4::File *mp4 = dynamic_cast<MP4::File*>(f.file()) )
757     {
758         if( mp4->tag() )
759             ReadMetaFromMP4( mp4->tag(), p_demux_meta, p_meta );
760     }
761 #endif
762     else if( MPC::File* mpc = dynamic_cast<MPC::File*>(f.file()) )
763     {
764         if( mpc->APETag() )
765             ReadMetaFromAPE( mpc->APETag(), p_demux_meta, p_meta );
766     }
767     else if( MPEG::File* mpeg = dynamic_cast<MPEG::File*>(f.file()) )
768     {
769         if( mpeg->APETag() )
770             ReadMetaFromAPE( mpeg->APETag(), p_demux_meta, p_meta );
771         if( mpeg->ID3v2Tag() )
772             ReadMetaFromId3v2( mpeg->ID3v2Tag(), p_demux_meta, p_meta );
773     }
774     else if( dynamic_cast<Ogg::File*>(f.file()) )
775     {
776         if( Ogg::FLAC::File* ogg_flac = dynamic_cast<Ogg::FLAC::File*>(f.file()))
777             ReadMetaFromXiph( ogg_flac->tag(), p_demux_meta, p_meta );
778         else if( Ogg::Speex::File* ogg_speex = dynamic_cast<Ogg::Speex::File*>(f.file()) )
779             ReadMetaFromXiph( ogg_speex->tag(), p_demux_meta, p_meta );
780         else if( Ogg::Vorbis::File* ogg_vorbis = dynamic_cast<Ogg::Vorbis::File*>(f.file()) )
781             ReadMetaFromXiph( ogg_vorbis->tag(), p_demux_meta, p_meta );
782 #if defined(TAGLIB_OPUSFILE_H)
783         else if( Ogg::Opus::File* ogg_opus = dynamic_cast<Ogg::Opus::File*>(f.file()) )
784             ReadMetaFromXiph( ogg_opus->tag(), p_demux_meta, p_meta );
785 #endif
786     }
787     else if( dynamic_cast<RIFF::File*>(f.file()) )
788     {
789         if( RIFF::AIFF::File* riff_aiff = dynamic_cast<RIFF::AIFF::File*>(f.file()) )
790             ReadMetaFromId3v2( riff_aiff->tag(), p_demux_meta, p_meta );
791         else if( RIFF::WAV::File* riff_wav = dynamic_cast<RIFF::WAV::File*>(f.file()) )
792             ReadMetaFromId3v2( riff_wav->tag(), p_demux_meta, p_meta );
793     }
794     else if( TrueAudio::File* trueaudio = dynamic_cast<TrueAudio::File*>(f.file()) )
795     {
796         if( trueaudio->ID3v2Tag() )
797             ReadMetaFromId3v2( trueaudio->ID3v2Tag(), p_demux_meta, p_meta );
798     }
799     else if( WavPack::File* wavpack = dynamic_cast<WavPack::File*>(f.file()) )
800     {
801         if( wavpack->APETag() )
802             ReadMetaFromAPE( wavpack->APETag(), p_demux_meta, p_meta );
803     }
804
805     return VLC_SUCCESS;
806 }
807
808
809 /**
810  * Write meta information to APE tags
811  * @param tag: the APE tag
812  * @param p_item: the input item
813  */
814 static void WriteMetaToAPE( APE::Tag* tag, input_item_t* p_item )
815 {
816     char* psz_meta;
817 #define WRITE( metaName, keyName )                      \
818     psz_meta = input_item_Get##metaName( p_item );      \
819     if( psz_meta )                                      \
820     {                                                   \
821         String key( keyName, String::UTF8 );            \
822         String value( psz_meta, String::UTF8 );         \
823         tag->addValue( key, value, true );              \
824     }                                                   \
825     free( psz_meta );
826
827     WRITE( Copyright, "COPYRIGHT" );
828     WRITE( Language, "LANGUAGE" );
829     WRITE( Publisher, "PUBLISHER" );
830     WRITE( TrackID, "MUSICBRAINZ_TRACKID" );
831 #undef WRITE
832 }
833
834
835 /**
836  * Write meta information to id3v2 tags
837  * @param tag: the id3v2 tag
838  * @param p_input: the input item
839  */
840 static void WriteMetaToId3v2( ID3v2::Tag* tag, input_item_t* p_item )
841 {
842     char* psz_meta;
843 #define WRITE( metaName, tagName )                                            \
844     psz_meta = input_item_Get##metaName( p_item );                            \
845     if( psz_meta )                                                            \
846     {                                                                         \
847         ByteVector p_byte( tagName, 4 );                                      \
848         tag->removeFrames( p_byte );                                         \
849         ID3v2::TextIdentificationFrame* p_frame =                             \
850             new ID3v2::TextIdentificationFrame( p_byte, String::UTF8 );       \
851         p_frame->setText( psz_meta );                                         \
852         tag->addFrame( p_frame );                                             \
853     }                                                                         \
854     free( psz_meta );
855
856     WRITE( Copyright, "TCOP" );
857     WRITE( EncodedBy, "TENC" );
858     WRITE( Language,  "TLAN" );
859     WRITE( Publisher, "TPUB" );
860
861 #undef WRITE
862     /* Known TXXX frames */
863     ID3v2::FrameList list = tag->frameListMap()["TXXX"];
864
865 #define WRITETXXX( metaName, txxName )\
866     psz_meta = input_item_Get##metaName( p_item );                                       \
867     if ( psz_meta )                                                                      \
868     {                                                                                    \
869         ID3v2::UserTextIdentificationFrame *p_txxx;                                      \
870         for( ID3v2::FrameList::Iterator iter = list.begin(); iter != list.end(); iter++ )\
871         {                                                                                \
872             p_txxx = dynamic_cast<ID3v2::UserTextIdentificationFrame*>(*iter);           \
873             if( !p_txxx )                                                                \
874                 continue;                                                                \
875             if( !strcmp( p_txxx->description().toCString( true ), txxName ) )            \
876             {                                                                            \
877                 p_txxx->setText( psz_meta );                                             \
878                 FREENULL( psz_meta );                                                    \
879                 break;                                                                   \
880             }                                                                            \
881         }                                                                                \
882         if( psz_meta ) /* not found in existing custom fields */                         \
883         {                                                                                \
884             ByteVector p_byte( "TXXX", 4 );                                              \
885             p_txxx = new ID3v2::UserTextIdentificationFrame( p_byte );                   \
886             p_txxx->setDescription( txxName );                                           \
887             p_txxx->setText( psz_meta );                                                 \
888             free( psz_meta );                                                            \
889             tag->addFrame( p_txxx );                                                     \
890         }                                                                                \
891     }
892
893     WRITETXXX( TrackTotal, "TRACKTOTAL" );
894
895 #undef WRITETXXX
896
897     /* Write album art */
898     char *psz_url = input_item_GetArtworkURL( p_item );
899     if( psz_url == NULL )
900         return;
901
902     char *psz_path = make_path( psz_url );
903     free( psz_url );
904     if( psz_path == NULL )
905         return;
906
907     const char *psz_mime = vlc_mime_Ext2Mime( psz_path );
908
909     FILE *p_file = vlc_fopen( psz_path, "rb" );
910     if( p_file == NULL )
911     {
912         free( psz_path );
913         return;
914     }
915
916     struct stat st;
917     if( vlc_stat( psz_path, &st ) == -1 )
918     {
919         free( psz_path );
920         fclose( p_file );
921         return;
922     }
923     off_t file_size = st.st_size;
924
925     free( psz_path );
926
927     /* Limit picture size to 10MiB */
928     if( file_size > 10485760 )
929     {
930       fclose( p_file );
931       return;
932     }
933
934     char *p_buffer = new (std::nothrow) char[file_size];
935     if( p_buffer == NULL )
936     {
937         fclose( p_file );
938         return;
939     }
940
941     if( fread( p_buffer, 1, file_size, p_file ) != (unsigned)file_size )
942     {
943         fclose( p_file );
944         delete[] p_buffer;
945         return;
946     }
947     fclose( p_file );
948
949     ByteVector data( p_buffer, file_size );
950     delete[] p_buffer;
951
952     ID3v2::FrameList frames = tag->frameList( "APIC" );
953     ID3v2::AttachedPictureFrame *frame = NULL;
954     if( frames.isEmpty() )
955     {
956         frame = new TagLib::ID3v2::AttachedPictureFrame;
957         tag->addFrame( frame );
958     }
959     else
960     {
961         frame = static_cast<ID3v2::AttachedPictureFrame *>( frames.back() );
962     }
963
964     frame->setPicture( data );
965     frame->setMimeType( psz_mime );
966 }
967
968
969 /**
970  * Write the meta information to XiphComments
971  * @param tag: the Xiph Comment
972  * @param p_input: the input item
973  */
974 static void WriteMetaToXiph( Ogg::XiphComment* tag, input_item_t* p_item )
975 {
976     char* psz_meta;
977 #define WRITE( metaName, keyName )                      \
978     psz_meta = input_item_Get##metaName( p_item );      \
979     if( psz_meta )                                      \
980     {                                                   \
981         String key( keyName, String::UTF8 );            \
982         String value( psz_meta, String::UTF8 );         \
983         tag->addField( key, value, true );              \
984     }                                                   \
985     free( psz_meta );
986
987     WRITE( TrackNum, "TRACKNUMBER" );
988     WRITE( TrackTotal, "TRACKTOTAL" );
989     WRITE( Copyright, "COPYRIGHT" );
990     WRITE( Publisher, "ORGANIZATION" );
991     WRITE( Date, "DATE" );
992     WRITE( EncodedBy, "ENCODER" );
993     WRITE( Rating, "RATING" );
994     WRITE( Language, "LANGUAGE" );
995     WRITE( TrackID, "MUSICBRAINZ_TRACKID" );
996 #undef WRITE
997 }
998
999
1000 /**
1001  * Set the tags to the file using TagLib
1002  * @param p_this: the demux object
1003  * @return VLC_SUCCESS if the operation success
1004  */
1005
1006 static int WriteMeta( vlc_object_t *p_this )
1007 {
1008     vlc_mutex_locker locker (&taglib_lock);
1009     meta_export_t *p_export = (meta_export_t *)p_this;
1010     input_item_t *p_item = p_export->p_item;
1011     FileRef f;
1012
1013     if( !p_item )
1014     {
1015         msg_Err( p_this, "Can't save meta data of an empty input" );
1016         return VLC_EGENERIC;
1017     }
1018
1019 #if defined(_WIN32)
1020     wchar_t *wpath = ToWide( p_export->psz_file );
1021     if( wpath == NULL )
1022         return VLC_EGENERIC;
1023     f = FileRef( wpath );
1024     free( wpath );
1025 #else
1026     f = FileRef( p_export->psz_file );
1027 #endif
1028
1029     if( f.isNull() || !f.tag() || f.file()->readOnly() )
1030     {
1031         msg_Err( p_this, "File %s can't be opened for tag writing",
1032                  p_export->psz_file );
1033         return VLC_EGENERIC;
1034     }
1035
1036     msg_Dbg( p_this, "Writing metadata for %s", p_export->psz_file );
1037
1038     Tag *p_tag = f.tag();
1039
1040     char *psz_meta;
1041
1042 #define SET( a, b )                                             \
1043     psz_meta = input_item_Get ## a( p_item );                   \
1044     if( psz_meta )                                              \
1045     {                                                           \
1046         String tmp( psz_meta, String::UTF8 );                   \
1047         p_tag->set##b( tmp );                                   \
1048     }                                                           \
1049     free( psz_meta );
1050
1051     // Saving all common fields
1052     // If the title is empty, use the name
1053     SET( TitleFbName, Title );
1054     SET( Artist, Artist );
1055     SET( Album, Album );
1056     SET( Description, Comment );
1057     SET( Genre, Genre );
1058
1059 #undef SET
1060
1061     psz_meta = input_item_GetDate( p_item );
1062     if( !EMPTY_STR(psz_meta) ) p_tag->setYear( atoi( psz_meta ) );
1063     else p_tag->setYear( 0 );
1064     free( psz_meta );
1065
1066     psz_meta = input_item_GetTrackNum( p_item );
1067     if( !EMPTY_STR(psz_meta) ) p_tag->setTrack( atoi( psz_meta ) );
1068     else p_tag->setTrack( 0 );
1069     free( psz_meta );
1070
1071
1072     // Try now to write special tags
1073 #ifdef TAGLIB_HAVE_APEFILE_H
1074     if( APE::File* ape = dynamic_cast<APE::File*>(f.file()) )
1075     {
1076         if( ape->APETag() )
1077             WriteMetaToAPE( ape->APETag(), p_item );
1078     }
1079     else
1080 #endif
1081     if( FLAC::File* flac = dynamic_cast<FLAC::File*>(f.file()) )
1082     {
1083         if( flac->ID3v2Tag() )
1084             WriteMetaToId3v2( flac->ID3v2Tag(), p_item );
1085         else if( flac->xiphComment() )
1086             WriteMetaToXiph( flac->xiphComment(), p_item );
1087     }
1088     else if( MPC::File* mpc = dynamic_cast<MPC::File*>(f.file()) )
1089     {
1090         if( mpc->APETag() )
1091             WriteMetaToAPE( mpc->APETag(), p_item );
1092     }
1093     else if( MPEG::File* mpeg = dynamic_cast<MPEG::File*>(f.file()) )
1094     {
1095         if( mpeg->ID3v2Tag() )
1096             WriteMetaToId3v2( mpeg->ID3v2Tag(), p_item );
1097         else if( mpeg->APETag() )
1098             WriteMetaToAPE( mpeg->APETag(), p_item );
1099     }
1100     else if( dynamic_cast<Ogg::File*>(f.file()) )
1101     {
1102         if( Ogg::FLAC::File* ogg_flac = dynamic_cast<Ogg::FLAC::File*>(f.file()))
1103             WriteMetaToXiph( ogg_flac->tag(), p_item );
1104         else if( Ogg::Speex::File* ogg_speex = dynamic_cast<Ogg::Speex::File*>(f.file()) )
1105             WriteMetaToXiph( ogg_speex->tag(), p_item );
1106         else if( Ogg::Vorbis::File* ogg_vorbis = dynamic_cast<Ogg::Vorbis::File*>(f.file()) )
1107             WriteMetaToXiph( ogg_vorbis->tag(), p_item );
1108 #if defined(TAGLIB_OPUSFILE_H)
1109         else if( Ogg::Opus::File* ogg_opus = dynamic_cast<Ogg::Opus::File*>(f.file()) )
1110             WriteMetaToXiph( ogg_opus->tag(), p_item );
1111 #endif
1112     }
1113     else if( dynamic_cast<RIFF::File*>(f.file()) )
1114     {
1115         if( RIFF::AIFF::File* riff_aiff = dynamic_cast<RIFF::AIFF::File*>(f.file()) )
1116             WriteMetaToId3v2( riff_aiff->tag(), p_item );
1117         else if( RIFF::WAV::File* riff_wav = dynamic_cast<RIFF::WAV::File*>(f.file()) )
1118             WriteMetaToId3v2( riff_wav->tag(), p_item );
1119     }
1120     else if( TrueAudio::File* trueaudio = dynamic_cast<TrueAudio::File*>(f.file()) )
1121     {
1122         if( trueaudio->ID3v2Tag() )
1123             WriteMetaToId3v2( trueaudio->ID3v2Tag(), p_item );
1124     }
1125     else if( WavPack::File* wavpack = dynamic_cast<WavPack::File*>(f.file()) )
1126     {
1127         if( wavpack->APETag() )
1128             WriteMetaToAPE( wavpack->APETag(), p_item );
1129     }
1130
1131     // Save the meta data
1132     f.save();
1133
1134     return VLC_SUCCESS;
1135 }