libextractor

GNU libextractor
Log | Files | Refs | Submodules | README | LICENSE

id3_extractor.c (57011B)


      1 /*
      2      This file is part of libextractor.
      3      Copyright (C) 2026 Vidyut Samanta and Christian Grothoff
      4 
      5      libextractor is free software; you can redistribute it and/or modify
      6      it under the terms of the GNU General Public License as published
      7      by the Free Software Foundation; either version 3, or (at your
      8      option) any later version.
      9 
     10      libextractor is distributed in the hope that it will be useful, but
     11      WITHOUT ANY WARRANTY; without even the implied warranty of
     12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     13      General Public License for more details.
     14 
     15      You should have received a copy of the GNU General Public License
     16      along with libextractor; see the file COPYING.  If not, write to the
     17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
     18      Boston, MA 02110-1301, USA.
     19  */
     20 /**
     21  * @file plugins/id3_extractor.c
     22  * @brief plugin to support MPEG audio with ID3v2 and ID3v1 tags
     23  * @author Christian Grothoff
     24  *
     25  * There is an unported `plugins/old/mp3_extractor.c' in this tree that
     26  * covers part of the same ground.  It got the MPEG frame header tables
     27  * right and they are reused here, but its strategy -- walk every frame
     28  * in the file, up to 31 MB, to decide whether the file is an MP3 --
     29  * is the opposite of what a first pass over a volume wants, so the
     30  * rest is written fresh.
     31  *
     32  * What we are after is not the song title.  It is the provenance: who
     33  * encoded the file (TENC), with what (TSSE and the LAME tag), who
     34  * owned it (TOWN), which player stamped it (PRIV) and which catalogue
     35  * it came from (UFID).  The LAME tag in particular is a fingerprint of
     36  * the exact ripping software and its settings.
     37  *
     38  * References: the ID3v2.2/2.3/2.4 specifications from id3.org, and the
     39  * Xing/Info and LAME tag layout as documented at
     40  * gabriel.mp3-tech.org/mp3infotag.html.
     41  */
     42 #include "platform.h"
     43 #include "extractor.h"
     44 #include "forensics.h"
     45 
     46 #include <stdarg.h>
     47 
     48 
     49 /**
     50  * Name we report our meta data under.
     51  */
     52 #define ID3_PLUGIN "id3"
     53 
     54 /**
     55  * MIME type we claim.
     56  */
     57 #define ID3_MIME "audio/mpeg"
     58 
     59 /**
     60  * Most of an ID3v2 tag we are willing to pull into memory.  Parsing
     61  * from a buffer rather than by seeking is what makes the
     62  * unsynchronisation scheme tractable; the price is this read.  Real
     63  * tags are a few kilobytes, or a few tens of kilobytes with cover art;
     64  * beyond this bound we parse the frames that fit and stop.
     65  */
     66 #define ID3_MAX_TAG_READ (256 * 1024)
     67 
     68 /**
     69  * Upper bound on the number of frames we walk.
     70  */
     71 #define ID3_MAX_FRAMES 128
     72 
     73 /**
     74  * Longest decoded string we build.
     75  */
     76 #define ID3_MAX_TEXT 1024
     77 
     78 /**
     79  * Largest embedded picture we hand on.  Anything bigger is skipped
     80  * rather than copied through the IPC channel.
     81  */
     82 #define ID3_MAX_PICTURE (100 * 1024)
     83 
     84 /**
     85  * Bytes we scan for the first MPEG audio frame.
     86  */
     87 #define ID3_SYNC_WINDOW 8192
     88 
     89 /**
     90  * How many TXXX frames we report as unknown user text.
     91  */
     92 #define ID3_MAX_USER_TEXT 8
     93 
     94 
     95 /**
     96  * Bitrates in kbit/s.  The row is picked from the MPEG version and the
     97  * layer, the column is the four bit field in the frame header.
     98  */
     99 static const unsigned int bitrate_table[5][16] = {
    100   /* MPEG 1 Layer I */
    101   { 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 0 },
    102   /* MPEG 1 Layer II */
    103   { 0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 0 },
    104   /* MPEG 1 Layer III */
    105   { 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0 },
    106   /* MPEG 2 / 2.5 Layer I */
    107   { 0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0 },
    108   /* MPEG 2 / 2.5 Layer II and III */
    109   { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0 }
    110 };
    111 
    112 
    113 /**
    114  * Sampling rates in Hz, indexed by version (0 = MPEG 1, 1 = MPEG 2,
    115  * 2 = MPEG 2.5) and by the two-bit field in the header.
    116  */
    117 static const unsigned int samplerate_table[3][3] = {
    118   { 44100, 48000, 32000 },
    119   { 22050, 24000, 16000 },
    120   { 11025, 12000, 8000 }
    121 };
    122 
    123 
    124 /**
    125  * Channel modes, in the order the header field numbers them.
    126  */
    127 static const char *const channel_modes[4] = {
    128   "stereo",
    129   "joint stereo",
    130   "dual channel",
    131   "mono"
    132 };
    133 
    134 
    135 /**
    136  * The ID3v1 genre numbers, as fixed by the original specification and
    137  * extended by Winamp.  ID3v2 `TCON' frames also refer to these by
    138  * number, in the "(52)" spelling.
    139  */
    140 static const char *const id3_genres[] = {
    141   "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk",
    142   "Grunge", "Hip-Hop", "Jazz", "Metal", "New Age", "Oldies",
    143   "Other", "Pop", "R&B", "Rap", "Reggae", "Rock",
    144   "Techno", "Industrial", "Alternative", "Ska", "Death Metal", "Pranks",
    145   "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal",
    146   "Jazz+Funk", "Fusion", "Trance", "Classical", "Instrumental", "Acid",
    147   "House", "Game", "Sound Clip", "Gospel", "Noise", "Alternative Rock",
    148   "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop",
    149   "Instrumental Rock", "Ethnic", "Gothic", "Darkwave",
    150   "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream",
    151   "Southern Rock", "Comedy", "Cult", "Gangsta", "Top 40",
    152   "Christian Rap", "Pop/Funk", "Jungle", "Native US", "Cabaret",
    153   "New Wave", "Psychedelic", "Rave", "Showtunes", "Trailer", "Lo-Fi",
    154   "Tribal", "Acid Punk", "Acid Jazz", "Polka", "Retro", "Musical",
    155   "Rock & Roll", "Hard Rock", "Folk", "Folk-Rock", "National Folk",
    156   "Swing", "Fast Fusion", "Bebop", "Latin", "Revival", "Celtic",
    157   "Bluegrass", "Avantgarde", "Gothic Rock", "Progressive Rock",
    158   "Psychedelic Rock", "Symphonic Rock", "Slow Rock", "Big Band",
    159   "Chorus", "Easy Listening", "Acoustic", "Humour", "Speech",
    160   "Chanson", "Opera", "Chamber Music", "Sonata", "Symphony",
    161   "Booty Bass", "Primus", "Porn Groove", "Satire", "Slow Jam", "Club",
    162   "Tango", "Samba", "Folklore", "Ballad", "Power Ballad",
    163   "Rhythmic Soul", "Freestyle", "Duet", "Punk Rock", "Drum Solo",
    164   "A Cappella", "Euro-House", "Dance Hall"
    165 };
    166 
    167 
    168 /**
    169  * An ID3v2 text frame identifier and the meta data type it maps to.
    170  */
    171 struct FrameMap
    172 {
    173   /**
    174    * Four character frame identifier.
    175    */
    176   const char *id;
    177 
    178   /**
    179    * Type to report the frame's text as.
    180    */
    181   enum EXTRACTOR_MetaType type;
    182 };
    183 
    184 
    185 /**
    186  * Text frames we understand.  The first block is the ordinary
    187  * descriptive tagging; the second is what tells us where the file came
    188  * from.
    189  */
    190 static const struct FrameMap text_frames[] = {
    191   { "TIT1", EXTRACTOR_METATYPE_GROUP },
    192   { "TIT2", EXTRACTOR_METATYPE_TITLE },
    193   { "TIT3", EXTRACTOR_METATYPE_SUBTITLE },
    194   { "TALB", EXTRACTOR_METATYPE_ALBUM },
    195   { "TPE1", EXTRACTOR_METATYPE_ARTIST },
    196   { "TPE2", EXTRACTOR_METATYPE_PERFORMER },
    197   { "TPE3", EXTRACTOR_METATYPE_CONDUCTOR },
    198   { "TPE4", EXTRACTOR_METATYPE_INTERPRETATION },
    199   { "TCOM", EXTRACTOR_METATYPE_COMPOSER },
    200   { "TEXT", EXTRACTOR_METATYPE_WRITER },
    201   { "TRCK", EXTRACTOR_METATYPE_TRACK_NUMBER },
    202   { "TPOS", EXTRACTOR_METATYPE_DISC_NUMBER },
    203   { "TYER", EXTRACTOR_METATYPE_PUBLICATION_DATE },
    204   { "TDRL", EXTRACTOR_METATYPE_PUBLICATION_DATE },
    205   { "TDRC", EXTRACTOR_METATYPE_CREATION_DATE },
    206   { "TPUB", EXTRACTOR_METATYPE_PUBLISHER },
    207   { "TCOP", EXTRACTOR_METATYPE_COPYRIGHT },
    208   { "TLAN", EXTRACTOR_METATYPE_LANGUAGE },
    209   { "TBPM", EXTRACTOR_METATYPE_BEATS_PER_MINUTE },
    210   { "TSRC", EXTRACTOR_METATYPE_ISRC },
    211   { "TMOO", EXTRACTOR_METATYPE_MOOD },
    212   { "TOAL", EXTRACTOR_METATYPE_ORIGINAL_TITLE },
    213   { "TOPE", EXTRACTOR_METATYPE_ORIGINAL_PERFORMER },
    214   { "TOLY", EXTRACTOR_METATYPE_ORIGINAL_WRITER },
    215   { "TORY", EXTRACTOR_METATYPE_ORIGINAL_RELEASE_YEAR },
    216   /* provenance */
    217   { "TENC", EXTRACTOR_METATYPE_ENCODED_BY },
    218   { "TSSE", EXTRACTOR_METATYPE_ENCODER_SETTINGS },
    219   { "TOWN", EXTRACTOR_METATYPE_OWNER_USER },
    220   { "TFLT", EXTRACTOR_METATYPE_SOURCE_DEVICE },
    221   { "TMED", EXTRACTOR_METATYPE_SOURCE_DEVICE },
    222   { NULL, EXTRACTOR_METATYPE_RESERVED }
    223 };
    224 
    225 
    226 /**
    227  * A three character ID3v2.2 frame identifier and the 2.3 identifier
    228  * that means the same thing.
    229  */
    230 struct FrameAlias
    231 {
    232   /**
    233    * ID3v2.2 identifier.
    234    */
    235   const char *old_id;
    236 
    237   /**
    238    * Equivalent ID3v2.3 identifier.
    239    */
    240   const char *new_id;
    241 };
    242 
    243 
    244 /**
    245  * ID3v2.2 used three character frame identifiers.  Rather than a
    246  * second dispatcher we translate them to their 2.3 equivalents and run
    247  * the same code.  `PIC' is deliberately absent: its payload names the
    248  * image format in three characters where `APIC' carries a MIME string,
    249  * so it cannot share the handler, and an attached picture is not worth
    250  * a second one.
    251  */
    252 static const struct FrameAlias v22_aliases[] = {
    253   { "TT1", "TIT1" }, { "TT2", "TIT2" }, { "TT3", "TIT3" },
    254   { "TAL", "TALB" }, { "TP1", "TPE1" }, { "TP2", "TPE2" },
    255   { "TP3", "TPE3" }, { "TP4", "TPE4" }, { "TCM", "TCOM" },
    256   { "TXT", "TEXT" }, { "TRK", "TRCK" }, { "TPA", "TPOS" },
    257   { "TYE", "TYER" }, { "TPB", "TPUB" }, { "TCR", "TCOP" },
    258   { "TLA", "TLAN" }, { "TBP", "TBPM" }, { "TRC", "TSRC" },
    259   { "TOT", "TOAL" }, { "TOA", "TOPE" }, { "TOL", "TOLY" },
    260   { "TOR", "TORY" }, { "TEN", "TENC" }, { "TSS", "TSSE" },
    261   { "TFT", "TFLT" }, { "TMT", "TMED" }, { "TCO", "TCON" },
    262   { "COM", "COMM" }, { "ULT", "USLT" }, { "UFI", "UFID" },
    263   { "TXX", "TXXX" }, { "WAF", "WOAF" }, { "WAR", "WOAR" },
    264   { "WCM", "WCOM" }, { "WPY", "WPAY" },
    265   { NULL, NULL }
    266 };
    267 
    268 
    269 /**
    270  * TXXX descriptions that name a store account.  The Apple ID of a
    271  * purchase normally lives in an M4A `----:com.apple.iTunes:...' atom
    272  * rather than in ID3, but transcoders copy it across under these
    273  * descriptions, and other stores stamp their own.
    274  */
    275 static const char *const purchase_descriptions[] = {
    276   "apid",
    277   "apple id",
    278   "purchase account",
    279   "purchased by",
    280   "itunes account",
    281   "itunes_purchase_account",
    282   NULL
    283 };
    284 
    285 
    286 /**
    287  * What we have already reported, so that the ID3v1 tag at the end of
    288  * the file can fill gaps without contradicting the ID3v2 tag in front
    289  * of it.
    290  */
    291 struct Id3Context
    292 {
    293   /**
    294    * Extraction context.
    295    */
    296   struct EXTRACTOR_ExtractContext *ec;
    297 
    298   /**
    299    * Number of TXXX frames reported so far.
    300    */
    301   unsigned int user_text;
    302 
    303   /**
    304    * Indexed by meta data type: 1 once we have emitted one.
    305    */
    306   unsigned char seen[EXTRACTOR_METATYPE_LAST];
    307 };
    308 
    309 
    310 /**
    311  * Emit a NUL-terminated string and remember that we did.
    312  *
    313  * @param ctx our state
    314  * @param type meta data type
    315  * @param s the string
    316  * @return 1 if the caller should stop extracting, 0 to continue
    317  */
    318 static int
    319 id3_emit (struct Id3Context *ctx,
    320           enum EXTRACTOR_MetaType type,
    321           const char *s)
    322 {
    323   /* An empty value is dropped by the emit helper, so it must not
    324      count as having covered this type: the ID3v1 tag may still have
    325      something real to say about it. */
    326   if ( ('\0' != s[0]) &&
    327        (0 < type) &&
    328        (type < EXTRACTOR_METATYPE_LAST) )
    329     ctx->seen[type] = 1;
    330   return EXTRACTOR_forensic_emit_text_ (ctx->ec,
    331                                         ID3_PLUGIN,
    332                                         type,
    333                                         s,
    334                                         strlen (s));
    335 }
    336 
    337 
    338 /**
    339  * Convert an ISO-8859-1 string to UTF-8.  The bytes cannot simply be
    340  * passed through: every code point from 0x80 up needs two bytes in
    341  * UTF-8, and handing the raw bytes to the caller would produce invalid
    342  * UTF-8 for exactly the accented characters that make a tag
    343  * interesting.
    344  *
    345  * @param in the Latin-1 bytes
    346  * @param len number of bytes in @a in
    347  * @param[out] out where to write the NUL-terminated UTF-8
    348  * @param out_size size of @a out in bytes
    349  * @return 1 on success, 0 if the result does not fit
    350  */
    351 static int
    352 latin1_to_utf8 (const unsigned char *in,
    353                 size_t len,
    354                 char *out,
    355                 size_t out_size)
    356 {
    357   size_t o = 0;
    358 
    359   for (size_t i = 0; i < len; i++)
    360   {
    361     if (0 == in[i])
    362       break;
    363     if (o + 2 >= out_size)
    364       return 0;
    365     if (in[i] < 0x80)
    366     {
    367       out[o++] = (char) in[i];
    368     }
    369     else
    370     {
    371       out[o++] = (char) (0xC0 | (in[i] >> 6));
    372       out[o++] = (char) (0x80 | (in[i] & 0x3F));
    373     }
    374   }
    375   out[o] = '\0';
    376   return 1;
    377 }
    378 
    379 
    380 /**
    381  * Convert a UTF-16 string to UTF-8.
    382  *
    383  * @param in the UTF-16 bytes
    384  * @param len number of bytes in @a in
    385  * @param big_endian 1 for UTF-16BE, 0 for UTF-16LE
    386  * @param[out] out where to write the NUL-terminated UTF-8
    387  * @param out_size size of @a out in bytes
    388  * @return 1 on success, 0 if the input is malformed or does not fit
    389  */
    390 static int
    391 utf16_to_utf8 (const unsigned char *in,
    392                size_t len,
    393                int big_endian,
    394                char *out,
    395                size_t out_size)
    396 {
    397   size_t o = 0;
    398   size_t i = 0;
    399 
    400   while (i + 1 < len)
    401   {
    402     uint32_t cp = big_endian
    403                   ? EXTRACTOR_forensic_be16_ (&in[i])
    404                   : EXTRACTOR_forensic_le16_ (&in[i]);
    405 
    406     i += 2;
    407     if (0 == cp)
    408       break;
    409     if ( (0xD800 <= cp) && (cp <= 0xDBFF) )
    410     {
    411       uint32_t lo;
    412 
    413       if (i + 1 >= len)
    414         return 0;
    415       lo = big_endian
    416            ? EXTRACTOR_forensic_be16_ (&in[i])
    417            : EXTRACTOR_forensic_le16_ (&in[i]);
    418       if ( (lo < 0xDC00) || (lo > 0xDFFF) )
    419         return 0;
    420       i += 2;
    421       cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
    422     }
    423     else if ( (0xDC00 <= cp) && (cp <= 0xDFFF) )
    424     {
    425       return 0;
    426     }
    427     if (o + 4 >= out_size)
    428       return 0;
    429     if (cp < 0x80)
    430     {
    431       out[o++] = (char) cp;
    432     }
    433     else if (cp < 0x800)
    434     {
    435       out[o++] = (char) (0xC0 | (cp >> 6));
    436       out[o++] = (char) (0x80 | (cp & 0x3F));
    437     }
    438     else if (cp < 0x10000)
    439     {
    440       out[o++] = (char) (0xE0 | (cp >> 12));
    441       out[o++] = (char) (0x80 | ((cp >> 6) & 0x3F));
    442       out[o++] = (char) (0x80 | (cp & 0x3F));
    443     }
    444     else
    445     {
    446       out[o++] = (char) (0xF0 | (cp >> 18));
    447       out[o++] = (char) (0x80 | ((cp >> 12) & 0x3F));
    448       out[o++] = (char) (0x80 | ((cp >> 6) & 0x3F));
    449       out[o++] = (char) (0x80 | (cp & 0x3F));
    450     }
    451   }
    452   out[o] = '\0';
    453   return 1;
    454 }
    455 
    456 
    457 /**
    458  * Decode a string in the encoding an ID3v2 text frame declares in its
    459  * first byte.
    460  *
    461  * @param enc 0 = ISO-8859-1, 1 = UTF-16 with byte order mark,
    462  *        2 = UTF-16BE, 3 = UTF-8
    463  * @param in the encoded bytes
    464  * @param len number of bytes in @a in
    465  * @param[out] out where to write the NUL-terminated UTF-8
    466  * @param out_size size of @a out in bytes
    467  * @return 1 on success, 0 if the encoding is unknown or the input is
    468  *         malformed
    469  */
    470 static int
    471 decode_text (unsigned int enc,
    472              const unsigned char *in,
    473              size_t len,
    474              char *out,
    475              size_t out_size)
    476 {
    477   switch (enc)
    478   {
    479   case 0:
    480     return latin1_to_utf8 (in,
    481                            len,
    482                            out,
    483                            out_size);
    484   case 1:
    485     if (len < 2)
    486       return 0;
    487     if ( (0xFF == in[0]) && (0xFE == in[1]) )
    488       return utf16_to_utf8 (&in[2],
    489                             len - 2,
    490                             0,
    491                             out,
    492                             out_size);
    493     if ( (0xFE == in[0]) && (0xFF == in[1]) )
    494       return utf16_to_utf8 (&in[2],
    495                             len - 2,
    496                             1,
    497                             out,
    498                             out_size);
    499     /* no byte order mark although the encoding byte promised one;
    500        little endian is what the taggers that get this wrong write */
    501     return utf16_to_utf8 (in,
    502                           len,
    503                           0,
    504                           out,
    505                           out_size);
    506   case 2:
    507     return utf16_to_utf8 (in,
    508                           len,
    509                           1,
    510                           out,
    511                           out_size);
    512   case 3:
    513     {
    514       size_t n = len;
    515 
    516       for (size_t i = 0; i < len; i++)
    517         if (0 == in[i])
    518         {
    519           n = i;
    520           break;
    521         }
    522       if (n >= out_size)
    523         return 0;
    524       if (! EXTRACTOR_forensic_utf8_valid_ ((const char *) in,
    525                                             n))
    526         return 0;
    527       memcpy (out,
    528               in,
    529               n);
    530       out[n] = '\0';
    531       return 1;
    532     }
    533   default:
    534     return 0;
    535   }
    536 }
    537 
    538 
    539 /**
    540  * Find the terminator of the string at the start of @a in.
    541  *
    542  * @param enc text encoding as in #decode_text()
    543  * @param in the bytes
    544  * @param len number of bytes in @a in
    545  * @param[out] next offset of the byte after the terminator
    546  * @return length of the string in bytes, excluding the terminator;
    547  *         @a len (and @a next set to @a len) if there is none
    548  */
    549 static size_t
    550 string_end (unsigned int enc,
    551             const unsigned char *in,
    552             size_t len,
    553             size_t *next)
    554 {
    555   if ( (1 == enc) || (2 == enc) )
    556   {
    557     for (size_t i = 0; i + 1 < len; i += 2)
    558       if ( (0 == in[i]) && (0 == in[i + 1]) )
    559       {
    560         *next = i + 2;
    561         return i;
    562       }
    563     *next = len;
    564     return len;
    565   }
    566   for (size_t i = 0; i < len; i++)
    567     if (0 == in[i])
    568     {
    569       *next = i + 1;
    570       return i;
    571     }
    572   *next = len;
    573   return len;
    574 }
    575 
    576 
    577 /**
    578  * Report a genre, resolving the numeric references ID3 allows.
    579  * `TCON' may hold "(52)", "52" or "Electronic"; only the last is
    580  * useful to a human.
    581  *
    582  * @param ctx our state
    583  * @param text the frame's text
    584  * @return 1 if the caller should stop extracting, 0 to continue
    585  */
    586 static int
    587 emit_genre (struct Id3Context *ctx,
    588             const char *text)
    589 {
    590   const char *p = text;
    591   char *endp;
    592   unsigned long n;
    593 
    594   if ('(' == p[0])
    595     p++;
    596   if ( ('0' <= p[0]) && (p[0] <= '9') )
    597   {
    598     n = strtoul (p,
    599                  &endp,
    600                  10);
    601     if ( ( (')' == *endp) || ('\0' == *endp) ) &&
    602          (n < sizeof (id3_genres) / sizeof (id3_genres[0])) )
    603       return id3_emit (ctx,
    604                        EXTRACTOR_METATYPE_GENRE,
    605                        id3_genres[n]);
    606   }
    607   return id3_emit (ctx,
    608                    EXTRACTOR_METATYPE_GENRE,
    609                    text);
    610 }
    611 
    612 
    613 /**
    614  * Handle one ID3v2 frame.
    615  *
    616  * @param ctx our state
    617  * @param id the four character frame identifier, NUL-terminated
    618  * @param data the frame's payload
    619  * @param len number of bytes in @a data
    620  * @return 1 if the caller should stop extracting, 0 to continue
    621  */
    622 static int
    623 handle_frame (struct Id3Context *ctx,
    624               const char *id,
    625               const unsigned char *data,
    626               size_t len)
    627 {
    628   char text[ID3_MAX_TEXT];
    629 
    630   if (0 == len)
    631     return 0;
    632   if ( ('T' == id[0]) &&
    633        (0 != strcmp (id,
    634                      "TXXX")) )
    635   {
    636     if (! decode_text (data[0],
    637                        &data[1],
    638                        len - 1,
    639                        text,
    640                        sizeof (text)))
    641       return 0;
    642     if (0 == strcmp (id,
    643                      "TCON"))
    644       return emit_genre (ctx,
    645                          text);
    646     for (unsigned int i = 0; NULL != text_frames[i].id; i++)
    647       if (0 == strcmp (id,
    648                        text_frames[i].id))
    649         return id3_emit (ctx,
    650                          text_frames[i].type,
    651                          text);
    652     return 0;   /* a text frame we do not care about */
    653   }
    654   if (0 == strcmp (id,
    655                    "TXXX"))
    656   {
    657     char value[ID3_MAX_TEXT];
    658     size_t dlen;
    659     size_t next;
    660 
    661     dlen = string_end (data[0],
    662                        &data[1],
    663                        len - 1,
    664                        &next);
    665     if (! decode_text (data[0],
    666                        &data[1],
    667                        dlen,
    668                        text,
    669                        sizeof (text)))
    670       return 0;
    671     if (next >= len - 1)
    672       return 0;
    673     if (! decode_text (data[0],
    674                        &data[1 + next],
    675                        len - 1 - next,
    676                        value,
    677                        sizeof (value)))
    678       return 0;
    679     for (unsigned int i = 0; NULL != purchase_descriptions[i]; i++)
    680     {
    681       size_t n = strlen (purchase_descriptions[i]);
    682       size_t k;
    683 
    684       if (strlen (text) != n)
    685         continue;
    686       for (k = 0; k < n; k++)
    687         if (tolower ((unsigned char) text[k]) != purchase_descriptions[i][k])
    688           break;
    689       if (k == n)
    690         return id3_emit (ctx,
    691                          EXTRACTOR_METATYPE_PURCHASE_ACCOUNT,
    692                          value);
    693     }
    694     if (ctx->user_text >= ID3_MAX_USER_TEXT)
    695       return 0;
    696     ctx->user_text++;
    697     return (0 != EXTRACTOR_forensic_emit_ (ctx->ec,
    698                                            ID3_PLUGIN,
    699                                            EXTRACTOR_METATYPE_UNKNOWN,
    700                                            "%s: %s",
    701                                            text,
    702                                            value)) ? 1 : 0;
    703   }
    704   if ( ('W' == id[0]) &&
    705        (0 != strcmp (id,
    706                      "WXXX")) )
    707   {
    708     /* the plain URL frames carry no encoding byte; they are always
    709        ISO-8859-1 */
    710     if (! latin1_to_utf8 (data,
    711                           len,
    712                           text,
    713                           sizeof (text)))
    714       return 0;
    715     return id3_emit (ctx,
    716                      EXTRACTOR_METATYPE_URL,
    717                      text);
    718   }
    719   if (0 == strcmp (id,
    720                    "WXXX"))
    721   {
    722     size_t next;
    723 
    724     (void) string_end (data[0],
    725                        &data[1],
    726                        len - 1,
    727                        &next);
    728     if (next >= len - 1)
    729       return 0;
    730     if (! latin1_to_utf8 (&data[1 + next],
    731                           len - 1 - next,
    732                           text,
    733                           sizeof (text)))
    734       return 0;
    735     return id3_emit (ctx,
    736                      EXTRACTOR_METATYPE_URL,
    737                      text);
    738   }
    739   if ( (0 == strcmp (id,
    740                      "COMM")) ||
    741        (0 == strcmp (id,
    742                      "USLT")) )
    743   {
    744     size_t next;
    745 
    746     /* encoding byte, three character language code, a short content
    747        descriptor and then the text */
    748     if (len < 5)
    749       return 0;
    750     (void) string_end (data[0],
    751                        &data[4],
    752                        len - 4,
    753                        &next);
    754     if (next >= len - 4)
    755       return 0;
    756     if (! decode_text (data[0],
    757                        &data[4 + next],
    758                        len - 4 - next,
    759                        text,
    760                        sizeof (text)))
    761       return 0;
    762     return id3_emit (ctx,
    763                      (0 == strcmp (id, "COMM"))
    764                      ? EXTRACTOR_METATYPE_COMMENT
    765                      : EXTRACTOR_METATYPE_LYRICS,
    766                      text);
    767   }
    768   if (0 == strcmp (id,
    769                    "UFID"))
    770   {
    771     char owner[256];
    772     size_t next;
    773     size_t olen;
    774     int printable = 1;
    775 
    776     olen = string_end (0,
    777                        data,
    778                        len,
    779                        &next);
    780     if ( (0 == olen) ||
    781          (next >= len) )
    782       return 0;
    783     if (! latin1_to_utf8 (data,
    784                           olen,
    785                           owner,
    786                           sizeof (owner)))
    787       return 0;
    788     for (size_t i = next; i < len; i++)
    789       if ( (data[i] < 0x20) || (data[i] > 0x7E) )
    790       {
    791         printable = 0;
    792         break;
    793       }
    794     if (printable)
    795     {
    796       size_t n = len - next;
    797 
    798       if (n > sizeof (text) / 2)
    799         n = sizeof (text) / 2;
    800       memcpy (text,
    801               &data[next],
    802               n);
    803       text[n] = '\0';
    804       ctx->seen[EXTRACTOR_METATYPE_SERIAL] = 1;
    805       return (0 != EXTRACTOR_forensic_emit_ (ctx->ec,
    806                                              ID3_PLUGIN,
    807                                              EXTRACTOR_METATYPE_SERIAL,
    808                                              "%s: %s",
    809                                              owner,
    810                                              text)) ? 1 : 0;
    811     }
    812     {
    813       static const char hex[] = "0123456789abcdef";
    814       size_t n = len - next;
    815       size_t o;
    816 
    817       if (n > 32)
    818         n = 32;
    819       o = strlen (owner);
    820       if (o + 2 + 2 * n + 1 > sizeof (text))
    821         return 0;
    822       memcpy (text,
    823               owner,
    824               o);
    825       text[o++] = ':';
    826       text[o++] = ' ';
    827       for (size_t i = 0; i < n; i++)
    828       {
    829         text[o++] = hex[data[next + i] >> 4];
    830         text[o++] = hex[data[next + i] & 0x0F];
    831       }
    832       text[o] = '\0';
    833     }
    834     return id3_emit (ctx,
    835                      EXTRACTOR_METATYPE_SERIAL,
    836                      text);
    837   }
    838   if (0 == strcmp (id,
    839                    "PRIV"))
    840   {
    841     size_t next;
    842     size_t olen;
    843 
    844     /* the owner identifier names the application that stamped the
    845        file -- iTunes, Windows Media Player, a shop's downloader.  The
    846        payload behind it is opaque binary and stays where it is. */
    847     olen = string_end (0,
    848                        data,
    849                        len,
    850                        &next);
    851     if (0 == olen)
    852       return 0;
    853     if (! latin1_to_utf8 (data,
    854                           olen,
    855                           text,
    856                           sizeof (text)))
    857       return 0;
    858     return id3_emit (ctx,
    859                      EXTRACTOR_METATYPE_APPLICATION_ID,
    860                      text);
    861   }
    862   if (0 == strcmp (id,
    863                    "APIC"))
    864   {
    865     char mime[128];
    866     size_t next;
    867     size_t mlen;
    868     size_t pos;
    869 
    870     mlen = string_end (0,
    871                        &data[1],
    872                        len - 1,
    873                        &next);
    874     if (! latin1_to_utf8 (&data[1],
    875                           mlen,
    876                           mime,
    877                           sizeof (mime)))
    878       return 0;
    879     pos = 1 + next;
    880     if (pos + 1 >= len)
    881       return 0;
    882     pos++;   /* picture type byte */
    883     (void) string_end (data[0],
    884                        &data[pos],
    885                        len - pos,
    886                        &next);
    887     pos += next;
    888     if (pos >= len)
    889       return 0;
    890     if (len - pos > ID3_MAX_PICTURE)
    891       return 0;   /* too big to be worth copying through the pipe */
    892     if ('\0' == mime[0])
    893       strcpy (mime,
    894               "image/jpeg");
    895     ctx->seen[EXTRACTOR_METATYPE_COVER_PICTURE] = 1;
    896     return (0 != ctx->ec->proc (ctx->ec->cls,
    897                                 ID3_PLUGIN,
    898                                 EXTRACTOR_METATYPE_COVER_PICTURE,
    899                                 EXTRACTOR_METAFORMAT_BINARY,
    900                                 mime,
    901                                 (const char *) &data[pos],
    902                                 len - pos)) ? 1 : 0;
    903   }
    904   return 0;
    905 }
    906 
    907 
    908 /**
    909  * Undo the ID3v2 unsynchronisation scheme in place: every 0xFF byte
    910  * that was followed by an inserted 0x00 loses that 0x00.
    911  *
    912  * @param[in,out] buf the tag data
    913  * @param len number of bytes in @a buf
    914  * @return number of bytes after the transformation
    915  */
    916 static size_t
    917 deunsynchronise (unsigned char *buf,
    918                  size_t len)
    919 {
    920   size_t o = 0;
    921 
    922   for (size_t i = 0; i < len; i++)
    923   {
    924     buf[o++] = buf[i];
    925     if ( (0xFF == buf[i]) &&
    926          (i + 1 < len) &&
    927          (0x00 == buf[i + 1]) )
    928       i++;
    929   }
    930   return o;
    931 }
    932 
    933 
    934 /**
    935  * Walk the frames of an ID3v2 tag that has already been read into
    936  * memory.
    937  *
    938  * @param ctx our state
    939  * @param major ID3v2 minor version: 2, 3 or 4
    940  * @param tag_unsync 1 if the tag header set the unsynchronisation flag
    941  * @param buf the tag body, after the ten byte header
    942  * @param len number of bytes in @a buf
    943  * @return 1 if the caller should stop extracting, 0 to continue
    944  */
    945 static int
    946 walk_frames (struct Id3Context *ctx,
    947              unsigned int major,
    948              int tag_unsync,
    949              unsigned char *buf,
    950              size_t len)
    951 {
    952   size_t pos = 0;
    953   unsigned int count = 0;
    954   const size_t hdr = (2 == major) ? 6 : 10;
    955   const size_t idlen = (2 == major) ? 3 : 4;
    956 
    957   while ( (pos + hdr <= len) &&
    958           (count < ID3_MAX_FRAMES) )
    959   {
    960     char id[5];
    961     size_t size;
    962     unsigned char *body;
    963     size_t blen;
    964     unsigned char flags2 = 0;
    965     int frame_unsync = tag_unsync;
    966 
    967     if (0 == buf[pos])
    968       break;   /* padding */
    969     for (size_t i = 0; i < idlen; i++)
    970     {
    971       unsigned char c = buf[pos + i];
    972 
    973       if ( ( (c < 'A') || (c > 'Z') ) &&
    974            ( (c < '0') || (c > '9') ) )
    975         return 0;   /* not a frame identifier; the tag ends here */
    976       id[i] = (char) c;
    977     }
    978     id[idlen] = '\0';
    979     if (2 == major)
    980     {
    981       size = ((size_t) buf[pos + 3] << 16)
    982              | ((size_t) buf[pos + 4] << 8)
    983              | (size_t) buf[pos + 5];
    984     }
    985     else if (4 == major)
    986     {
    987       /* In 2.4 the frame size is synchsafe -- seven bits per byte --
    988          while in 2.3 it is a plain big-endian integer.  Getting this
    989          backwards is the classic ID3 bug: it only shows up for frames
    990          of 128 bytes or more, so a tagger tested on short titles looks
    991          fine and falls apart on the first embedded picture.  Taggers
    992          that write 2.4 headers with 2.3 sizes exist, and they give
    993          themselves away by setting the high bit of a size byte, which
    994          a synchsafe integer never does. */
    995       if ( (0 != (buf[pos + 4] & 0x80)) ||
    996            (0 != (buf[pos + 5] & 0x80)) ||
    997            (0 != (buf[pos + 6] & 0x80)) ||
    998            (0 != (buf[pos + 7] & 0x80)) )
    999         size = (size_t) EXTRACTOR_forensic_be32_ (&buf[pos + 4]);
   1000       else
   1001         size = (((size_t) buf[pos + 4]) << 21)
   1002                | (((size_t) buf[pos + 5]) << 14)
   1003                | (((size_t) buf[pos + 6]) << 7)
   1004                | ((size_t) buf[pos + 7]);
   1005     }
   1006     else
   1007     {
   1008       size = (size_t) EXTRACTOR_forensic_be32_ (&buf[pos + 4]);
   1009     }
   1010     if (0 == size)
   1011       break;   /* a zero length frame cannot be followed by anything */
   1012     if (size > len - pos - hdr)
   1013       break;   /* runs past the end of the tag */
   1014     if (2 != major)
   1015       flags2 = buf[pos + 9];
   1016     body = &buf[pos + hdr];
   1017     blen = size;
   1018     pos += hdr + size;
   1019     count++;
   1020     if (3 == major)
   1021     {
   1022       if (0 != (flags2 & 0xC0))
   1023         continue;   /* compressed or encrypted */
   1024       if (0 != (flags2 & 0x20))
   1025       {
   1026         if (0 == blen)
   1027           continue;
   1028         body++;
   1029         blen--;   /* group identifier */
   1030       }
   1031     }
   1032     else if (4 == major)
   1033     {
   1034       if (0 != (flags2 & 0x0C))
   1035         continue;   /* compressed or encrypted */
   1036       if (0 != (flags2 & 0x40))
   1037       {
   1038         if (0 == blen)
   1039           continue;
   1040         body++;
   1041         blen--;   /* group identifier */
   1042       }
   1043       if (0 != (flags2 & 0x02))
   1044         frame_unsync = 1;
   1045       if (0 != (flags2 & 0x01))
   1046       {
   1047         if (blen < 4)
   1048           continue;
   1049         body += 4;
   1050         blen -= 4;   /* data length indicator */
   1051       }
   1052     }
   1053     if (frame_unsync)
   1054       blen = deunsynchronise (body,
   1055                               blen);
   1056     if (2 == major)
   1057     {
   1058       unsigned int a;
   1059 
   1060       for (a = 0; NULL != v22_aliases[a].old_id; a++)
   1061         if (0 == strcmp (id,
   1062                          v22_aliases[a].old_id))
   1063           break;
   1064       if (NULL == v22_aliases[a].old_id)
   1065         continue;   /* a 2.2 frame we do not handle */
   1066       if (handle_frame (ctx,
   1067                         v22_aliases[a].new_id,
   1068                         body,
   1069                         blen))
   1070         return 1;
   1071       continue;
   1072     }
   1073     if (handle_frame (ctx,
   1074                       id,
   1075                       body,
   1076                       blen))
   1077       return 1;
   1078   }
   1079   return 0;
   1080 }
   1081 
   1082 
   1083 /**
   1084  * A decoded MPEG audio frame header.
   1085  */
   1086 struct MpegHeader
   1087 {
   1088   /**
   1089    * 1, 2 or 25 for MPEG 1, MPEG 2 and MPEG 2.5.
   1090    */
   1091   unsigned int version;
   1092 
   1093   /**
   1094    * 1, 2 or 3.
   1095    */
   1096   unsigned int layer;
   1097 
   1098   /**
   1099    * Bitrate in bits per second.
   1100    */
   1101   unsigned int bitrate;
   1102 
   1103   /**
   1104    * Sampling rate in Hz.
   1105    */
   1106   unsigned int sample_rate;
   1107 
   1108   /**
   1109    * Channel mode, 0 to 3, indexing #channel_modes.
   1110    */
   1111   unsigned int mode;
   1112 
   1113   /**
   1114    * Number of samples this frame encodes.
   1115    */
   1116   unsigned int samples;
   1117 
   1118   /**
   1119    * Length of the frame in bytes, including the header.
   1120    */
   1121   unsigned int frame_len;
   1122 
   1123   /**
   1124    * 1 if a CRC follows the header.
   1125    */
   1126   int protected_frame;
   1127 };
   1128 
   1129 
   1130 /**
   1131  * Decode and validate a four byte MPEG audio frame header.
   1132  *
   1133  * Every reserved combination is rejected: without that, one byte in
   1134  * every 2048 of arbitrary binary starts something that looks like a
   1135  * frame.
   1136  *
   1137  * @param h the four bytes
   1138  * @param[out] f the decoded header
   1139  * @return 1 if @a h is a valid header, 0 if not
   1140  */
   1141 static int
   1142 parse_mpeg_header (const unsigned char *h,
   1143                    struct MpegHeader *f)
   1144 {
   1145   unsigned int vbits;
   1146   unsigned int lbits;
   1147   unsigned int brindex;
   1148   unsigned int srindex;
   1149   unsigned int column;
   1150   unsigned int vrow;
   1151   unsigned int padding;
   1152 
   1153   if (0xFF != h[0])
   1154     return 0;
   1155   if (0xE0 != (h[1] & 0xE0))
   1156     return 0;
   1157   vbits = (h[1] >> 3) & 0x03;
   1158   lbits = (h[1] >> 1) & 0x03;
   1159   if (1 == vbits)
   1160     return 0;   /* reserved version */
   1161   if (0 == lbits)
   1162     return 0;   /* reserved layer */
   1163   brindex = (h[2] >> 4) & 0x0F;
   1164   srindex = (h[2] >> 2) & 0x03;
   1165   if ( (0 == brindex) ||
   1166        (15 == brindex) )
   1167     return 0;   /* "free" and "bad" are both unusable to us */
   1168   if (3 == srindex)
   1169     return 0;   /* reserved */
   1170   if (3 == (h[3] & 0x03))
   1171     return 0;   /* reserved emphasis */
   1172   f->layer = 4 - lbits;
   1173   switch (vbits)
   1174   {
   1175   case 0:
   1176     f->version = 25;
   1177     vrow = 2;
   1178     break;
   1179   case 2:
   1180     f->version = 2;
   1181     vrow = 1;
   1182     break;
   1183   default:
   1184     f->version = 1;
   1185     vrow = 0;
   1186     break;
   1187   }
   1188   if (1 == f->version)
   1189     column = f->layer - 1;
   1190   else
   1191     column = (1 == f->layer) ? 3 : 4;
   1192   f->bitrate = 1000 * bitrate_table[column][brindex];
   1193   f->sample_rate = samplerate_table[vrow][srindex];
   1194   f->mode = (h[3] >> 6) & 0x03;
   1195   f->protected_frame = (0 == (h[1] & 0x01)) ? 1 : 0;
   1196   padding = (h[2] >> 1) & 0x01;
   1197   if (1 == f->layer)
   1198     f->samples = 384;
   1199   else if (2 == f->layer)
   1200     f->samples = 1152;
   1201   else
   1202     f->samples = (1 == f->version) ? 1152 : 576;
   1203   if (1 == f->layer)
   1204     f->frame_len = (12 * f->bitrate / f->sample_rate + padding) * 4;
   1205   else
   1206     f->frame_len = (f->samples / 8) * f->bitrate / f->sample_rate + padding;
   1207   if (f->frame_len < 24)
   1208     return 0;
   1209   return 1;
   1210 }
   1211 
   1212 
   1213 /**
   1214  * Report the ReplayGain field at @a p, if it holds one.
   1215  *
   1216  * @param ctx our state
   1217  * @param type meta data type to report it as
   1218  * @param p the two bytes
   1219  * @param want_name the name code this field must carry (1 = track,
   1220  *        2 = album)
   1221  * @return 1 if the caller should stop extracting, 0 to continue
   1222  */
   1223 static int
   1224 emit_replay_gain (struct Id3Context *ctx,
   1225                   enum EXTRACTOR_MetaType type,
   1226                   const unsigned char *p,
   1227                   unsigned int want_name)
   1228 {
   1229   uint16_t v = EXTRACTOR_forensic_be16_ (p);
   1230   unsigned int name = (v >> 13) & 0x07;
   1231   unsigned int value = v & 0x01FF;
   1232 
   1233   if (name != want_name)
   1234     return 0;
   1235   if (0 == value)
   1236     return 0;
   1237   ctx->seen[type] = 1;
   1238   return (0 != EXTRACTOR_forensic_emit_ (ctx->ec,
   1239                                          ID3_PLUGIN,
   1240                                          type,
   1241                                          "%s%u.%u dB",
   1242                                          (0 != ((v >> 9) & 0x01)) ? "-" : "+",
   1243                                          value / 10,
   1244                                          value % 10)) ? 1 : 0;
   1245 }
   1246 
   1247 
   1248 /**
   1249  * Append a comma separated fragment to the encoder settings summary,
   1250  * never running past the end of @a buf.
   1251  *
   1252  * @param buf where to build the summary
   1253  * @param size size of @a buf in bytes
   1254  * @param[in,out] off current length of the summary
   1255  * @param fmt printf format string for the fragment
   1256  */
   1257 static void
   1258 append_setting (char *buf,
   1259                 size_t size,
   1260                 size_t *off,
   1261                 const char *fmt,
   1262                 ...)
   1263 __attribute__ ((format (printf, 4, 5)));
   1264 
   1265 static void
   1266 append_setting (char *buf,
   1267                 size_t size,
   1268                 size_t *off,
   1269                 const char *fmt,
   1270                 ...)
   1271 {
   1272   va_list ap;
   1273   int n;
   1274 
   1275   if (*off + 3 >= size)
   1276     return;
   1277   if (0 != *off)
   1278   {
   1279     buf[(*off)++] = ',';
   1280     buf[(*off)++] = ' ';
   1281     buf[*off] = '\0';
   1282   }
   1283   va_start (ap, fmt);
   1284   n = vsnprintf (&buf[*off],
   1285                  size - *off,
   1286                  fmt,
   1287                  ap);
   1288   va_end (ap);
   1289   if (0 >= n)
   1290     return;
   1291   if (((size_t) n) >= size - *off)
   1292     *off = size - 1;
   1293   else
   1294     *off += (size_t) n;
   1295 }
   1296 
   1297 
   1298 /**
   1299  * Read the Xing/Info header and the LAME tag that may sit inside the
   1300  * first audio frame.
   1301  *
   1302  * The LAME tag is the most identifying thing in an MP3: it names the
   1303  * encoder build and the settings it ran with, which together pin down
   1304  * the ripping software far more precisely than any text frame.
   1305  *
   1306  * @param ctx our state
   1307  * @param f the decoded frame header
   1308  * @param frame the frame's bytes
   1309  * @param len number of bytes of the frame we have
   1310  * @return 1 if the caller should stop extracting, 0 to continue
   1311  */
   1312 static int
   1313 extract_xing (struct Id3Context *ctx,
   1314               const struct MpegHeader *f,
   1315               const unsigned char *frame,
   1316               size_t len)
   1317 {
   1318   size_t xo;
   1319   size_t p;
   1320   uint32_t flags;
   1321   uint32_t frames = 0;
   1322   uint32_t nbytes = 0;
   1323   uint32_t quality = 0;
   1324   int have_quality = 0;
   1325   int vbr;
   1326   char settings[ID3_MAX_TEXT];
   1327   size_t so = 0;
   1328 
   1329   /* The tag sits just past the side information, whose size depends on
   1330      the version and on whether the frame is mono.  A CRC, if present,
   1331      takes two more bytes right after the header. */
   1332   if (1 == f->version)
   1333     xo = (3 == f->mode) ? 21 : 36;
   1334   else
   1335     xo = (3 == f->mode) ? 13 : 21;
   1336   if (f->protected_frame)
   1337     xo += 2;
   1338   if (xo + 8 > len)
   1339     return 0;
   1340   if (0 == memcmp (&frame[xo],
   1341                    "Xing",
   1342                    4))
   1343   {
   1344     vbr = 1;
   1345   }
   1346   else if (0 == memcmp (&frame[xo],
   1347                         "Info",
   1348                         4))
   1349   {
   1350     vbr = 0;
   1351   }
   1352   else
   1353   {
   1354     return 0;
   1355   }
   1356   flags = EXTRACTOR_forensic_be32_ (&frame[xo + 4]);
   1357   p = xo + 8;
   1358   if (0 != (flags & 0x01))
   1359   {
   1360     if (p + 4 > len)
   1361       return 0;
   1362     frames = EXTRACTOR_forensic_be32_ (&frame[p]);
   1363     p += 4;
   1364   }
   1365   if (0 != (flags & 0x02))
   1366   {
   1367     if (p + 4 > len)
   1368       return 0;
   1369     nbytes = EXTRACTOR_forensic_be32_ (&frame[p]);
   1370     p += 4;
   1371   }
   1372   if (0 != (flags & 0x04))
   1373   {
   1374     if (p + 100 > len)
   1375       return 0;
   1376     p += 100;   /* seek table */
   1377   }
   1378   if (0 != (flags & 0x08))
   1379   {
   1380     if (p + 4 > len)
   1381       return 0;
   1382     quality = EXTRACTOR_forensic_be32_ (&frame[p]);
   1383     have_quality = 1;
   1384     p += 4;
   1385   }
   1386   if ( (0 != frames) &&
   1387        (frames < 100000000u) &&
   1388        (0 != f->sample_rate) )
   1389   {
   1390     uint64_t samples = (uint64_t) frames * f->samples;
   1391     unsigned int secs = (unsigned int) (samples / f->sample_rate);
   1392 
   1393     if (EXTRACTOR_forensic_emit_ (ctx->ec,
   1394                                   ID3_PLUGIN,
   1395                                   EXTRACTOR_METATYPE_DURATION,
   1396                                   "%u:%02u:%02u",
   1397                                   secs / 3600,
   1398                                   (secs / 60) % 60,
   1399                                   secs % 60))
   1400       return 1;
   1401     ctx->seen[EXTRACTOR_METATYPE_DURATION] = 1;
   1402     if (0 != nbytes)
   1403     {
   1404       uint64_t avg = ((uint64_t) nbytes) * 8 * f->sample_rate / samples;
   1405 
   1406       if (EXTRACTOR_forensic_emit_ (ctx->ec,
   1407                                     ID3_PLUGIN,
   1408                                     EXTRACTOR_METATYPE_BITRATE,
   1409                                     "%llu",
   1410                                     (unsigned long long) avg))
   1411         return 1;
   1412       ctx->seen[EXTRACTOR_METATYPE_BITRATE] = 1;
   1413     }
   1414   }
   1415   /* The LAME extension follows the Xing fields.  36 bytes: a nine
   1416      character encoder string, then the settings it ran with. */
   1417   if (p + 36 > len)
   1418   {
   1419     /* no room for the extension; still report what the magic said */
   1420     return id3_emit (ctx,
   1421                      EXTRACTOR_METATYPE_BITRATE_MODE,
   1422                      vbr ? "VBR" : "CBR");
   1423   }
   1424   {
   1425     const unsigned char *l = &frame[p];
   1426     char version[10];
   1427     unsigned int method = l[9] & 0x0F;
   1428     unsigned int lowpass = l[10];
   1429     unsigned int abr = l[20];
   1430     unsigned int delay = ((unsigned int) l[21] << 4) | (l[22] >> 4);
   1431     unsigned int padding = ((unsigned int) (l[22] & 0x0F) << 8) | l[23];
   1432     unsigned int preset = EXTRACTOR_forensic_be16_ (&l[26]) & 0x07FF;
   1433     const char *mode;
   1434     int printable = 0;
   1435 
   1436     /* We do not check the tag's own CRC-16.  The field exists, but the
   1437        encoders that write this tag do not agree on what it covers --
   1438        LAME and ffmpeg produce different values for the same layout --
   1439        so a mismatch would say more about the writer than about the
   1440        data, and rejecting on it would lose real metadata.  The nine
   1441        character encoder string is self-validating enough: it has to be
   1442        printable ASCII with something in it. */
   1443     for (unsigned int i = 0; i < 9; i++)
   1444     {
   1445       if ( (l[i] < 0x20) || (l[i] > 0x7E) )
   1446       {
   1447         printable = 0;
   1448         break;
   1449       }
   1450       if (' ' != l[i])
   1451         printable++;
   1452     }
   1453     if (printable < 4)
   1454       return id3_emit (ctx,
   1455                        EXTRACTOR_METATYPE_BITRATE_MODE,
   1456                        vbr ? "VBR" : "CBR");
   1457     memcpy (version,
   1458             l,
   1459             9);
   1460     version[9] = '\0';
   1461     switch (method)
   1462     {
   1463     case 1:
   1464       mode = "CBR";
   1465       break;
   1466     case 2:
   1467       mode = "ABR";
   1468       break;
   1469     case 8:
   1470       mode = "CBR (2 pass)";
   1471       break;
   1472     case 9:
   1473       mode = "ABR (2 pass)";
   1474       break;
   1475     case 0:
   1476       mode = vbr ? "VBR" : "CBR";
   1477       break;
   1478     default:
   1479       mode = "VBR";
   1480       break;
   1481     }
   1482     if (id3_emit (ctx,
   1483                   EXTRACTOR_METATYPE_BITRATE_MODE,
   1484                   mode))
   1485       return 1;
   1486     if (id3_emit (ctx,
   1487                   EXTRACTOR_METATYPE_ENCODER,
   1488                   version))
   1489       return 1;
   1490     for (unsigned int i = 0; i < 9; i++)
   1491       if ( ('0' <= version[i]) && (version[i] <= '9') )
   1492       {
   1493         if (id3_emit (ctx,
   1494                       EXTRACTOR_METATYPE_ENCODER_VERSION,
   1495                       &version[i]))
   1496           return 1;
   1497         break;
   1498       }
   1499     settings[0] = '\0';
   1500     if (0 != lowpass)
   1501       append_setting (settings,
   1502                       sizeof (settings),
   1503                       &so,
   1504                       "lowpass %u Hz",
   1505                       100 * lowpass);
   1506     if ( (have_quality) &&
   1507          (quality <= 100) )
   1508       append_setting (settings,
   1509                       sizeof (settings),
   1510                       &so,
   1511                       "quality %u",
   1512                       (unsigned int) quality);
   1513     append_setting (settings,
   1514                     sizeof (settings),
   1515                     &so,
   1516                     "VBR method %u",
   1517                     method);
   1518     if (0 != abr)
   1519       append_setting (settings,
   1520                       sizeof (settings),
   1521                       &so,
   1522                       "min bitrate %u kbit/s",
   1523                       abr);
   1524     if (0 != preset)
   1525       append_setting (settings,
   1526                       sizeof (settings),
   1527                       &so,
   1528                       "preset %u",
   1529                       preset);
   1530     append_setting (settings,
   1531                     sizeof (settings),
   1532                     &so,
   1533                     "delay %u, padding %u",
   1534                     delay,
   1535                     padding);
   1536     if (id3_emit (ctx,
   1537                   EXTRACTOR_METATYPE_ENCODER_SETTINGS,
   1538                   settings))
   1539       return 1;
   1540     if (emit_replay_gain (ctx,
   1541                           EXTRACTOR_METATYPE_TRACK_GAIN,
   1542                           &l[15],
   1543                           1))
   1544       return 1;
   1545     if (emit_replay_gain (ctx,
   1546                           EXTRACTOR_METATYPE_ALBUM_GAIN,
   1547                           &l[17],
   1548                           2))
   1549       return 1;
   1550   }
   1551   return 0;
   1552 }
   1553 
   1554 
   1555 /**
   1556  * Find and describe the first MPEG audio frame at or after @a start.
   1557  *
   1558  * @param ctx our state
   1559  * @param start where the audio should begin
   1560  * @param size size of the file
   1561  * @return 1 if the caller should stop extracting, 0 to continue
   1562  */
   1563 static int
   1564 extract_audio (struct Id3Context *ctx,
   1565                uint64_t start,
   1566                uint64_t size)
   1567 {
   1568   unsigned char window[ID3_SYNC_WINDOW];
   1569   struct MpegHeader f;
   1570   size_t wlen;
   1571   size_t at = 0;
   1572   int have = 0;
   1573 
   1574   if (start >= size)
   1575     return 0;
   1576   wlen = ((size - start) < sizeof (window))
   1577          ? (size_t) (size - start)
   1578          : sizeof (window);
   1579   if (wlen < 4)
   1580     return 0;
   1581   if (! EXTRACTOR_forensic_read_ (ctx->ec,
   1582                                   (int64_t) start,
   1583                                   window,
   1584                                   wlen))
   1585     return 0;
   1586   for (size_t i = 0; i + 4 <= wlen; i++)
   1587   {
   1588     struct MpegHeader next;
   1589 
   1590     if (0xFF != window[i])
   1591       continue;
   1592     if (! parse_mpeg_header (&window[i],
   1593                              &f))
   1594       continue;
   1595     /* Confirm with the frame after this one where we can: a single
   1596        header pattern turns up in arbitrary data often enough that it
   1597        is not evidence on its own. */
   1598     if (i + f.frame_len + 4 <= wlen)
   1599     {
   1600       if (! parse_mpeg_header (&window[i + f.frame_len],
   1601                                &next))
   1602         continue;
   1603       if ( (next.version != f.version) ||
   1604            (next.layer != f.layer) ||
   1605            (next.sample_rate != f.sample_rate) )
   1606         continue;
   1607     }
   1608     at = i;
   1609     have = 1;
   1610     break;
   1611   }
   1612   if (! have)
   1613     return 0;
   1614   if (EXTRACTOR_forensic_emit_ (ctx->ec,
   1615                                 ID3_PLUGIN,
   1616                                 EXTRACTOR_METATYPE_CODEC,
   1617                                 "MPEG %s Layer %s",
   1618                                 (1 == f.version) ? "1"
   1619                                 : ((2 == f.version) ? "2" : "2.5"),
   1620                                 (1 == f.layer) ? "I"
   1621                                 : ((2 == f.layer) ? "II" : "III")))
   1622     return 1;
   1623   if (EXTRACTOR_forensic_emit_ (ctx->ec,
   1624                                 ID3_PLUGIN,
   1625                                 EXTRACTOR_METATYPE_FORMAT,
   1626                                 "MPEG %s Layer %s, %s",
   1627                                 (1 == f.version) ? "1"
   1628                                 : ((2 == f.version) ? "2" : "2.5"),
   1629                                 (1 == f.layer) ? "I"
   1630                                 : ((2 == f.layer) ? "II" : "III"),
   1631                                 channel_modes[f.mode]))
   1632     return 1;
   1633   if (EXTRACTOR_forensic_emit_ (ctx->ec,
   1634                                 ID3_PLUGIN,
   1635                                 EXTRACTOR_METATYPE_SAMPLE_RATE,
   1636                                 "%u",
   1637                                 f.sample_rate))
   1638     return 1;
   1639   if (EXTRACTOR_forensic_emit_ (ctx->ec,
   1640                                 ID3_PLUGIN,
   1641                                 EXTRACTOR_METATYPE_CHANNELS,
   1642                                 "%u",
   1643                                 (3 == f.mode) ? 1 : 2))
   1644     return 1;
   1645   if (EXTRACTOR_forensic_emit_ (ctx->ec,
   1646                                 ID3_PLUGIN,
   1647                                 EXTRACTOR_METATYPE_NOMINAL_BITRATE,
   1648                                 "%u",
   1649                                 f.bitrate))
   1650     return 1;
   1651   if (extract_xing (ctx,
   1652                     &f,
   1653                     &window[at],
   1654                     wlen - at))
   1655     return 1;
   1656   if (! ctx->seen[EXTRACTOR_METATYPE_BITRATE])
   1657   {
   1658     if (EXTRACTOR_forensic_emit_ (ctx->ec,
   1659                                   ID3_PLUGIN,
   1660                                   EXTRACTOR_METATYPE_BITRATE,
   1661                                   "%u",
   1662                                   f.bitrate))
   1663       return 1;
   1664     ctx->seen[EXTRACTOR_METATYPE_BITRATE] = 1;
   1665   }
   1666   return 0;
   1667 }
   1668 
   1669 
   1670 /**
   1671  * Report a field of the ID3v1 tag, unless the ID3v2 tag already
   1672  * supplied one of the same kind.
   1673  *
   1674  * @param ctx our state
   1675  * @param type meta data type
   1676  * @param data the fixed width field
   1677  * @param len width of the field
   1678  * @return 1 if the caller should stop extracting, 0 to continue
   1679  */
   1680 static int
   1681 emit_v1_field (struct Id3Context *ctx,
   1682                enum EXTRACTOR_MetaType type,
   1683                const unsigned char *data,
   1684                size_t len)
   1685 {
   1686   char text[128];
   1687 
   1688   if (ctx->seen[type])
   1689     return 0;
   1690   len = EXTRACTOR_forensic_trim_ ((const char *) data,
   1691                                   len);
   1692   if (0 == len)
   1693     return 0;
   1694   if (! latin1_to_utf8 (data,
   1695                         len,
   1696                         text,
   1697                         sizeof (text)))
   1698     return 0;
   1699   return id3_emit (ctx,
   1700                    type,
   1701                    text);
   1702 }
   1703 
   1704 
   1705 /**
   1706  * Read the ID3v1 tag in the last 128 bytes of the file.  It only ever
   1707  * fills gaps: where an ID3v2 tag said anything, it wins, because the
   1708  * v1 fields are truncated to 30 bytes and have no declared character
   1709  * set.
   1710  *
   1711  * @param ctx our state
   1712  * @param tag the 128 bytes
   1713  * @return 1 if the caller should stop extracting, 0 to continue
   1714  */
   1715 static int
   1716 extract_v1 (struct Id3Context *ctx,
   1717             const unsigned char *tag)
   1718 {
   1719   if (emit_v1_field (ctx,
   1720                      EXTRACTOR_METATYPE_TITLE,
   1721                      &tag[3],
   1722                      30))
   1723     return 1;
   1724   if (emit_v1_field (ctx,
   1725                      EXTRACTOR_METATYPE_ARTIST,
   1726                      &tag[33],
   1727                      30))
   1728     return 1;
   1729   if (emit_v1_field (ctx,
   1730                      EXTRACTOR_METATYPE_ALBUM,
   1731                      &tag[63],
   1732                      30))
   1733     return 1;
   1734   if (emit_v1_field (ctx,
   1735                      EXTRACTOR_METATYPE_PUBLICATION_DATE,
   1736                      &tag[93],
   1737                      4))
   1738     return 1;
   1739   /* ID3v1.1 stole the last two bytes of the comment for a track
   1740      number: a NUL in the second to last byte marks it */
   1741   if ( (0 == tag[125]) &&
   1742        (0 != tag[126]) )
   1743   {
   1744     if (emit_v1_field (ctx,
   1745                        EXTRACTOR_METATYPE_COMMENT,
   1746                        &tag[97],
   1747                        28))
   1748       return 1;
   1749     if (! ctx->seen[EXTRACTOR_METATYPE_TRACK_NUMBER])
   1750     {
   1751       if (EXTRACTOR_forensic_emit_ (ctx->ec,
   1752                                     ID3_PLUGIN,
   1753                                     EXTRACTOR_METATYPE_TRACK_NUMBER,
   1754                                     "%u",
   1755                                     (unsigned int) tag[126]))
   1756         return 1;
   1757       ctx->seen[EXTRACTOR_METATYPE_TRACK_NUMBER] = 1;
   1758     }
   1759   }
   1760   else if (emit_v1_field (ctx,
   1761                           EXTRACTOR_METATYPE_COMMENT,
   1762                           &tag[97],
   1763                           30))
   1764   {
   1765     return 1;
   1766   }
   1767   if ( (! ctx->seen[EXTRACTOR_METATYPE_GENRE]) &&
   1768        (tag[127] < sizeof (id3_genres) / sizeof (id3_genres[0])) )
   1769     return id3_emit (ctx,
   1770                      EXTRACTOR_METATYPE_GENRE,
   1771                      id3_genres[tag[127]]);
   1772   return 0;
   1773 }
   1774 
   1775 
   1776 /**
   1777  * Read and parse the ID3v2 tag at the start of the file.
   1778  *
   1779  * @param ctx our state
   1780  * @param head the ten byte tag header
   1781  * @param tag_size size of the tag body, from the header
   1782  * @return 1 if the caller should stop extracting, 0 to continue
   1783  */
   1784 static int
   1785 extract_v2 (struct Id3Context *ctx,
   1786             const unsigned char *head,
   1787             uint64_t tag_size)
   1788 {
   1789   unsigned char *buf;
   1790   size_t len;
   1791   size_t skip = 0;
   1792   unsigned int major = head[3];
   1793   int tag_unsync = (0 != (head[5] & 0x80)) ? 1 : 0;
   1794   int ret;
   1795 
   1796   len = (tag_size < ID3_MAX_TAG_READ)
   1797         ? (size_t) tag_size
   1798         : ID3_MAX_TAG_READ;
   1799   if (len < 10)
   1800     return 0;
   1801   buf = malloc (len);
   1802   if (NULL == buf)
   1803     return 0;
   1804   if (! EXTRACTOR_forensic_read_ (ctx->ec,
   1805                                   10,
   1806                                   buf,
   1807                                   len))
   1808   {
   1809     free (buf);
   1810     return 0;
   1811   }
   1812   if ( (tag_unsync) &&
   1813        (4 > major) )
   1814   {
   1815     /* up to 2.3 the whole tag body is unsynchronised as one unit; from
   1816        2.4 it is a per-frame property, handled in walk_frames() */
   1817     len = deunsynchronise (buf,
   1818                            len);
   1819     tag_unsync = 0;
   1820   }
   1821   if (0 != (head[5] & 0x40))
   1822   {
   1823     /* extended header; 2.3 states a size that excludes its own four
   1824        byte field, 2.4 a synchsafe size that includes it */
   1825     if (len < 4)
   1826     {
   1827       free (buf);
   1828       return 0;
   1829     }
   1830     if (4 == major)
   1831       skip = (((size_t) buf[0]) << 21)
   1832              | (((size_t) buf[1]) << 14)
   1833              | (((size_t) buf[2]) << 7)
   1834              | ((size_t) buf[3]);
   1835     else
   1836       skip = (size_t) EXTRACTOR_forensic_be32_ (buf) + 4;
   1837     if (skip >= len)
   1838     {
   1839       free (buf);
   1840       return 0;
   1841     }
   1842   }
   1843   ret = walk_frames (ctx,
   1844                      major,
   1845                      tag_unsync,
   1846                      &buf[skip],
   1847                      len - skip);
   1848   free (buf);
   1849   return ret;
   1850 }
   1851 
   1852 
   1853 /**
   1854  * Decide whether the file opens with MPEG audio.
   1855  *
   1856  * A single frame header is not enough evidence.  The pattern is four
   1857  * bytes with eleven set bits at the front, and although rejecting
   1858  * every reserved field value cuts the false positive rate a long way,
   1859  * arbitrary binary still produces one now and then.  Requiring the
   1860  * next frame to follow exactly where this one says it will, with the
   1861  * same version, layer and sampling rate, is what makes it evidence.
   1862  *
   1863  * @param ec extraction context
   1864  * @param head the first four bytes of the file
   1865  * @param size size of the file
   1866  * @return 1 if the file begins with a confirmed frame, 0 if not
   1867  */
   1868 static int
   1869 confirm_sync (struct EXTRACTOR_ExtractContext *ec,
   1870               const unsigned char *head,
   1871               uint64_t size)
   1872 {
   1873   struct MpegHeader first;
   1874   struct MpegHeader next;
   1875   unsigned char raw[4];
   1876 
   1877   if (! parse_mpeg_header (head,
   1878                            &first))
   1879     return 0;
   1880   if (((uint64_t) first.frame_len) + 4 > size)
   1881     return 0;
   1882   if (! EXTRACTOR_forensic_read_ (ec,
   1883                                   (int64_t) first.frame_len,
   1884                                   raw,
   1885                                   sizeof (raw)))
   1886     return 0;
   1887   if (! parse_mpeg_header (raw,
   1888                            &next))
   1889     return 0;
   1890   return ( (next.version == first.version) &&
   1891            (next.layer == first.layer) &&
   1892            (next.sample_rate == first.sample_rate) ) ? 1 : 0;
   1893 }
   1894 
   1895 
   1896 /**
   1897  * Main entry method for the 'audio/mpeg' extraction plugin.
   1898  *
   1899  * @param ec extraction context provided to the plugin
   1900  */
   1901 void
   1902 EXTRACTOR_id3_extract_method (struct EXTRACTOR_ExtractContext *ec);
   1903 
   1904 void
   1905 EXTRACTOR_id3_extract_method (struct EXTRACTOR_ExtractContext *ec)
   1906 {
   1907   struct Id3Context ctx;
   1908   unsigned char head[10];
   1909   unsigned char v1[128];
   1910   uint64_t size;
   1911   uint64_t tag_size = 0;
   1912   uint64_t audio_start = 0;
   1913   int have_v2 = 0;
   1914   int have_v1 = 0;
   1915 
   1916   size = ec->get_size (ec->cls);
   1917   if ( (UINT64_MAX == size) ||
   1918        (size < 128) )
   1919     return;
   1920   if (! EXTRACTOR_forensic_read_ (ec,
   1921                                   0,
   1922                                   head,
   1923                                   sizeof (head)))
   1924     return;
   1925   if ( (0 == memcmp (head,
   1926                      "ID3",
   1927                      3)) &&
   1928        (head[3] >= 2) &&
   1929        (head[3] <= 4) &&
   1930        (0xFF != head[4]) &&
   1931        (0 == (head[6] & 0x80)) &&
   1932        (0 == (head[7] & 0x80)) &&
   1933        (0 == (head[8] & 0x80)) &&
   1934        (0 == (head[9] & 0x80)) )
   1935   {
   1936     /* the tag size is synchsafe: seven bits per byte, so that no run
   1937        of bytes in the header can be mistaken for a frame sync */
   1938     tag_size = (((uint64_t) head[6]) << 21)
   1939                | (((uint64_t) head[7]) << 14)
   1940                | (((uint64_t) head[8]) << 7)
   1941                | ((uint64_t) head[9]);
   1942     audio_start = 10 + tag_size;
   1943     if (0 != (head[5] & 0x10))
   1944       audio_start += 10;   /* footer */
   1945     if (audio_start <= size)
   1946       have_v2 = 1;
   1947   }
   1948   if (! have_v2)
   1949   {
   1950     /* No tag in front.  Either the audio starts right here, or this is
   1951        one of the files that carry nothing but an ID3v1 tag at the very
   1952        end -- the only case in which we look at the tail of a file we
   1953        have not yet identified, and the reason for the read below. */
   1954     if (! confirm_sync (ec,
   1955                         head,
   1956                         size))
   1957     {
   1958       if (! EXTRACTOR_forensic_read_ (ec,
   1959                                       (int64_t) (size - 128),
   1960                                       v1,
   1961                                       sizeof (v1)))
   1962         return;
   1963       if (0 != memcmp (v1,
   1964                        "TAG",
   1965                        3))
   1966         return;
   1967       have_v1 = 1;
   1968     }
   1969   }
   1970   if (! have_v1)
   1971   {
   1972     if (EXTRACTOR_forensic_read_ (ec,
   1973                                   (int64_t) (size - 128),
   1974                                   v1,
   1975                                   sizeof (v1)))
   1976       have_v1 = (0 == memcmp (v1,
   1977                               "TAG",
   1978                               3)) ? 1 : 0;
   1979   }
   1980   memset (&ctx,
   1981           0,
   1982           sizeof (ctx));
   1983   ctx.ec = ec;
   1984   if (EXTRACTOR_forensic_emit_text_ (ec,
   1985                                      ID3_PLUGIN,
   1986                                      EXTRACTOR_METATYPE_MIMETYPE,
   1987                                      ID3_MIME,
   1988                                      strlen (ID3_MIME)))
   1989     return;
   1990   if (have_v2)
   1991   {
   1992     if (EXTRACTOR_forensic_emit_ (ec,
   1993                                   ID3_PLUGIN,
   1994                                   EXTRACTOR_METATYPE_FORMAT_VERSION,
   1995                                   "ID3v2.%u.%u",
   1996                                   (unsigned int) head[3],
   1997                                   (unsigned int) head[4]))
   1998       return;
   1999     if (extract_v2 (&ctx,
   2000                     head,
   2001                     tag_size))
   2002       return;
   2003   }
   2004   if (extract_audio (&ctx,
   2005                      audio_start,
   2006                      have_v1 ? (size - 128) : size))
   2007     return;
   2008   if (have_v1)
   2009     (void) extract_v1 (&ctx,
   2010                        v1);
   2011 }
   2012 
   2013 
   2014 /* end of id3_extractor.c */