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