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