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