]> git.sesse.net Git - vlc/blob - modules/meta_engine/taglib.cpp
taglib: fix windows static build
[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 type;
471         int i_data = vlc_b64_decode_binary( &p_data, art_list[0].toCString(true) );
472         p_attachment = ParseFlacPicture( p_data, i_data, 0, &type );
473     }
474
475     TAB_INIT( p_demux_meta->i_attachments, p_demux_meta->attachments );
476     TAB_APPEND_CAST( (input_attachment_t**),
477                      p_demux_meta->i_attachments, p_demux_meta->attachments,
478                      p_attachment );
479
480     char *psz_url;
481     if( asprintf( &psz_url, "attachment://%s", p_attachment->psz_name ) != -1 ) {
482         vlc_meta_SetArtURL( p_meta, psz_url );
483         free( psz_url );
484     }
485 }
486
487
488 #if defined(TAGLIB_WITH_MP4)
489 /**
490  * Read the meta information from mp4 specific tags
491  * @param tag: the mp4 tag
492  * @param p_demux_meta: the demuxer meta
493  * @param p_meta: the meta
494  */
495 static void ReadMetaFromMP4( MP4::Tag* tag, demux_meta_t *p_demux_meta, vlc_meta_t* p_meta )
496 {
497     if( tag->itemListMap().contains("covr") )
498     {
499         MP4::CoverArtList list = tag->itemListMap()["covr"].toCoverArtList();
500         const char *psz_format = list[0].format() == MP4::CoverArt::PNG ? "image/png" : "image/jpeg";
501
502         msg_Dbg( p_demux_meta, "Found embedded art (%s) is %i bytes",
503                  psz_format, list[0].data().size() );
504
505         TAB_INIT( p_demux_meta->i_attachments, p_demux_meta->attachments );
506         input_attachment_t *p_attachment =
507                 vlc_input_attachment_New( "cover", psz_format, "cover",
508                                           list[0].data().data(), list[0].data().size() );
509         TAB_APPEND_CAST( (input_attachment_t**),
510                          p_demux_meta->i_attachments, p_demux_meta->attachments,
511                          p_attachment );
512         vlc_meta_SetArtURL( p_meta, "attachment://cover" );
513     }
514 }
515 #endif
516
517
518 /**
519  * Get the tags from the file using TagLib
520  * @param p_this: the demux object
521  * @return VLC_SUCCESS if the operation success
522  */
523 static int ReadMeta( vlc_object_t* p_this)
524 {
525     vlc_mutex_locker locker (&taglib_lock);
526     demux_meta_t*   p_demux_meta = (demux_meta_t *)p_this;
527     demux_t*        p_demux = p_demux_meta->p_demux;
528     vlc_meta_t*     p_meta;
529     FileRef f;
530
531     p_demux_meta->p_meta = NULL;
532     if( strcmp( p_demux->psz_access, "file" ) )
533         return VLC_EGENERIC;
534
535     char *psz_path = strdup( p_demux->psz_file );
536     if( !psz_path )
537         return VLC_ENOMEM;
538
539 #if defined(WIN32)
540     wchar_t *wpath = ToWide( psz_path );
541     if( wpath == NULL )
542     {
543         free( psz_path );
544         return VLC_EGENERIC;
545     }
546     f = FileRef( wpath );
547     free( wpath );
548 #else
549     f = FileRef( psz_path );
550 #endif
551     free( psz_path );
552
553     if( f.isNull() )
554         return VLC_EGENERIC;
555     if( !f.tag() || f.tag()->isEmpty() )
556         return VLC_EGENERIC;
557
558     p_demux_meta->p_meta = p_meta = vlc_meta_New();
559     if( !p_meta )
560         return VLC_ENOMEM;
561
562
563     // Read the tags from the file
564     Tag* p_tag = f.tag();
565
566 #define SET( tag, meta )                                                       \
567     if( !p_tag->tag().isNull() && !p_tag->tag().isEmpty() )                    \
568         vlc_meta_Set##meta( p_meta, p_tag->tag().toCString(true) )
569 #define SETINT( tag, meta )                                                    \
570     if( p_tag->tag() )                                                         \
571     {                                                                          \
572         char psz_tmp[10];                                                      \
573         snprintf( psz_tmp, 10, "%d", p_tag->tag() );                           \
574         vlc_meta_Set##meta( p_meta, psz_tmp );                                 \
575     }
576
577     SET( title, Title );
578     SET( artist, Artist );
579     SET( album, Album );
580     SET( comment, Description );
581     SET( genre, Genre );
582     SETINT( year, Date );
583     SETINT( track, TrackNum );
584
585 #undef SETINT
586 #undef SET
587
588
589     // Try now to read special tags
590 #ifdef TAGLIB_HAVE_APEFILE_H
591     if( APE::File* ape = dynamic_cast<APE::File*>(f.file()) )
592     {
593         if( ape->APETag() )
594             ReadMetaFromAPE( ape->APETag(), p_demux_meta, p_meta );
595     }
596     else
597 #endif
598 #ifdef TAGLIB_HAVE_ASFPICTURE_H
599     if( ASF::File* asf = dynamic_cast<ASF::File*>(f.file()) )
600     {
601         if( asf->tag() )
602             ReadMetaFromASF( asf->tag(), p_demux_meta, p_meta );
603     }
604     else
605 #endif
606     if( FLAC::File* flac = dynamic_cast<FLAC::File*>(f.file()) )
607     {
608         if( flac->ID3v2Tag() )
609             ReadMetaFromId3v2( flac->ID3v2Tag(), p_demux_meta, p_meta );
610         else if( flac->xiphComment() )
611             ReadMetaFromXiph( flac->xiphComment(), p_demux_meta, p_meta );
612     }
613 #if defined(TAGLIB_WITH_MP4)
614     else if( MP4::File *mp4 = dynamic_cast<MP4::File*>(f.file()) )
615     {
616         if( mp4->tag() )
617             ReadMetaFromMP4( mp4->tag(), p_demux_meta, p_meta );
618     }
619 #endif
620     else if( MPC::File* mpc = dynamic_cast<MPC::File*>(f.file()) )
621     {
622         if( mpc->APETag() )
623             ReadMetaFromAPE( mpc->APETag(), p_demux_meta, p_meta );
624     }
625     else if( MPEG::File* mpeg = dynamic_cast<MPEG::File*>(f.file()) )
626     {
627         if( mpeg->ID3v2Tag() )
628             ReadMetaFromId3v2( mpeg->ID3v2Tag(), p_demux_meta, p_meta );
629         else if( mpeg->APETag() )
630             ReadMetaFromAPE( mpeg->APETag(), p_demux_meta, p_meta );
631     }
632     else if( dynamic_cast<Ogg::File*>(f.file()) )
633     {
634         if( Ogg::FLAC::File* ogg_flac = dynamic_cast<Ogg::FLAC::File*>(f.file()))
635             ReadMetaFromXiph( ogg_flac->tag(), p_demux_meta, p_meta );
636         else if( Ogg::Speex::File* ogg_speex = dynamic_cast<Ogg::Speex::File*>(f.file()) )
637             ReadMetaFromXiph( ogg_speex->tag(), p_demux_meta, p_meta );
638         else if( Ogg::Vorbis::File* ogg_vorbis = dynamic_cast<Ogg::Vorbis::File*>(f.file()) )
639             ReadMetaFromXiph( ogg_vorbis->tag(), p_demux_meta, p_meta );
640     }
641     else if( dynamic_cast<RIFF::File*>(f.file()) )
642     {
643         if( RIFF::AIFF::File* riff_aiff = dynamic_cast<RIFF::AIFF::File*>(f.file()) )
644             ReadMetaFromId3v2( riff_aiff->tag(), p_demux_meta, p_meta );
645         else if( RIFF::WAV::File* riff_wav = dynamic_cast<RIFF::WAV::File*>(f.file()) )
646             ReadMetaFromId3v2( riff_wav->tag(), p_demux_meta, p_meta );
647     }
648     else if( TrueAudio::File* trueaudio = dynamic_cast<TrueAudio::File*>(f.file()) )
649     {
650         if( trueaudio->ID3v2Tag() )
651             ReadMetaFromId3v2( trueaudio->ID3v2Tag(), p_demux_meta, p_meta );
652     }
653     else if( WavPack::File* wavpack = dynamic_cast<WavPack::File*>(f.file()) )
654     {
655         if( wavpack->APETag() )
656             ReadMetaFromAPE( wavpack->APETag(), p_demux_meta, p_meta );
657     }
658
659     return VLC_SUCCESS;
660 }
661
662
663 /**
664  * Write meta information to APE tags
665  * @param tag: the APE tag
666  * @param p_item: the input item
667  */
668 static void WriteMetaToAPE( APE::Tag* tag, input_item_t* p_item )
669 {
670     char* psz_meta;
671 #define WRITE( metaName, keyName )                      \
672     psz_meta = input_item_Get##metaName( p_item );      \
673     if( psz_meta )                                      \
674     {                                                   \
675         String key( keyName, String::UTF8 );            \
676         String value( psz_meta, String::UTF8 );         \
677         tag->addValue( key, value, true );              \
678     }                                                   \
679     free( psz_meta );
680
681     WRITE( Copyright, "COPYRIGHT" );
682     WRITE( Language, "LANGUAGE" );
683     WRITE( Publisher, "PUBLISHER" );
684
685 #undef WRITE
686 }
687
688
689 /**
690  * Write meta information to id3v2 tags
691  * @param tag: the id3v2 tag
692  * @param p_input: the input item
693  */
694 static void WriteMetaToId3v2( ID3v2::Tag* tag, input_item_t* p_item )
695 {
696     char* psz_meta;
697 #define WRITE( metaName, tagName )                                            \
698     psz_meta = input_item_Get##metaName( p_item );                            \
699     if( psz_meta )                                                            \
700     {                                                                         \
701         ByteVector p_byte( tagName, 4 );                                      \
702         tag->removeFrames( p_byte );                                         \
703         ID3v2::TextIdentificationFrame* p_frame =                             \
704             new ID3v2::TextIdentificationFrame( p_byte, String::UTF8 );       \
705         p_frame->setText( psz_meta );                                         \
706         tag->addFrame( p_frame );                                             \
707     }                                                                         \
708     free( psz_meta );
709
710     WRITE( Copyright, "TCOP" );
711     WRITE( EncodedBy, "TENC" );
712     WRITE( Language,  "TLAN" );
713     WRITE( Publisher, "TPUB" );
714
715 #undef WRITE
716
717     /* Write album art */
718     char *psz_url = input_item_GetArtworkURL( p_item );
719     if( psz_url == NULL )
720         return;
721
722     char *psz_path = make_path( psz_url );
723     free( psz_url );
724     if( psz_path == NULL )
725         return;
726
727     const char *psz_mime = vlc_mime_Ext2Mime( psz_path );
728
729     FILE *p_file = vlc_fopen( psz_path, "rb" );
730     if( p_file == NULL )
731     {
732         free( psz_path );
733         return;
734     }
735
736     struct stat st;
737     if( vlc_stat( psz_path, &st ) == -1 )
738     {
739         free( psz_path );
740         fclose( p_file );
741         return;
742     }
743     off_t file_size = st.st_size;
744
745     free( psz_path );
746
747     /* Limit picture size to 10MiB */
748     if( file_size > 10485760 )
749     {
750       fclose( p_file );
751       return;
752     }
753
754     char *p_buffer = new (std::nothrow) char[file_size];
755     if( p_buffer == NULL )
756     {
757         fclose( p_file );
758         return;
759     }
760
761     if( fread( p_buffer, 1, file_size, p_file ) != (unsigned)file_size )
762     {
763         fclose( p_file );
764         delete[] p_buffer;
765         return;
766     }
767     fclose( p_file );
768
769     ByteVector data( p_buffer, file_size );
770     delete[] p_buffer;
771
772     ID3v2::FrameList frames = tag->frameList( "APIC" );
773     ID3v2::AttachedPictureFrame *frame = NULL;
774     if( frames.isEmpty() )
775     {
776         frame = new TagLib::ID3v2::AttachedPictureFrame;
777         tag->addFrame( frame );
778     }
779     else
780     {
781         frame = static_cast<ID3v2::AttachedPictureFrame *>( frames.back() );
782     }
783
784     frame->setPicture( data );
785     frame->setMimeType( psz_mime );
786 }
787
788
789 /**
790  * Write the meta information to XiphComments
791  * @param tag: the Xiph Comment
792  * @param p_input: the input item
793  */
794 static void WriteMetaToXiph( Ogg::XiphComment* tag, input_item_t* p_item )
795 {
796     char* psz_meta;
797 #define WRITE( metaName, keyName )                      \
798     psz_meta = input_item_Get##metaName( p_item );      \
799     if( psz_meta )                                      \
800     {                                                   \
801         String key( keyName, String::UTF8 );            \
802         String value( psz_meta, String::UTF8 );         \
803         tag->addField( key, value, true );              \
804     }                                                   \
805     free( psz_meta );
806
807     WRITE( Copyright, "COPYRIGHT" );
808
809 #undef WRITE
810 }
811
812
813 /**
814  * Set the tags to the file using TagLib
815  * @param p_this: the demux object
816  * @return VLC_SUCCESS if the operation success
817  */
818
819 static int WriteMeta( vlc_object_t *p_this )
820 {
821     vlc_mutex_locker locker (&taglib_lock);
822     meta_export_t *p_export = (meta_export_t *)p_this;
823     input_item_t *p_item = p_export->p_item;
824     FileRef f;
825
826     if( !p_item )
827     {
828         msg_Err( p_this, "Can't save meta data of an empty input" );
829         return VLC_EGENERIC;
830     }
831
832 #if defined(WIN32)
833     wchar_t *wpath = ToWide( p_export->psz_file );
834     if( wpath == NULL )
835         return VLC_EGENERIC;
836     f = FileRef( wpath );
837     free( wpath );
838 #else
839     f = FileRef( p_export->psz_file );
840 #endif
841
842     if( f.isNull() || !f.tag() || f.file()->readOnly() )
843     {
844         msg_Err( p_this, "File %s can't be opened for tag writing",
845                  p_export->psz_file );
846         return VLC_EGENERIC;
847     }
848
849     msg_Dbg( p_this, "Writing metadata for %s", p_export->psz_file );
850
851     Tag *p_tag = f.tag();
852
853     char *psz_meta;
854
855 #define SET( a, b )                                             \
856     psz_meta = input_item_Get ## a( p_item );                   \
857     if( psz_meta )                                              \
858     {                                                           \
859         String tmp( psz_meta, String::UTF8 );                   \
860         p_tag->set##b( tmp );                                   \
861     }                                                           \
862     free( psz_meta );
863
864     // Saving all common fields
865     // If the title is empty, use the name
866     SET( TitleFbName, Title );
867     SET( Artist, Artist );
868     SET( Album, Album );
869     SET( Description, Comment );
870     SET( Genre, Genre );
871
872 #undef SET
873
874     psz_meta = input_item_GetDate( p_item );
875     if( !EMPTY_STR(psz_meta) ) p_tag->setYear( atoi( psz_meta ) );
876     free( psz_meta );
877
878     psz_meta = input_item_GetTrackNum( p_item );
879     if( !EMPTY_STR(psz_meta) ) p_tag->setTrack( atoi( psz_meta ) );
880     free( psz_meta );
881
882
883     // Try now to write special tags
884 #ifdef TAGLIB_HAVE_APEFILE_H
885     if( APE::File* ape = dynamic_cast<APE::File*>(f.file()) )
886     {
887         if( ape->APETag() )
888             WriteMetaToAPE( ape->APETag(), p_item );
889     }
890     else
891 #endif
892     if( FLAC::File* flac = dynamic_cast<FLAC::File*>(f.file()) )
893     {
894         if( flac->ID3v2Tag() )
895             WriteMetaToId3v2( flac->ID3v2Tag(), p_item );
896         else if( flac->xiphComment() )
897             WriteMetaToXiph( flac->xiphComment(), p_item );
898     }
899     else if( MPC::File* mpc = dynamic_cast<MPC::File*>(f.file()) )
900     {
901         if( mpc->APETag() )
902             WriteMetaToAPE( mpc->APETag(), p_item );
903     }
904     else if( MPEG::File* mpeg = dynamic_cast<MPEG::File*>(f.file()) )
905     {
906         if( mpeg->ID3v2Tag() )
907             WriteMetaToId3v2( mpeg->ID3v2Tag(), p_item );
908         else if( mpeg->APETag() )
909             WriteMetaToAPE( mpeg->APETag(), p_item );
910     }
911     else if( dynamic_cast<Ogg::File*>(f.file()) )
912     {
913         if( Ogg::FLAC::File* ogg_flac = dynamic_cast<Ogg::FLAC::File*>(f.file()))
914             WriteMetaToXiph( ogg_flac->tag(), p_item );
915         else if( Ogg::Speex::File* ogg_speex = dynamic_cast<Ogg::Speex::File*>(f.file()) )
916             WriteMetaToXiph( ogg_speex->tag(), p_item );
917         else if( Ogg::Vorbis::File* ogg_vorbis = dynamic_cast<Ogg::Vorbis::File*>(f.file()) )
918             WriteMetaToXiph( ogg_vorbis->tag(), p_item );
919     }
920     else if( dynamic_cast<RIFF::File*>(f.file()) )
921     {
922         if( RIFF::AIFF::File* riff_aiff = dynamic_cast<RIFF::AIFF::File*>(f.file()) )
923             WriteMetaToId3v2( riff_aiff->tag(), p_item );
924         else if( RIFF::WAV::File* riff_wav = dynamic_cast<RIFF::WAV::File*>(f.file()) )
925             WriteMetaToId3v2( riff_wav->tag(), p_item );
926     }
927     else if( TrueAudio::File* trueaudio = dynamic_cast<TrueAudio::File*>(f.file()) )
928     {
929         if( trueaudio->ID3v2Tag() )
930             WriteMetaToId3v2( trueaudio->ID3v2Tag(), p_item );
931     }
932     else if( WavPack::File* wavpack = dynamic_cast<WavPack::File*>(f.file()) )
933     {
934         if( wavpack->APETag() )
935             WriteMetaToAPE( wavpack->APETag(), p_item );
936     }
937
938     // Save the meta data
939     f.save();
940
941     return VLC_SUCCESS;
942 }
943