idiii (empty) → 0.0
raw patch · 23 files changed
+3405/−0 lines, 23 filesdep +MissingHdep +basedep +bytestringsetup-changed
Dependencies added: MissingH, base, bytestring, containers, data-accessor, encoding, haskell98, polyparse, utf8-string
Files
- LICENSE +10/−0
- Setup.lhs +5/−0
- idiii.cabal +37/−0
- src/ID3.hs +20/−0
- src/ID3/Parser.hs +26/−0
- src/ID3/Parser/ExtHeader.hs +52/−0
- src/ID3/Parser/Frame.hs +131/−0
- src/ID3/Parser/General.hs +318/−0
- src/ID3/Parser/Header.hs +66/−0
- src/ID3/Parser/NativeFrames.hs +1452/−0
- src/ID3/Parser/Tag.hs +35/−0
- src/ID3/Parser/UnSync.hs +137/−0
- src/ID3/ReadTag.hs +26/−0
- src/ID3/Simple.hs +83/−0
- src/ID3/Type.hs +19/−0
- src/ID3/Type/ExtHeader.hs +205/−0
- src/ID3/Type/Flags.hs +30/−0
- src/ID3/Type/Frame.hs +323/−0
- src/ID3/Type/FrameInfo.hs +114/−0
- src/ID3/Type/Header.hs +122/−0
- src/ID3/Type/Tag.hs +123/−0
- src/ID3/Type/Unparse.hs +33/−0
- src/ID3/WriteTag.hs +38/−0
+ LICENSE view
@@ -0,0 +1,10 @@+Copyright (c) 2009, Laughedelic+All rights reserved.++Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:++ * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.+ * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.+ * Neither the name of the Laughedelic nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ Setup.lhs view
@@ -0,0 +1,5 @@+#! /usr/bin/env runhaskell+ +> import Distribution.Simple+> main = defaultMain+
+ idiii.cabal view
@@ -0,0 +1,37 @@+Name: idiii+Version: 0.0+Synopsis: ID3v2 tag editing-suite+Description: ID3v2 tag editing-suite+Category: Text, Sound+License: BSD3+License-file: LICENSE+Author: laughedelic+Maintainer: laughedelic@gmail.com+Build-Depends: base < 5, polyparse, haskell98, bytestring, encoding, data-accessor, utf8-string, containers, MissingH+Build-Type: Simple+hs-source-dirs: src+Exposed-modules: ID3,+ ID3.Simple,++ ID3.Parser,+ ID3.Parser.Header,+ ID3.Parser.ExtHeader,+ ID3.Parser.Frame,+ ID3.Parser.Tag,+ ID3.Parser.General,+ ID3.Parser.UnSync,+ ID3.Parser.NativeFrames,++ ID3.Type,+ ID3.Type.Header,+ ID3.Type.ExtHeader,+ ID3.Type.Frame,+ ID3.Type.FrameInfo,+ ID3.Type.Tag,+ ID3.Type.Flags,+ ID3.Type.Unparse,++ ID3.ReadTag,+ ID3.WriteTag+ghc-options: -Wall+
+ src/ID3.hs view
@@ -0,0 +1,20 @@+module ID3+(+ module ID3.Type+ , module ID3.Parser++ , module ID3.ReadTag+ , module ID3.WriteTag++ , module Data.Accessor+)++where++import ID3.Type+import ID3.Parser++import ID3.ReadTag+import ID3.WriteTag++import Data.Accessor
+ src/ID3/Parser.hs view
@@ -0,0 +1,26 @@+module ID3.Parser+(+ module ID3.Parser.Tag+ , module ID3.Parser.Header+ , module ID3.Parser.ExtHeader+ , module ID3.Parser.Frame+ , module ID3.Parser.General++ , module ID3.Parser.UnSync+ , module ID3.Parser.NativeFrames++ , module Text.ParserCombinators.Poly.State+)+where+++import ID3.Parser.Tag+import ID3.Parser.Header+import ID3.Parser.ExtHeader+import ID3.Parser.Frame+import ID3.Parser.General++import ID3.Parser.UnSync+import ID3.Parser.NativeFrames++import Text.ParserCombinators.Poly.State
+ src/ID3/Parser/ExtHeader.hs view
@@ -0,0 +1,52 @@+-- | This module provides parsers for Extended Header+--+-- (<http://www.id3.org/id3v2.4.0-structure>)+module ID3.Parser.ExtHeader+ (parseExtHeader)+where++---- IMPORTS+import ID3.Parser.General+import ID3.Type.ExtHeader++import Data.Accessor+import Data.Word (Word8)+----++++-- | Parses Extended Header as 'ID3ExtHeader' structure+parseExtHeader :: TagParser ID3ExtHeader+parseExtHeader = do+ s <- parseSize_ 4 `err` "ext header size" -- Extended header size 4 * %0xxxxxxx+ word8 0x01 `err` "ext header pre-flags" -- Number of flag bytes $01+ [b,c,d] <- parseFlags_ [2,3,4] `err` "ext header flags" -- Extended Flags %0bcd0000+ bb <- if b then parseB else return False+ cc <- if c then parseC else return []+ dd <- if d then parseD else return []+ return $ initID3ExtHeader [ extSize^=s+ , extFlags^=(initExtFlags [ isUpdate^=bb+ , crc^=cc+ , restrictions^=dd+ ])+ ]+++-- | parser for @b@ flag - 'isUpdate'+parseB :: TagParser Bool+parseB = do+ word8 0x00+ return True++-- | parser for @c@ flag - CRC data+parseC :: TagParser [Word8]+parseC = do+ word8 0x05+ count 5 anyWord8++-- | parser for @d@ flag - restrictions flags+-- TODO: make Flags type and structure for these flags+parseD :: TagParser [Bool]+parseD = do+ word8 0x01+ parseFlags_ [1..8]
+ src/ID3/Parser/Frame.hs view
@@ -0,0 +1,131 @@+-- | This Module provides parsers for frames.+module ID3.Parser.Frame+where++---- IMPORTS+import Text.ParserCombinators.Poly.State++import ID3.Parser.General+import ID3.Parser.NativeFrames+import ID3.Type.Frame+import ID3.Type.Flags++import Data.Accessor+import Data.Map (Map)+import qualified Data.Map as Map++import qualified Data.ByteString.Lazy as BS+import qualified Data.ByteString.Lazy.Char8 as C+----++parseFrames :: TagParser ([FrameID], Map FrameID ID3Frame)+parseFrames = do+ frames <- many1 anyFrame+ let idList = map (\f -> f^.frHeader^.frID) frames+ return ( idList , Map.fromList (zip idList frames) )++-- | Parses any Frame Header+anyFrameHeader :: TagParser FrameHeader+anyFrameHeader = do+ i <- frameID `err` "frame id"+ s <- frameSize `err` "frame size"+ f <- frameFlags `err` "frame flags"+ return $ initFrameHeader [frID^=i, frSize^=s, frFlags^=f]++-- | Parses any Frame+anyFrame :: TagParser ID3Frame+anyFrame = do+ h <- anyFrameHeader `err` "frame header"+ i <- frameInfo (h^.frID) `err` "frame info"+ return $ initID3Frame [frHeader^=h, frInfo^=i]++-- | Parses Frame Header with given id+frameHeader :: FrameID -> TagParser FrameHeader+frameHeader i = do+ string i+ s <- frameSize+ f <- frameFlags+ return $ initFrameHeader [frID^=i, frSize^=s, frFlags^=f]++-- | Parses Frame with given id+parseFrame :: FrameID -> TagParser ID3Frame+parseFrame id = do+ h <- frameHeader id+ i <- frameInfo id+ return $ initID3Frame [frHeader^=h, frInfo^=i]++frameID :: TagParser FrameID+frameID = do+ name <- count 4 $ upper `onFail` digit+ posUpdate (+4)+ return $ C.unpack $ BS.pack name++frameSize :: TagParser FrameSize+frameSize = parseSize_ 4++frameFlags = do+ s <- frameStatusFlags `err` "status flags"+ f <- frameFormatFlags `err` "format flags"+ return $ initFrameFlags [status^=s, format^=f]++frameStatusFlags = do+ fs <- parseFlags_ [2,3,4]+ return $ mkFlags [2,3,4] fs+ -- i.e. %0abc0000++frameFormatFlags = do+ fs <- parseFlags_ [2,5,6,7,8]+ return $ mkFlags [2,5,6,7,8] fs+ -- i.e. %0h00kmnp+++-- {-- FRAME CONTENT+{-+ -If nothing else is said, strings, including numeric strings and URLs+ - [URL], are represented as ISO-8859-1 [ISO-8859-1] characters in the+ - range $20 - $FF. Such strings are represented in frame descriptions+ - as <text string>, or <full text string> if newlines are allowed. If+ - nothing else is said newline character is forbidden. In ISO-8859-1 a+ - newline is represented, when allowed, with $0A only.+ -+ - Frames that allow different types of text encoding contains a text+ - encoding description byte. Possible encodings:+ -+ - $00 ISO-8859-1 [ISO-8859-1]. Terminated with $00.+ - $01 UTF-16 [UTF-16] encoded Unicode [UNICODE] with BOM. All+ - strings in the same frame SHALL have the same byteorder.+ - Terminated with $00 00.+ - $02 UTF-16BE [UTF-16] encoded Unicode [UNICODE] without BOM.+ - Terminated with $00 00.+ - $03 UTF-8 [UTF-8] encoded Unicode [UNICODE]. Terminated with $00.+ -+ - Strings dependent on encoding are represented in frame descriptions+ - as <text string according to encoding>, or <full text string+ - according to encoding> if newlines are allowed. Any empty strings of+ - type $01 which are NULL-terminated may have the Unicode BOM followed+ - by a Unicode NULL ($FF FE 00 00 or $FE FF 00 00).+ -+ - The timestamp fields are based on a subset of ISO 8601. When being as+ - precise as possible the format of a time string is+ - yyyy-MM-ddTHH:mm:ss (year, "-", month, "-", day, "T", hour (out of+ - 24), ":", minutes, ":", seconds), but the precision may be reduced by+ - removing as many time indicators as wanted. Hence valid timestamps+ - are+ - yyyy, yyyy-MM, yyyy-MM-dd, yyyy-MM-ddTHH, yyyy-MM-ddTHH:mm and+ - yyyy-MM-ddTHH:mm:ss. All time stamps are UTC. For durations, use+ - the slash character as described in 8601, and for multiple non-+ - contiguous dates, use multiple strings, if allowed by the frame+ - definition.+ -+ - The three byte language field, present in several frames, is used to+ - describe the language of the frame's content, according to ISO-639-2+ - [ISO-639-2]. The language should be represented in lower case. If the+ - language is not known the string "XXX" should be used.+ -+ - All URLs [URL] MAY be relative, e.g. "picture.png", "../doc.txt".+ -+ - If a frame is longer than it should be, e.g. having more fields than+ - specified in this document, that indicates that additions to the+ - frame have been made in a later version of the ID3v2 standard. This+ - is reflected by the revision number in the header of the tag.+ --}
+ src/ID3/Parser/General.hs view
@@ -0,0 +1,318 @@+-- | This module contain different general parsers.+module ID3.Parser.General where++---- IMPORTS+import Text.ParserCombinators.Poly.State+import ID3.Parser.UnSync+import qualified Data.ByteString.Lazy as BS+import qualified Data.ByteString.Lazy.Char8 as C+import Data.Word (Word8)+import Bits+import Data.Accessor+import Data.Encoding+import Data.Encoding.ISO88591+import Data.Encoding.UTF8+import Data.Encoding.UTF16+import Data.ByteString.Lazy.UTF8 (toString)+import Codec.Binary.UTF8.String as Codec+----++---,--------------------------------+-- | Just a synonim for one item of input stream+type Token = Word8++-- | Parsers state+data St = State { tagPos :: Integer -- ^ current position in tag+-- , headerFlags :: [Bool] -- ^+-- , frFlags :: [Bool]} -- ^ current frame flags+ , curSize :: Integer -- ^ current frame size+ , curEncoding :: Integer -- ^ current frame encoding+ }++instance Show St where+ show st = show (tagPos st+ ,curSize st+ ,curEncoding st)+initState = State 0 10 0++type TagParser = Parser St Token++run :: TagParser a -> [Word8] -> (Either String a, [Token])+run p cont = (result, rest) where (result, _, rest) = runParser p initState cont++---,--------------------------------++-- pos = accessor (stGet >>= return . tagPos) (stUpdate $ \p st -> st {tagPos = p} )++-- | Returns 'tagPos' from 'St'.+posGet :: TagParser Integer+posGet = stGet >>= return . tagPos+-- | Updates 'tagPos' with given function.+posUpdate :: (Integer -> Integer) -> TagParser ()+posUpdate f = stUpdate ( \st -> st {tagPos = f (tagPos st)} )+-- | Sets 'tagPos' with given value.+posSet :: Integer -> TagParser ()+posSet p = posUpdate (\_ -> p)+-- | Decrements 'tagPos'.+posDec :: TagParser ()+posDec = posUpdate (\p -> p-1)+-- | Incremets 'tagPos'.+posInc :: TagParser ()+posInc = posUpdate (\p -> p+1)++---,--------------------------------+-- | Returns 'curSize' from 'St'.+sizeGet :: TagParser Integer+sizeGet = stGet >>= return . curSize+-- | Updates 'curSize' with given function.+sizeUpdate :: (Integer -> Integer) -> TagParser ()+sizeUpdate f = stUpdate ( \st -> st {curSize = f (curSize st)} )+-- | Sets 'curSize' with given value.+sizeSet :: Integer -> TagParser ()+sizeSet s = sizeUpdate (\_ -> s)+-- | Decrements 'curSize'.+sizeDec :: TagParser ()+sizeDec = sizeUpdate (\x -> x-1)+-- | Incremets 'curSize'.+sizeInc :: TagParser ()+sizeInc = sizeUpdate (\x -> x+1)++---,--------------------------------+-- | Returns 'curEncoding' from 'St'.+encGet :: TagParser Integer+encGet = stGet >>= return . curEncoding+-- | Updates 'curEncoding' with given function.+encUpdate :: (Integer -> Integer) -> TagParser ()+encUpdate f = stUpdate ( \st -> st {curEncoding = f (curEncoding st)} )+-- | Sets 'curEncoding' with given value.+encSet :: Integer -> TagParser ()+encSet e = encUpdate (\_ -> e)+-- | Parses one byte and sets 'curEncoding'.+encRead :: TagParser Integer+encRead = anyWord8 >>= encSet . toInteger >> encGet+++---,--------------------------------+-- | Wrapper for /reiterative/ parsers.+-- Mnemonic: @if 'curSize' > 0 then@ continue @else@ stop+ifSize :: TagParser [a] -> TagParser [a]+ifSize p = do+ s <- sizeGet+ if s > 0+ then p+ else return []++-- | Wrapper for atomic parsers.+-- Increases 'tagPos' and decreases 'curSize'.+withSize p = do+ x <- p+ sizeDec+ posInc+ return x++-- Wrapper for any parser, that increaser tagPos and decreases curSize according to result of parsing+-- It is useful only for parsers, that return as much tokens, as they've read from the stream.+-- If result is list, then state updates according to it's length, else (!) result takes as a single-sized value.+{-withState :: TagParser a -> TagParser a+withState parser = do+ x <- parser+ case x of+ [] -> return x -- empty list+ (_:_) -> do -- non-empty list+ let n = toInteger $ length x+ posUpdate (+n)+ sizeUpdate (subtract n)+ return x+ _ -> do -- singleton+ posInc+ sizeDec+ return x+-}++---,--------------------------------+-- | @'many'' p@ parses a list of elements with individual parser @p@.+-- Cannot fail, since an empty list is a valid return value.+-- Unlike default 'many', stops if 'curSize' became 0.+many' :: TagParser a -> TagParser [a]+many' p = many1' p `onFail` return []++-- | Parse a non-empty list of items.+many1' :: TagParser a -> TagParser [a]+many1' p = ifSize $ do+ x <- p+ xs <- many' p+ return (x:xs)+++---,--------------------------------+-- | @'manyTill'' p end@ parses a possibly-empty sequence of @p@'s, terminated by a @end@.+manyTill' :: TagParser a -> TagParser z -> TagParser [a]+manyTill' p end = manyTill1' p end `onFail` return []++-- | 'manyTill1\' p end' parses a non-empty sequence of p's, terminated by a end.+manyTill1' :: TagParser a -> TagParser z -> TagParser [a]+manyTill1' p end = ifSize $ (end >> return []) `onFail`+ (ifSize $ do+ x <- p+ xs <- manyTill' p end+ return (x:xs))++skipTill p end = end `onFail` do {p; skipTill p end}++---,--------------------------------+-- | Parse a list of items separated by discarded junk.+sepBy' :: TagParser a -> TagParser sep -> TagParser [a]+sepBy' p sep = sepBy1' p sep `onFail` return []++-- | Parse a non-empty list of items separated by discarded junk.+sepBy1' :: TagParser a -> TagParser sep -> TagParser [a]+sepBy1' p sep= ifSize $ do+ x <- p+ xs <- many' (sep >> p)+ return (x:xs)++---,--------------------------------+-- | 'count n p' parses a precise number of items, n, using the parser p, in sequence.+count :: (Num n) => n -> TagParser a -> TagParser [a]+count 0 _ = return []+count n p = do+ x <- p+ xs <- count (n-1) p+ return (x:xs)++-- | 'count' n p' parses a precise number of items, n, using the parser p, in sequence.+count' :: (Num n) => n -> TagParser a -> TagParser [a]+count' 0 _ = return []+count' n p = ifSize $ do+ x <- p+ xs <- count' (n-1) p+ return (x:xs)++---,--------------------------------+-- | Hybrid of 'count' and 'sepBy\''+countSepBy' :: (Num n) => n -> TagParser a -> TagParser sep -> TagParser [a]+countSepBy' 0 _ _ = return []+countSepBy' n p sep = ifSize $ do+ x <- p+ xs <- count' (n-1) (sep >> p)+ return (x:xs)++---,--------------------------------+-- | 'terminator' parses values termination symbol, according to current encoding ('curEncoding').+terminator :: TagParser [Token]+terminator = do+ enc <- encGet+ case enc of+ 0x01 -> word8s [00,00] -- UTF-16+ 0x02 -> word8s [00,00] -- UTF-16 BOM+ _ -> word8s [00] -- ISO-8859-1 or UTF-8++encPack :: Integer -> [Token] -> String+encPack 0x00 = toString . recode' ISO88591 UTF8 . BS.pack . filter (/=00)+encPack 0x01 = toString . recode' UTF16 UTF8 . BS.pack . filter (/=00)+encPack 0x02 = toString . recode' UTF16 UTF8 . BS.pack . filter (/=00)+encPack _ = Codec.decode . filter (/=00)++recode' from to = Data.Encoding.encodeLazyByteString to . Data.Encoding.decodeLazyByteString from++---,--------------------------------+-- | Parses a list of values (as [Token]) separated with termination symbol+parseValues :: (Num n) => n -> TagParser [[Token]]+parseValues n = countSepBy' n (many' nonNull) terminator++-- | Parses one value (as [Token]) till termination symbol+parseValue :: TagParser [Token]+parseValue = nonNull `manyTill'` terminator++-- any byte except null+nonNull = withSize $ satisfy (/=0x00) `adjustErr` (++"\nWTF: nonNull")++-- | Parses one value and returns it as a 'String'+parseString :: TagParser String+parseString = do+ e <- encGet+ v <- parseValue+ return $ encPack e v -- C.unpack . BS.pack++-- | Parses one value and returns it as a 'Integer'+parseNumber :: TagParser Integer+parseNumber = parseValue >>= return . sum . (zipWith (*) (iterate (*10) 1)) . reverse . map toInteger++-- | Parses 3 bytes of language value (as a String) and returns a pair ("Language", value)+parseLanguage :: TagParser String+parseLanguage = do+ lang <- count' 3 anyWord8+ return $ encPack 0x03 lang++-- | Takes a list of keys and parses a list of values. Result is zip of these two lists.+formValues :: [String] -> TagParser [(String, String)]+formValues keys = do+ enc <- encGet+ vals <- parseValues (length keys)+ return $ zip keys $ map (encPack enc) vals++--(<|>) = onFail++---,--------------------------------+-- | Takes a list of 'Parser's and applies them by turns.+parsers :: [TagParser a] -> TagParser [a]+parsers [] = return []+parsers (p:ps) = do+ x <- p+ xs <- parsers ps+ return (x:xs)++---,--------------------------------+-- | Parses given 'Token'.+word8 :: Token -> TagParser Token+word8 w = (withSize $ satisfy (==w)) `err` (" \nWTF: word8 "++(show w))++-- | Parses given list of 'Token's.+word8s :: [Token] -> TagParser [Token]+word8s ws = parsers $ map word8 ws++-- | Parses given 'ByteString'.+byteString :: BS.ByteString -> TagParser BS.ByteString+byteString bs = (word8s $ BS.unpack bs) >> return bs++-- | Same as 'byteString' but argument is simple 'String'.+string :: String -> TagParser BS.ByteString+string = byteString . C.pack++-- | Parses upper-case letters (as 'Token')+upper :: TagParser Token+upper = satisfy (\x -> (0x41<=x)&&(x<=0x5a)) `err` ("\nWTF: upper")++-- | Parses digit-symbol (as 'Token')+digit :: TagParser Token+digit = satisfy (\x -> (0x30<=x)&&(x<=0x39)) `err` ("\nWTF: digit")++---,--------------------------------+-- | Parses any 'Token'.+anyWord8 :: TagParser Token+anyWord8 = withSize next `err` "anyWord8"++err p s = do+ pos <- posGet+ p `adjustErr` (++"\n"++"at "++(show pos)++": "++s)++---,--------------------------------+type Size = Integer+-- | 'parseSize_ n' parses n bytes of synchronized size-value, and returns unsynchronized 'Integer' value.+parseSize_ :: Integer -> TagParser Size+parseSize_ n = do+ s <- count n next+ let size = unSynchronise s+ posUpdate (+n)+ sizeSet size+ return size++-- | Takes template of flags-byte and returns it as ['Bool'] value.+-- For example, for %abcd0000 template you should use 'parseFlags_ [1..4]'.+parseFlags_ :: [Int] -> TagParser [Bool]+parseFlags_ nums = do+ flag <- anyWord8+ sizeInc+-- posInc+ return $ map (\i -> testBit flag (i-1)) nums+
+ src/ID3/Parser/Header.hs view
@@ -0,0 +1,66 @@+{- |+This module provides parsers for Header.++(<http://www.id3.org/id3v2.4.0-structure>)+-}+module ID3.Parser.Header+ ( parseHeader+ , parseFooter+ )+where++---- IMPORTS+import Text.ParserCombinators.Poly.State+import ID3.Parser.General+import ID3.Type.Header+import ID3.Type.Flags+import Data.Accessor+----+++---,-----------------------------+-- | Parses id3v2 'Header'+parseHeader :: TagParser ID3Header+parseHeader = do+ string "ID3" `err` "ID3"+ parseHeader_++parseHeader_ = do+ v <- parseVersion `err` "tag version"+ f <- parseFlags `err` "tag flags"+ s <- parseSize `err` "tag size"+ return $ initID3Header [tagVersion^=v, tagFlags^=f, tagSize^=s]+ -- i.e. return ([major version, revision number], [a, b, c, d], size)++parseVersion :: TagParser TagVersion+parseVersion = count 2 anyWord8++parseFlags :: TagParser TagFlags+parseFlags = do+ fs <- parseFlags_ [1..4]+ return $ mkFlags [1..4] fs+ -- i.e. %abcd0000++parseSize :: TagParser TagSize+parseSize = parseSize_ 4++{- | /ID3v2 FOOTER/ (optional)++ To speed up the process of locating an ID3v2 tag when searching from+ the end of a file, a footer can be added to the tag. It is REQUIRED+ to add a footer to an appended tag, i.e. a tag located after all+ audio data. The footer is a copy of the header, but with a different+ identifier.++@+ ID3v2 identifier \"3DI\"+ ID3v2 version $04 00+ ID3v2 flags %abcd0000+ ID3v2 size 4 * %0xxxxxxx+@++-}+parseFooter :: TagParser ID3Header+parseFooter = do+ string "3DI"+ parseHeader_
+ src/ID3/Parser/NativeFrames.hs view
@@ -0,0 +1,1452 @@+module ID3.Parser.NativeFrames+where++-- {-- IMPORTS+import qualified Data.ByteString.Lazy as BS+import qualified Data.ByteString.Lazy.Char8 as C+import ID3.Parser.UnSync+import ID3.Parser.General+import ID3.Type.FrameInfo+{-import ID3.Type.Frame-}+----}+++--frameInfo :: String -> TagParser (FrameName, FrameInfo)+++---- {-- TODO: 4.1. Unique file identifier++-- This frame's purpose is to be able to identify the audio file in a+-- database, that may provide more information relevant to the content.+-- Since standardisation of such a database is beyond this document, all+-- UFID frames begin with an 'owner identifier' field. It is a null-+-- terminated string with a URL [URL] containing an email address, or a+-- link to a location where an email address can be found, that belongs+-- to the organisation responsible for this specific database+-- implementation. Questions regarding the database should be sent to+-- the indicated email address. The URL should not be used for the+-- actual database queries. The string+-- "http://www.id3.org/dummy/ufid.html" should be used for tests. The+-- 'Owner identifier' must be non-empty (more than just a termination).+-- The 'Owner identifier' is then followed by the actual identifier,+-- which may be up to 64 bytes. There may be more than one "UFID" frame+-- in a tag, but only one with the same 'Owner identifier'.++ -- <Header for 'Unique file identifier', ID: "UFID">+ -- Owner identifier <text string> $00+ -- Identifier <up to 64 bytes binary data>+---- --}++++---- {-- 4.2. Text information frames++-- The text information frames are often the most important frames,+-- containing information like artist, album and more. There may only be+-- one text information frame of its kind in an tag. All text+-- information frames supports multiple strings, stored as a null+-- separated list, where null is reperesented by the termination code+-- for the charater encoding. All text frame identifiers begin with "T".+-- Only text frame identifiers begin with "T", with the exception of the+-- "TXXX" frame. All the text information frames have the following+-- format:++ -- <Header for 'Text information frame', ID: "T000" - "TZZZ",+ -- excluding "TXXX" described in 4.2.6.>+ -- Text encoding $xx+ -- Information <text string(s) according to encoding>++textInfo :: String -> TagParser FrameInfo+textInfo _ = do+ enc <- encRead+ info <- parseString+ return $ Text enc info --(name, [("Information", encPack enc info)])++---- {-- 4.3. URL link frames++-- With these frames dynamic data such as webpages with touring+-- information, price information or plain ordinary news can be added to+-- the tag. There may only be one URL [URL] link frame of its kind in an+-- tag, except when stated otherwise in the frame description. If the+-- text string is followed by a string termination, all the following+-- information should be ignored and not be displayed. All URL link+-- frame identifiers begins with "W". Only URL link frame identifiers+-- begins with "W", except for "WXXX". All URL link frames have the+-- following format:++ -- <Header for 'URL link frame', ID: "W000" - "WZZZ", excluding "WXXX"+ -- described in 4.3.2.>+ -- URL <text string>++urlInfo name = do+ --info <- formValues ["URL"]+ url <- parseString+ return $ URL url --(name, info)+++---- {-- 4.2.1. Identification frames++-- TIT1+-- The 'Content group description' frame is used if the sound belongs to+-- a larger category of sounds/music. For example, classical music is+-- often sorted in different musical sections (e.g. "Piano Concerto",+-- "Weather - Hurricane").+frameInfo "TIT1" = textInfo "Content group description"++-- TIT2+-- The 'Title/Songname/Content description' frame is the actual name of+-- the piece (e.g. "Adagio", "Hurricane Donna").+frameInfo "TIT2" = textInfo "Title"++-- TIT3+-- The 'Subtitle/Description refinement' frame is used for information+-- directly related to the contents title (e.g. "Op. 16" or "Performed+-- live at Wembley").+frameInfo "TIT3" = textInfo "Subtitle"++-- TALB+-- The 'Album/Movie/Show title' frame is intended for the title of the+-- recording (or source of sound) from which the audio in the file is+-- taken.+frameInfo "TALB" = textInfo "Album"++-- TOAL+-- The 'Original album/movie/show title' frame is intended for the title+-- of the original recording (or source of sound), if for example the+-- music in the file should be a cover of a previously released song.+frameInfo "TOAL" = textInfo "Original album"++-- TRCK+-- The 'Track number/Position in set' frame is a numeric string+-- containing the order number of the audio-file on its original+-- recording. This MAY be extended with a "/" character and a numeric+-- string containing the total number of tracks/elements on the original+-- recording. E.g. "4/9".+frameInfo "TRCK" = textInfo "Track number"++-- TPOS+-- The 'Part of a set' frame is a numeric string that describes which+-- part of a set the audio came from. This frame is used if the source+-- described in the "TALB" frame is divided into several mediums, e.g. a+-- double CD. The value MAY be extended with a "/" character and a+-- numeric string containing the total number of parts in the set. E.g.+-- "1/2".+frameInfo "TPOS" = textInfo "Part of a set"++-- TSST+-- The 'Set subtitle' frame is intended for the subtitle of the part of+-- a set this track belongs to.+frameInfo "TSST" = textInfo "Set subtitle"++-- TSRC+-- The 'ISRC' frame should contain the International Standard Recording+-- Code [ISRC] (12 characters).+frameInfo "TSRC" = textInfo "International Standard Recording Code [ISRC]"+---- --}++---- {-- 4.2.2. Involved persons frames++-- TPE1+-- The 'Lead artist/Lead performer/Soloist/Performing group' is+-- used for the main artist.+frameInfo "TPE1" = textInfo "Lead artist"++-- TPE2+-- The 'Band/Orchestra/Accompaniment' frame is used for additional+-- information about the performers in the recording.+frameInfo "TPE2" = textInfo "Accompaniment"++-- TPE3+-- The 'Conductor' frame is used for the name of the conductor.+frameInfo "TPE3" = textInfo "Conductor"++-- TPE4+-- The 'Interpreted, remixed, or otherwise modified by' frame contains+-- more information about the people behind a remix and similar+-- interpretations of another existing piece.+frameInfo "TPE4" = textInfo "Remixed by"++-- TOPE+-- The 'Original artist/performer' frame is intended for the performer+-- of the original recording, if for example the music in the file+-- should be a cover of a previously released song.+frameInfo "TOPE" = textInfo "Original artist"++-- TEXT+-- The 'Lyricist/Text writer' frame is intended for the writer of the+-- text or lyrics in the recording.+frameInfo "TEXT" = textInfo "Text writer"++-- TOLY+-- The 'Original lyricist/text writer' frame is intended for the+-- text writer of the original recording, if for example the music in+-- the file should be a cover of a previously released song.+frameInfo "TOLY" = textInfo "Original text writer"++-- TCOM+-- The 'Composer' frame is intended for the name of the composer.+frameInfo "TCOM" = textInfo "Composer"++-- TMCL+-- The 'Musician credits list' is intended as a mapping between+-- instruments and the musician that played it. Every odd field is an+-- instrument and every even is an artist or a comma delimited list of+-- artists.+frameInfo "TMCL" = textInfo "Musician credits list"++-- TIPL+-- The 'Involved people list' is very similar to the musician credits+-- list, but maps between functions, like producer, and names.+frameInfo "TIPL" = textInfo "Involved people list"++-- TENC+-- The 'Encoded by' frame contains the name of the person or+-- organisation that encoded the audio file. This field may contain a+-- copyright message, if the audio file also is copyrighted by the+-- encoder.+frameInfo "TENC" = textInfo "Encoded by"+---- --}++---- {-- 4.2.3. Derived and subjective properties frames++-- TBPM+-- The 'BPM' frame contains the number of beats per minute in the+-- main part of the audio. The BPM is an integer and represented as a+-- numerical string.+frameInfo "TBPM" = textInfo "Beats per minute"++-- TLEN+-- The 'Length' frame contains the length of the audio file in+-- milliseconds, represented as a numeric string.+frameInfo "TLEN" = textInfo "Length (in milliseconds)"++-- TKEY+-- The 'Initial key' frame contains the musical key in which the sound+-- starts. It is represented as a string with a maximum length of three+-- characters. The ground keys are represented with "A","B","C","D","E",+-- "F" and "G" and halfkeys represented with "b" and "#". Minor is+-- represented as "m", e.g. "Dbm" $00. Off key is represented with an+-- "o" only.+frameInfo "TKEY" = textInfo ""++-- TLAN+-- The 'Language' frame should contain the languages of the text or+-- lyrics spoken or sung in the audio. The language is represented with+-- three characters according to ISO-639-2 [ISO-639-2]. If more than one+-- language is used in the text their language codes should follow+-- according to the amount of their usage, e.g. "eng" $00 "sve" $00.+frameInfo "TLAN" = textInfo "Language"++-- TCON+-- The 'Content type', which ID3v1 was stored as a one byte numeric+-- value only, is now a string. You may use one or several of the ID3v1+-- types as numerical strings, or, since the category list would be+-- impossible to maintain with accurate and up to date categories,+-- define your own. Example: "21" $00 "Eurodisco" $00++-- You may also use any of the following keywords:++ -- RX Remix+ -- CR Cover+frameInfo "TCON" = textInfo "Content type"++-- TFLT+-- The 'File type' frame indicates which type of audio this tag defines.+-- The following types and refinements are defined:++ -- MIME MIME type follows+ -- MPG MPEG Audio+ -- /1 MPEG 1/2 layer I+ -- /2 MPEG 1/2 layer II+ -- /3 MPEG 1/2 layer III+ -- /2.5 MPEG 2.5+ -- /AAC Advanced audio compression+ -- VQF Transform-domain Weighted Interleave Vector Quantisation+ -- PCM Pulse Code Modulated audio++-- but other types may be used, but not for these types though. This is+-- used in a similar way to the predefined types in the "TMED" frame,+-- but without parentheses. If this frame is not present audio type is+-- assumed to be "MPG".+frameInfo "TFLT" = textInfo "File type"++-- TMED+-- The 'Media type' frame describes from which media the sound+-- originated. This may be a text string or a reference to the+-- predefined media types found in the list below. Example:+-- "VID/PAL/VHS" $00.+frameInfo "TMED" = textInfo "Media type"++-- {-- Media types:+-- DIG Other digital media+ -- /A Analogue transfer from media++-- ANA Other analogue media+ -- /WAC Wax cylinder+ -- /8CA 8-track tape cassette++-- CD CD+ -- /A Analogue transfer from media+ -- /DD DDD+ -- /AD ADD+ -- /AA AAD++-- LD Laserdisc++-- TT Turntable records+ -- /33 33.33 rpm+ -- /45 45 rpm+ -- /71 71.29 rpm+ -- /76 76.59 rpm+ -- /78 78.26 rpm+ -- /80 80 rpm++-- MD MiniDisc+ -- /A Analogue transfer from media++-- DAT DAT+ -- /A Analogue transfer from media+ -- /1 standard, 48 kHz/16 bits, linear+ -- /2 mode 2, 32 kHz/16 bits, linear+ -- /3 mode 3, 32 kHz/12 bits, non-linear, low speed+ -- /4 mode 4, 32 kHz/12 bits, 4 channels+ -- /5 mode 5, 44.1 kHz/16 bits, linear+ -- /6 mode 6, 44.1 kHz/16 bits, 'wide track' play++-- DCC DCC+ -- /A Analogue transfer from media++-- DVD DVD+ -- /A Analogue transfer from media++-- TV Television+ -- /PAL PAL+ -- /NTSC NTSC+ -- /SECAM SECAM++-- VID Video+ -- /PAL PAL+ -- /NTSC NTSC+ -- /SECAM SECAM+ -- /VHS VHS+ -- /SVHS S-VHS+ -- /BETA BETAMAX++-- RAD Radio+ -- /FM FM+ -- /AM AM+ -- /LW LW+ -- /MW MW++-- TEL Telephone+ -- /I ISDN++-- MC MC (normal cassette)+ -- /4 4.75 cm/s (normal speed for a two sided cassette)+ -- /9 9.5 cm/s+ -- /I Type I cassette (ferric/normal)+ -- /II Type II cassette (chrome)+ -- /III Type III cassette (ferric chrome)+ -- /IV Type IV cassette (metal)++-- REE Reel+ -- /9 9.5 cm/s+ -- /19 19 cm/s+ -- /38 38 cm/s+ -- /76 76 cm/s+ -- /I Type I cassette (ferric/normal)+ -- /II Type II cassette (chrome)+ -- /III Type III cassette (ferric chrome)+ -- /IV Type IV cassette (metal)+----}++-- TMOO+-- The 'Mood' frame is intended to reflect the mood of the audio with a+-- few keywords, e.g. "Romantic" or "Sad".+frameInfo "TMOD" = textInfo "Mood"+---- --}++---- {-- 4.2.4. Rights and license frames++-- TCOP+-- The 'Copyright message' frame, in which the string must begin with a+-- year and a space character (making five characters), is intended for+-- the copyright holder of the original sound, not the audio file+-- itself. The absence of this frame means only that the copyright+-- information is unavailable or has been removed, and must not be+-- interpreted to mean that the audio is public domain. Every time this+-- field is displayed the field must be preceded with "Copyright " (C) "+-- ", where (C) is one character showing a C in a circle.+frameInfo "TCOP" = textInfo "Copyright message"++-- TPRO+-- The 'Produced notice' frame, in which the string must begin with a+-- year and a space character (making five characters), is intended for+-- the production copyright holder of the original sound, not the audio+-- file itself. The absence of this frame means only that the production+-- copyright information is unavailable or has been removed, and must+-- not be interpreted to mean that the audio is public domain. Every+-- time this field is displayed the field must be preceded with+-- "Produced " (P) " ", where (P) is one character showing a P in a+-- circle.+frameInfo "TPRO" = textInfo "Produced notice"++-- TPUB+-- The 'Publisher' frame simply contains the name of the label or+-- publisher.+frameInfo "TPUB" = textInfo "Produced notice"++-- TOWN+-- The 'File owner/licensee' frame contains the name of the owner or+-- licensee of the file and it's contents.+frameInfo "TOWN" = textInfo "File owner/licensee"++-- TRSN+-- The 'Internet radio station name' frame contains the name of the+-- internet radio station from which the audio is streamed.+frameInfo "TRSN" = textInfo "Internet radio station name"++-- TRSO+-- The 'Internet radio station owner' frame contains the name of the+-- owner of the internet radio station from which the audio is+-- streamed.+frameInfo "TRSO" = textInfo "Internet radio station owner"+---- --}++---- {-- 4.2.5. Other text frames++-- TOFN+-- The 'Original filename' frame contains the preferred filename for the+-- file, since some media doesn't allow the desired length of the+-- filename. The filename is case sensitive and includes its suffix.+frameInfo "TOFN" = textInfo "Original filename"++-- TDLY+-- The 'Playlist delay' defines the numbers of milliseconds of silence+-- that should be inserted before this audio. The value zero indicates+-- that this is a part of a multifile audio track that should be played+-- continuously.+frameInfo "TDLY" = textInfo "Playlist delay"++-- TDEN+-- The 'Encoding time' frame contains a timestamp describing when the+-- audio was encoded. Timestamp format is described in the ID3v2+-- structure document [ID3v2-strct].+frameInfo "TDEN" = textInfo "Encoding time"++-- TDOR+-- The 'Original release time' frame contains a timestamp describing+-- when the original recording of the audio was released. Timestamp+-- format is described in the ID3v2 structure document [ID3v2-strct].+frameInfo "TDOR" = textInfo "Original release time"++-- TDRC+-- The 'Recording time' frame contains a timestamp describing when the+-- audio was recorded. Timestamp format is described in the ID3v2+-- structure document [ID3v2-strct].+frameInfo "TDRC" = textInfo "Recording time"++-- TDRL+-- The 'Release time' frame contains a timestamp describing when the+-- audio was first released. Timestamp format is described in the ID3v2+-- structure document [ID3v2-strct].+frameInfo "TDRL" = textInfo "Release time"++-- TDTG+-- The 'Tagging time' frame contains a timestamp describing then the+-- audio was tagged. Timestamp format is described in the ID3v2+-- structure document [ID3v2-strct].+frameInfo "TDTG" = textInfo "Tagging time"++-- TSSE+-- The 'Software/Hardware and settings used for encoding' frame+-- includes the used audio encoder and its settings when the file was+-- encoded. Hardware refers to hardware encoders, not the computer on+-- which a program was run.+frameInfo "TSSE" = textInfo "Software/Hardware and settings used for encoding"++-- TSOA+-- The 'Album sort order' frame defines a string which should be used+-- instead of the album name (TALB) for sorting purposes. E.g. an album+-- named "A Soundtrack" might preferably be sorted as "Soundtrack".+frameInfo "TSOA" = textInfo "Album sort order"++-- TSOP+-- The 'Performer sort order' frame defines a string which should be+-- used instead of the performer (TPE2) for sorting purposes.+frameInfo "TSOP" = textInfo "Performer sort order"++-- TSOT+-- The 'Title sort order' frame defines a string which should be used+-- instead of the title (TIT2) for sorting purposes.+frameInfo "TSOT" = textInfo "Title sort order"+---- --}++frameInfo "TCMP" = do+ encRead+ f <- parseNumber+ return $ TCMP (f == 1)++---- {-- 4.2.6. User defined text information frame++-- This frame is intended for one-string text information concerning the+-- audio file in a similar way to the other "T"-frames. The frame body+-- consists of a description of the string, represented as a terminated+-- string, followed by the actual string. There may be more than one+-- "TXXX" frame in each tag, but only one with the same description.++ -- <Header for 'User defined text information frame', ID: "TXXX">+ -- Text encoding $xx+ -- Description <text string according to encoding> $00 (00)+ -- Value <text string according to encoding>++frameInfo "TXXX" = do+ enc <- encRead+ descr <- parseString+ value <- parseString+ return $ TXXX enc descr value -- (name, info)++---- --} }}}++---- {-- 4.3.1. URL link frames - details++-- WCOM+-- The 'Commercial information' frame is a URL pointing at a webpage+-- with information such as where the album can be bought. There may be+-- more than one "WCOM" frame in a tag, but not with the same content.+frameInfo "WCOM" = urlInfo "Commercial information"++-- WCOP+-- The 'Copyright/Legal information' frame is a URL pointing at a+-- webpage where the terms of use and ownership of the file is+-- described.+frameInfo "WCOP" = urlInfo "Copyright/Legal information"++-- WOAF+-- The 'Official audio file webpage' frame is a URL pointing at a file+-- specific webpage.+frameInfo "WOAF" = urlInfo "Official audio file webpage"++-- WOAR+-- The 'Official artist/performer webpage' frame is a URL pointing at+-- the artists official webpage. There may be more than one "WOAR" frame+-- in a tag if the audio contains more than one performer, but not with+-- the same content.+frameInfo "WOAR" = urlInfo "Official artist webpage"++-- WOAS+-- The 'Official audio source webpage' frame is a URL pointing at the+-- official webpage for the source of the audio file, e.g. a movie.+frameInfo "WOAS" = urlInfo "Official audio source webpage"++-- WORS+-- The 'Official Internet radio station homepage' contains a URL+-- pointing at the homepage of the internet radio station.+frameInfo "WORS" = urlInfo "Official Internet radio station homepage"++-- WPAY+-- The 'Payment' frame is a URL pointing at a webpage that will handle+-- the process of paying for this file.+frameInfo "WPAY" = urlInfo "Payment" -- hahaha! LOL!!! :D++-- WPUB+-- The 'Publishers official webpage' frame is a URL pointing at the+-- official webpage for the publisher.+frameInfo "WPUB" = urlInfo "Publishers official webpage"+---- --}++---- {-- 4.3.2. User defined URL link frame++-- This frame is intended for URL [URL] links concerning the audio file+-- in a similar way to the other "W"-frames. The frame body consists+-- of a description of the string, represented as a terminated string,+-- followed by the actual URL. The URL is always encoded with ISO-8859-1+-- [ISO-8859-1]. There may be more than one "WXXX" frame in each tag,+-- but only one with the same description.++ -- <Header for 'User defined URL link frame', ID: "WXXX">+ -- Text encoding $xx+ -- Description <text string according to encoding> $00 (00)+ -- URL <text string>++frameInfo "WXXX" = do+ enc <- encRead+ descr <- parseString+ url <- parseString+ return $ WXXX enc descr url-- (name, info)++---- --} }}}++---- {-- TODO: 4.4. Music CD identifier ++-- This frame is intended for music that comes from a CD, so that the CD+-- can be identified in databases such as the CDDB [CDDB]. The frame+-- consists of a binary dump of the Table Of Contents, TOC, from the CD,+-- which is a header of 4 bytes and then 8 bytes/track on the CD plus 8+-- bytes for the 'lead out', making a maximum of 804 bytes. The offset+-- to the beginning of every track on the CD should be described with a+-- four bytes absolute CD-frame address per track, and not with absolute+-- time. When this frame is used the presence of a valid "TRCK" frame is+-- REQUIRED, even if the CD's only got one track. It is recommended that+-- this frame is always added to tags originating from CDs. There may+-- only be one "MCDI" frame in each tag.++ -- <Header for 'Music CD identifier', ID: "MCDI">+ -- CD TOC <binary data>+---- --}++---- {-- TODO: 4.5. Event timing codes ++-- This frame allows synchronisation with key events in the audio. The+-- header is:++ -- <Header for 'Event timing codes', ID: "ETCO">+ -- Time stamp format $xx++-- Where time stamp format is:++ -- $01 Absolute time, 32 bit sized, using MPEG [MPEG] frames as unit+ -- $02 Absolute time, 32 bit sized, using milliseconds as unit++-- Absolute time means that every stamp contains the time from the+-- beginning of the file.++-- Followed by a list of key events in the following format:++ -- Type of event $xx+ -- Time stamp $xx (xx ...)++-- The 'Time stamp' is set to zero if directly at the beginning of the+-- sound or after the previous event. All events MUST be sorted in+-- chronological order. The type of event is as follows:++ -- $00 padding (has no meaning)+ -- $01 end of initial silence+ -- $02 intro start+ -- $03 main part start+ -- $04 outro start+ -- $05 outro end+ -- $06 verse start+ -- $07 refrain start+ -- $08 interlude start+ -- $09 theme start+ -- $0A variation start+ -- $0B key change+ -- $0C time change+ -- $0D momentary unwanted noise (Snap, Crackle & Pop)+ -- $0E sustained noise+ -- $0F sustained noise end+ -- $10 intro end+ -- $11 main part end+ -- $12 verse end+ -- $13 refrain end+ -- $14 theme end+ -- $15 profanity+ -- $16 profanity end++ -- $17-$DF reserved for future use++ -- $E0-$EF not predefined synch 0-F++ -- $F0-$FC reserved for future use++ -- $FD audio end (start of silence)+ -- $FE audio file ends+ -- $FF one more byte of events follows (all the following bytes with+ -- the value $FF have the same function)++-- Terminating the start events such as "intro start" is OPTIONAL. The+-- 'Not predefined synch's ($E0-EF) are for user events. You might want+-- to synchronise your music to something, like setting off an explosion+-- on-stage, activating a screensaver etc.++-- There may only be one "ETCO" frame in each tag.+---- --}++---- {-- TODO: 4.6. MPEG location lookup table ++-- To increase performance and accuracy of jumps within a MPEG [MPEG]+-- audio file, frames with time codes in different locations in the file+-- might be useful. This ID3v2 frame includes references that the+-- software can use to calculate positions in the file. After the frame+-- header follows a descriptor of how much the 'frame counter' should be+-- increased for every reference. If this value is two then the first+-- reference points out the second frame, the 2nd reference the 4th+-- frame, the 3rd reference the 6th frame etc. In a similar way the+-- 'bytes between reference' and 'milliseconds between reference' points+-- out bytes and milliseconds respectively.++-- Each reference consists of two parts; a certain number of bits, as+-- defined in 'bits for bytes deviation', that describes the difference+-- between what is said in 'bytes between reference' and the reality and+-- a certain number of bits, as defined in 'bits for milliseconds+-- deviation', that describes the difference between what is said in+-- 'milliseconds between reference' and the reality. The number of bits+-- in every reference, i.e. 'bits for bytes deviation'+'bits for+-- milliseconds deviation', must be a multiple of four. There may only+-- be one "MLLT" frame in each tag.++ -- <Header for 'Location lookup table', ID: "MLLT">+ -- MPEG frames between reference $xx xx+ -- Bytes between reference $xx xx xx+ -- Milliseconds between reference $xx xx xx+ -- Bits for bytes deviation $xx+ -- Bits for milliseconds dev. $xx++-- Then for every reference the following data is included;++ -- Deviation in bytes %xxx....+ -- Deviation in milliseconds %xxx....+---- --}++---- {-- TODO: 4.7. Synchronised tempo codes ++-- For a more accurate description of the tempo of a musical piece, this+-- frame might be used. After the header follows one byte describing+-- which time stamp format should be used. Then follows one or more+-- tempo codes. Each tempo code consists of one tempo part and one time+-- part. The tempo is in BPM described with one or two bytes. If the+-- first byte has the value $FF, one more byte follows, which is added+-- to the first giving a range from 2 - 510 BPM, since $00 and $01 is+-- reserved. $00 is used to describe a beat-free time period, which is+-- not the same as a music-free time period. $01 is used to indicate one+-- single beat-stroke followed by a beat-free period.++-- The tempo descriptor is followed by a time stamp. Every time the+-- tempo in the music changes, a tempo descriptor may indicate this for+-- the player. All tempo descriptors MUST be sorted in chronological+-- order. The first beat-stroke in a time-period is at the same time as+-- the beat description occurs. There may only be one "SYTC" frame in+-- each tag.++ -- <Header for 'Synchronised tempo codes', ID: "SYTC">+ -- Time stamp format $xx+ -- Tempo data <binary data>++-- Where time stamp format is:++ -- $01 Absolute time, 32 bit sized, using MPEG [MPEG] frames as unit+ -- $02 Absolute time, 32 bit sized, using milliseconds as unit++-- Absolute time means that every stamp contains the time from the+-- beginning of the file.+---- --}}++---- {-- 4.8. Unsynchronised lyrics/text transcription++-- This frame contains the lyrics of the song or a text transcription of+-- other vocal activities. The head includes an encoding descriptor and+-- a content descriptor. The body consists of the actual text. The+-- 'Content descriptor' is a terminated string. If no descriptor is+-- entered, 'Content descriptor' is $00 (00) only. Newline characters+-- are allowed in the text. There may be more than one 'Unsynchronised+-- lyrics/text transcription' frame in each tag, but only one with the+-- same language and content descriptor.++ -- <Header for 'Unsynchronised lyrics/text transcription', ID: "USLT">+ -- Text encoding $xx+ -- Language $xx xx xx+ -- Content descriptor <text string according to encoding> $00 (00)+ -- Lyrics/text <full text string according to encoding>++frameInfo "USLT" = do+ enc <- encRead+ lang <- parseLanguage+ descr <- parseString+ text <- parseString+ return $ USLT enc lang descr text-- ("Unsynchronised lyrics: "++name, lang:info )++---- --}++---- {-- TODO: 4.9. Synchronised lyrics/text++-- This is another way of incorporating the words, said or sung lyrics,+-- in the audio file as text, this time, however, in sync with the+-- audio. It might also be used to describing events e.g. occurring on a+-- stage or on the screen in sync with the audio. The header includes a+-- content descriptor, represented with as terminated text string. If no+-- descriptor is entered, 'Content descriptor' is $00 (00) only.++ -- <Header for 'Synchronised lyrics/text', ID: "SYLT">+ -- Text encoding $xx+ -- Language $xx xx xx+ -- Time stamp format $xx+ -- Content type $xx+ -- Content descriptor <text string according to encoding> $00 (00)++-- Content type: $00 is other+ -- $01 is lyrics+ -- $02 is text transcription+ -- $03 is movement/part name (e.g. "Adagio")+ -- $04 is events (e.g. "Don Quijote enters the stage")+ -- $05 is chord (e.g. "Bb F Fsus")+ -- $06 is trivia/'pop up' information+ -- $07 is URLs to webpages+ -- $08 is URLs to images++-- Time stamp format:++ -- $01 Absolute time, 32 bit sized, using MPEG [MPEG] frames as unit+ -- $02 Absolute time, 32 bit sized, using milliseconds as unit++-- Absolute time means that every stamp contains the time from the+-- beginning of the file.++-- The text that follows the frame header differs from that of the+-- unsynchronised lyrics/text transcription in one major way. Each+-- syllable (or whatever size of text is considered to be convenient by+-- the encoder) is a null terminated string followed by a time stamp+-- denoting where in the sound file it belongs. Each sync thus has the+-- following structure:++ -- Terminated text to be synced (typically a syllable)+ -- Sync identifier (terminator to above string) $00 (00)+ -- Time stamp $xx (xx ...)++-- The 'time stamp' is set to zero or the whole sync is omitted if+-- located directly at the beginning of the sound. All time stamps+-- should be sorted in chronological order. The sync can be considered+-- as a validator of the subsequent string.++-- Newline characters are allowed in all "SYLT" frames and MUST be used+-- after every entry (name, event etc.) in a frame with the content type+-- $03 - $04.++-- A few considerations regarding whitespace characters: Whitespace+-- separating words should mark the beginning of a new word, thus+-- occurring in front of the first syllable of a new word. This is also+-- valid for new line characters. A syllable followed by a comma should+-- not be broken apart with a sync (both the syllable and the comma+-- should be before the sync).++-- An example: The "USLT" passage++ -- "Strangers in the night" $0A "Exchanging glances"++-- would be "SYLT" encoded as:++ -- "Strang" $00 xx xx "ers" $00 xx xx " in" $00 xx xx " the" $00 xx xx+ -- " night" $00 xx xx 0A "Ex" $00 xx xx "chang" $00 xx xx "ing" $00 xx+ -- xx "glan" $00 xx xx "ces" $00 xx xx++-- There may be more than one "SYLT" frame in each tag, but only one+-- with the same language and content descriptor.+---- --}++---- {-- 4.10. Comments++-- This frame is intended for any kind of full text information that+-- does not fit in any other frame. It consists of a frame header+-- followed by encoding, language and content descriptors and is ended+-- with the actual comment as a text string. Newline characters are+-- allowed in the comment text string. There may be more than one+-- comment frame in each tag, but only one with the same language and+-- content descriptor.++ -- <Header for 'Comment', ID: "COMM">+ -- Text encoding $xx+ -- Language $xx xx xx+ -- Short content descrip. <text string according to encoding> $00 (00)+ -- The actual text <full text string according to encoding>++frameInfo "COMM" = do+ enc <- encRead+ lang <- parseLanguage+ descr <- parseString+ text <- parseString+ many' terminator -- ???!!!!+ return $ COMM enc lang descr text-- ("Comment: "++name, lang:info )++---- --}++---- {-- TODO: 4.11. Relative volume adjustment (2)++-- This is a more subjective frame than the previous ones. It allows the+-- user to say how much he wants to increase/decrease the volume on each+-- channel when the file is played. The purpose is to be able to align+-- all files to a reference volume, so that you don't have to change the+-- volume constantly. This frame may also be used to balance adjust the+-- audio. The volume adjustment is encoded as a fixed point decibel+-- value, 16 bit signed integer representing (adjustment*512), giving+-- +/- 64 dB with a precision of 0.001953125 dB. E.g. +2 dB is stored as+-- $04 00 and -2 dB is $FC 00. There may be more than one "RVA2" frame+-- in each tag, but only one with the same identification string.++ -- <Header for 'Relative volume adjustment (2)', ID: "RVA2">+ -- Identification <text string> $00++-- The 'identification' string is used to identify the situation and/or+-- device where this adjustment should apply. The following is then+-- repeated for every channel++ -- Type of channel $xx+ -- Volume adjustment $xx xx+ -- Bits representing peak $xx+ -- Peak volume $xx (xx ...)+++-- Type of channel: $00 Other+ -- $01 Master volume+ -- $02 Front right+ -- $03 Front left+ -- $04 Back right+ -- $05 Back left+ -- $06 Front centre+ -- $07 Back centre+ -- $08 Subwoofer++-- Bits representing peak can be any number between 0 and 255. 0 means+-- that there is no peak volume field. The peak volume field is always+-- padded to whole bytes, setting the most significant bits to zero.+---- --}++---- {-- TODO: 4.12. Equalisation (2)++-- This is another subjective, alignment frame. It allows the user to+-- predefine an equalisation curve within the audio file. There may be+-- more than one "EQU2" frame in each tag, but only one with the same+-- identification string.++ -- <Header of 'Equalisation (2)', ID: "EQU2">+ -- Interpolation method $xx+ -- Identification <text string> $00++-- The 'interpolation method' describes which method is preferred when+-- an interpolation between the adjustment point that follows. The+-- following methods are currently defined:++ -- $00 Band+ -- No interpolation is made. A jump from one adjustment level to+ -- another occurs in the middle between two adjustment points.+ -- $01 Linear+ -- Interpolation between adjustment points is linear.++-- The 'identification' string is used to identify the situation and/or+-- device where this adjustment should apply. The following is then+-- repeated for every adjustment point++ -- Frequency $xx xx+ -- Volume adjustment $xx xx++-- The frequency is stored in units of 1/2 Hz, giving it a range from 0+-- to 32767 Hz.++-- The volume adjustment is encoded as a fixed point decibel value, 16+-- bit signed integer representing (adjustment*512), giving +/- 64 dB+-- with a precision of 0.001953125 dB. E.g. +2 dB is stored as $04 00+-- and -2 dB is $FC 00.++-- Adjustment points should be ordered by frequency and one frequency+-- should only be described once in the frame.+---- --}++---- {-- TODO: 4.13. Reverb++-- Yet another subjective frame, with which you can adjust echoes of+-- different kinds. Reverb left/right is the delay between every bounce+-- in ms. Reverb bounces left/right is the number of bounces that should+-- be made. $FF equals an infinite number of bounces. Feedback is the+-- amount of volume that should be returned to the next echo bounce. $00+-- is 0%, $FF is 100%. If this value were $7F, there would be 50% volume+-- reduction on the first bounce, 50% of that on the second and so on.+-- Left to left means the sound from the left bounce to be played in the+-- left speaker, while left to right means sound from the left bounce to+-- be played in the right speaker.++-- 'Premix left to right' is the amount of left sound to be mixed in the+-- right before any reverb is applied, where $00 id 0% and $FF is 100%.+-- 'Premix right to left' does the same thing, but right to left.+-- Setting both premix to $FF would result in a mono output (if the+-- reverb is applied symmetric). There may only be one "RVRB" frame in+-- each tag.++ -- <Header for 'Reverb', ID: "RVRB">+ -- Reverb left (ms) $xx xx+ -- Reverb right (ms) $xx xx+ -- Reverb bounces, left $xx+ -- Reverb bounces, right $xx+ -- Reverb feedback, left to left $xx+ -- Reverb feedback, left to right $xx+ -- Reverb feedback, right to right $xx+ -- Reverb feedback, right to left $xx+ -- Premix left to right $xx+ -- Premix right to left $xx+---- --}++---- {-- 4.14. Attached picture++-- This frame contains a picture directly related to the audio file.+-- Image format is the MIME type and subtype [MIME] for the image. In+-- the event that the MIME media type name is omitted, "image/" will be+-- implied. The "image/png" [PNG] or "image/jpeg" [JFIF] picture format+-- should be used when interoperability is wanted. Description is a+-- short description of the picture, represented as a terminated+-- text string. There may be several pictures attached to one file, each+-- in their individual "APIC" frame, but only one with the same content+-- descriptor. There may only be one picture with the picture type+-- declared as picture type $01 and $02 respectively. There is the+-- possibility to put only a link to the image file by using the 'MIME+-- type' "-- >" and having a complete URL [URL] instead of picture data.+-- The use of linked files should however be used sparingly since there+-- is the risk of separation of files.++ -- <Header for 'Attached picture', ID: "APIC">+ -- Text encoding $xx+ -- MIME type <text string> $00+ -- Picture type $xx+ -- Description <text string according to encoding> $00 (00)+ -- Picture data <binary data>++frameInfo "APIC" = do+ enc <- encRead+ mime <- parseString+ picType <- anyWord8+ descr <- parseString+ picData <- many' anyWord8+ return $ APIC enc mime picType descr picData -- ("Attached picture", [])++-- Picture type: $00 Other+ -- $01 32x32 pixels 'file icon' (PNG only)+ -- $02 Other file icon+ -- $03 Cover (front)+ -- $04 Cover (back)+ -- $05 Leaflet page+ -- $06 Media (e.g. label side of CD)+ -- $07 Lead artist/lead performer/soloist+ -- $08 Artist/performer+ -- $09 Conductor+ -- $0A Band/Orchestra+ -- $0B Composer+ -- $0C Lyricist/text writer+ -- $0D Recording Location+ -- $0E During recording+ -- $0F During performance+ -- $10 Movie/video screen capture+ -- $11 A bright coloured fish+ -- $12 Illustration+ -- $13 Band/artist logotype+ -- $14 Publisher/Studio logotype+---- --}++---- {-- TODO: 4.15. General encapsulated object++-- In this frame any type of file can be encapsulated. After the header,+-- 'Frame size' and 'Encoding' follows 'MIME type' [MIME] represented as+-- as a terminated string encoded with ISO 8859-1 [ISO-8859-1]. The+-- filename is case sensitive and is encoded as 'Encoding'. Then follows+-- a content description as terminated string, encoded as 'Encoding'.+-- The last thing in the frame is the actual object. The first two+-- strings may be omitted, leaving only their terminations. MIME type is+-- always an ISO-8859-1 text string. There may be more than one "GEOB"+-- frame in each tag, but only one with the same content descriptor.++ -- <Header for 'General encapsulated object', ID: "GEOB">+ -- Text encoding $xx+ -- MIME type <text string> $00+ -- Filename <text string according to encoding> $00 (00)+ -- Content description <text string according to encoding> $00 (00)+ -- Encapsulated object <binary data>+---- --}++---- {-- 4.16. Play counter++-- This is simply a counter of the number of times a file has been+-- played. The value is increased by one every time the file begins to+-- play. There may only be one "PCNT" frame in each tag. When the+-- counter reaches all one's, one byte is inserted in front of the+-- counter thus making the counter eight bits bigger. The counter must+-- be at least 32-bits long to begin with.++ -- <Header for 'Play counter', ID: "PCNT">+ -- Counter $xx xx xx xx (xx ...)++frameInfo "PCNT" = do+ cnt <- many' anyWord8+ return $ PCNT (wordsToInteger cnt)-- ("Play counter", [("Counter", pack counter)])++---- --}++---- {-- 4.17. Popularimeter++-- The purpose of this frame is to specify how good an audio file is.+-- Many interesting applications could be found to this frame such as a+-- playlist that features better audio files more often than others or+-- it could be used to profile a person's taste and find other 'good'+-- files by comparing people's profiles. The frame contains the email+-- address to the user, one rating byte and a four byte play counter,+-- intended to be increased with one for every time the file is played.+-- The email is a terminated string. The rating is 1-255 where 1 is+-- worst and 255 is best. 0 is unknown. If no personal counter is wanted+-- it may be omitted. When the counter reaches all one's, one byte is+-- inserted in front of the counter thus making the counter eight bits+-- bigger in the same away as the play counter ("PCNT"). There may be+-- more than one "POPM" frame in each tag, but only one with the same+-- email address.++ -- <Header for 'Popularimeter', ID: "POPM">+ -- Email to user <text string> $00+ -- Rating $xx+ -- Counter $xx xx xx xx (xx ...)++frameInfo "POPM" = do+ encSet 0x00+ mail <- parseString+ rate <- anyWord8+ cnt <- many' anyWord8+ return $ POPM mail (toInteger rate) (wordsToInteger cnt)-- ("Popularimeter: "++email, [("Rating", pack [rating]), ("Counter", pack counter)])++---- --}++---- {-- TODO: 4.18. Recommended buffer size++-- Sometimes the server from which an audio file is streamed is aware of+-- transmission or coding problems resulting in interruptions in the+-- audio stream. In these cases, the size of the buffer can be+-- recommended by the server using this frame. If the 'embedded info+-- flag' is true (1) then this indicates that an ID3 tag with the+-- maximum size described in 'Buffer size' may occur in the audio+-- stream. In such case the tag should reside between two MPEG [MPEG]+-- frames, if the audio is MPEG encoded. If the position of the next tag+-- is known, 'offset to next tag' may be used. The offset is calculated+-- from the end of tag in which this frame resides to the first byte of+-- the header in the next. This field may be omitted. Embedded tags are+-- generally not recommended since this could render unpredictable+-- behaviour from present software/hardware.++-- For applications like streaming audio it might be an idea to embed+-- tags into the audio stream though. If the clients connects to+-- individual connections like HTTP and there is a possibility to begin+-- every transmission with a tag, then this tag should include a+-- 'recommended buffer size' frame. If the client is connected to a+-- arbitrary point in the stream, such as radio or multicast, then the+-- 'recommended buffer size' frame SHOULD be included in every tag.++-- The 'Buffer size' should be kept to a minimum. There may only be one+-- "RBUF" frame in each tag.++ -- <Header for 'Recommended buffer size', ID: "RBUF">+ -- Buffer size $xx xx xx+ -- Embedded info flag %0000000x+ -- Offset to next tag $xx xx xx xx+---- --}++---- {-- TODO: 4.19. Audio encryption++-- This frame indicates if the actual audio stream is encrypted, and by+-- whom. Since standardisation of such encryption scheme is beyond this+-- document, all "AENC" frames begin with a terminated string with a+-- URL containing an email address, or a link to a location where an+-- email address can be found, that belongs to the organisation+-- responsible for this specific encrypted audio file. Questions+-- regarding the encrypted audio should be sent to the email address+-- specified. If a $00 is found directly after the 'Frame size' and the+-- audio file indeed is encrypted, the whole file may be considered+-- useless.++-- After the 'Owner identifier', a pointer to an unencrypted part of the+-- audio can be specified. The 'Preview start' and 'Preview length' is+-- described in frames. If no part is unencrypted, these fields should+-- be left zeroed. After the 'preview length' field follows optionally a+-- data block required for decryption of the audio. There may be more+-- than one "AENC" frames in a tag, but only one with the same 'Owner+-- identifier'.++ -- <Header for 'Audio encryption', ID: "AENC">+ -- Owner identifier <text string> $00+ -- Preview start $xx xx+ -- Preview length $xx xx+ -- Encryption info <binary data>+---- --}++---- {-- TODO: 4.20. Linked information++-- To keep information duplication as low as possible this frame may be+-- used to link information from another ID3v2 tag that might reside in+-- another audio file or alone in a binary file. It is RECOMMENDED that+-- this method is only used when the files are stored on a CD-ROM or+-- other circumstances when the risk of file separation is low. The+-- frame contains a frame identifier, which is the frame that should be+-- linked into this tag, a URL [URL] field, where a reference to the+-- file where the frame is given, and additional ID data, if needed.+-- Data should be retrieved from the first tag found in the file to+-- which this link points. There may be more than one "LINK" frame in a+-- tag, but only one with the same contents. A linked frame is to be+-- considered as part of the tag and has the same restrictions as if it+-- was a physical part of the tag (i.e. only one "RVRB" frame allowed,+-- whether it's linked or not).++ -- <Header for 'Linked information', ID: "LINK">+ -- Frame identifier $xx xx xx xx+ -- URL <text string> $00+ -- ID and additional data <text string(s)>++-- Frames that may be linked and need no additional data are "ASPI",+-- "ETCO", "EQU2", "MCID", "MLLT", "OWNE", "RVA2", "RVRB", "SYTC", the+-- text information frames and the URL link frames.++-- The "AENC", "APIC", "GEOB" and "TXXX" frames may be linked with+-- the content descriptor as additional ID data.++-- The "USER" frame may be linked with the language field as additional+-- ID data.++-- The "PRIV" frame may be linked with the owner identifier as+-- additional ID data.++-- The "COMM", "SYLT" and "USLT" frames may be linked with three bytes+-- of language descriptor directly followed by a content descriptor as+-- additional ID data.+---- --}++---- {-- TODO: 4.21. Position synchronisation frame++-- This frame delivers information to the listener of how far into the+-- audio stream he picked up; in effect, it states the time offset from+-- the first frame in the stream. The frame layout is:++ -- <Head for 'Position synchronisation', ID: "POSS">+ -- Time stamp format $xx+ -- Position $xx (xx ...)++-- Where time stamp format is:++ -- $01 Absolute time, 32 bit sized, using MPEG frames as unit+ -- $02 Absolute time, 32 bit sized, using milliseconds as unit++-- and position is where in the audio the listener starts to receive,+-- i.e. the beginning of the next frame. If this frame is used in the+-- beginning of a file the value is always 0. There may only be one+-- "POSS" frame in each tag.+---- --}++---- {-- TODO: 4.22. Terms of use frame++-- This frame contains a brief description of the terms of use and+-- ownership of the file. More detailed information concerning the legal+-- terms might be available through the "WCOP" frame. Newlines are+-- allowed in the text. There may be more than one 'Terms of use' frame+-- in a tag, but only one with the same 'Language'.++ -- <Header for 'Terms of use frame', ID: "USER">+ -- Text encoding $xx+ -- Language $xx xx xx+ -- The actual text <text string according to encoding>+---- --}++---- {-- TODO: 4.23. Ownership frame++-- The ownership frame might be used as a reminder of a made transaction+-- or, if signed, as proof. Note that the "USER" and "TOWN" frames are+-- good to use in conjunction with this one. The frame begins, after the+-- frame ID, size and encoding fields, with a 'price paid' field. The+-- first three characters of this field contains the currency used for+-- the transaction, encoded according to ISO 4217 [ISO-4217] alphabetic+-- currency code. Concatenated to this is the actual price paid, as a+-- numerical string using "." as the decimal separator. Next is an 8+-- character date string (YYYYMMDD) followed by a string with the name+-- of the seller as the last field in the frame. There may only be one+-- "OWNE" frame in a tag.++ -- <Header for 'Ownership frame', ID: "OWNE">+ -- Text encoding $xx+ -- Price paid <text string> $00+ -- Date of purch. <text string>+ -- Seller <text string according to encoding>+---- --}++---- {-- TODO: 4.24. Commercial frame++-- This frame enables several competing offers in the same tag by+-- bundling all needed information. That makes this frame rather complex+-- but it's an easier solution than if one tries to achieve the same+-- result with several frames. The frame begins, after the frame ID,+-- size and encoding fields, with a price string field. A price is+-- constructed by one three character currency code, encoded according+-- to ISO 4217 [ISO-4217] alphabetic currency code, followed by a+-- numerical value where "." is used as decimal separator. In the price+-- string several prices may be concatenated, separated by a "/"+-- character, but there may only be one currency of each type.++-- The price string is followed by an 8 character date string in the+-- format YYYYMMDD, describing for how long the price is valid. After+-- that is a contact URL, with which the user can contact the seller,+-- followed by a one byte 'received as' field. It describes how the+-- audio is delivered when bought according to the following list:++ -- $00 Other+ -- $01 Standard CD album with other songs+ -- $02 Compressed audio on CD+ -- $03 File over the Internet+ -- $04 Stream over the Internet+ -- $05 As note sheets+ -- $06 As note sheets in a book with other sheets+ -- $07 Music on other media+ -- $08 Non-musical merchandise++-- Next follows a terminated string with the name of the seller followed+-- by a terminated string with a short description of the product. The+-- last thing is the ability to include a company logotype. The first of+-- them is the 'Picture MIME type' field containing information about+-- which picture format is used. In the event that the MIME media type+-- name is omitted, "image/" will be implied. Currently only "image/png"+-- and "image/jpeg" are allowed. This format string is followed by the+-- binary picture data. This two last fields may be omitted if no+-- picture is attached. There may be more than one 'commercial frame' in+-- a tag, but no two may be identical.++ -- <Header for 'Commercial frame', ID: "COMR">+ -- Text encoding $xx+ -- Price string <text string> $00+ -- Valid until <text string>+ -- Contact URL <text string> $00+ -- Received as $xx+ -- Name of seller <text string according to encoding> $00 (00)+ -- Description <text string according to encoding> $00 (00)+ -- Picture MIME type <string> $00+ -- Seller logo <binary data>+---- --}++---- {-- TODO: 4.25. Encryption method registration++-- To identify with which method a frame has been encrypted the+-- encryption method must be registered in the tag with this frame. The+-- 'Owner identifier' is a null-terminated string with a URL [URL]+-- containing an email address, or a link to a location where an email+-- address can be found, that belongs to the organisation responsible+-- for this specific encryption method. Questions regarding the+-- encryption method should be sent to the indicated email address. The+-- 'Method symbol' contains a value that is associated with this method+-- throughout the whole tag, in the range $80-F0. All other values are+-- reserved. The 'Method symbol' may optionally be followed by+-- encryption specific data. There may be several "ENCR" frames in a tag+-- but only one containing the same symbol and only one containing the+-- same owner identifier. The method must be used somewhere in the tag.+-- See the description of the frame encryption flag in the ID3v2+-- structure document [ID3v2-strct] for more information.++ -- <Header for 'Encryption method registration', ID: "ENCR">+ -- Owner identifier <text string> $00+ -- Method symbol $xx+ -- Encryption data <binary data>+---- --}++---- {-- TODO: 4.26. Group identification registration++-- This frame enables grouping of otherwise unrelated frames. This can+-- be used when some frames are to be signed. To identify which frames+-- belongs to a set of frames a group identifier must be registered in+-- the tag with this frame. The 'Owner identifier' is a null-terminated+-- string with a URL [URL] containing an email address, or a link to a+-- location where an email address can be found, that belongs to the+-- organisation responsible for this grouping. Questions regarding the+-- grouping should be sent to the indicated email address. The 'Group+-- symbol' contains a value that associates the frame with this group+-- throughout the whole tag, in the range $80-F0. All other values are+-- reserved. The 'Group symbol' may optionally be followed by some group+-- specific data, e.g. a digital signature. There may be several "GRID"+-- frames in a tag but only one containing the same symbol and only one+-- containing the same owner identifier. The group symbol must be used+-- somewhere in the tag. See the description of the frame grouping flag+-- in the ID3v2 structure document [ID3v2-strct] for more information.++ -- <Header for 'Group ID registration', ID: "GRID">+ -- Owner identifier <text string> $00+ -- Group symbol $xx+ -- Group dependent data <binary data>+---- --}++---- {-- TODO: 4.27. Private frame++-- This frame is used to contain information from a software producer+-- that its program uses and does not fit into the other frames. The+-- frame consists of an 'Owner identifier' string and the binary data.+-- The 'Owner identifier' is a null-terminated string with a URL [URL]+-- containing an email address, or a link to a location where an email+-- address can be found, that belongs to the organisation responsible+-- for the frame. Questions regarding the frame should be sent to the+-- indicated email address. The tag may contain more than one "PRIV"+-- frame but only with different contents.++ -- <Header for 'Private frame', ID: "PRIV">+ -- Owner identifier <text string> $00+ -- The private data <binary data>+---- --}++---- {-- TODO: 4.28. Signature frame++-- This frame enables a group of frames, grouped with the 'Group+-- identification registration', to be signed. Although signatures can+-- reside inside the registration frame, it might be desired to store+-- the signature elsewhere, e.g. in watermarks. There may be more than+-- one 'signature frame' in a tag, but no two may be identical.++ -- <Header for 'Signature frame', ID: "SIGN">+ -- Group symbol $xx+ -- Signature <binary data>+---- --}++---- {-- TODO: 4.29. Seek frame++-- This frame indicates where other tags in a file/stream can be found.+-- The 'minimum offset to next tag' is calculated from the end of this+-- tag to the beginning of the next. There may only be one 'seek frame'+-- in a tag.++-- <Header for 'Seek frame', ID: "SEEK">+-- Minimum offset to next tag $xx xx xx xx+---- --}++---- {-- TODO: 4.30. Audio seek point index++-- Audio files with variable bit rates are intrinsically difficult to+-- deal with in the case of seeking within the file. The ASPI frame+-- makes seeking easier by providing a list a seek points within the+-- audio file. The seek points are a fractional offset within the audio+-- data, providing a starting point from which to find an appropriate+-- point to start decoding. The presence of an ASPI frame requires the+-- existence of a TLEN frame, indicating the duration of the file in+-- milliseconds. There may only be one 'audio seek point index' frame in+-- a tag.++ -- <Header for 'Seek Point Index', ID: "ASPI">+ -- Indexed data start (S) $xx xx xx xx+ -- Indexed data length (L) $xx xx xx xx+ -- Number of index points (N) $xx xx+ -- Bits per index point (b) $xx++-- Then for every index point the following data is included;++ -- Fraction at index (Fi) $xx (xx)++-- 'Indexed data start' is a byte offset from the beginning of the file.+-- 'Indexed data length' is the byte length of the audio data being+-- indexed. 'Number of index points' is the number of index points, as+-- the name implies. The recommended number is 100. 'Bits per index+-- point' is 8 or 16, depending on the chosen precision. 8 bits works+-- well for short files (less than 5 minutes of audio), while 16 bits is+-- advantageous for long files. 'Fraction at index' is the numerator of+-- the fraction representing a relative position in the data. The+-- denominator is 2 to the power of b.++-- Here are the algorithms to be used in the calculation. The known data+-- must be the offset of the start of the indexed data (S), the offset+-- of the end of the indexed data (E), the number of index points (N),+-- the offset at index i (Oi). We calculate the fraction at index i+-- (Fi).++-- Oi is the offset of the frame whose start is soonest after the point+-- for which the time offset is (i/N * duration).++-- The frame data should be calculated as follows:++ -- Fi = Oi/L * 2^b (rounded down to the nearest integer)++-- Offset calculation should be calculated as follows from data in the+-- frame:++ -- Oi = (Fi/2^b)*L (rounded up to the nearest integer)+---- --}++frameInfo _ = do+ cont <- parseString+ return $ Unknown cont
+ src/ID3/Parser/Tag.hs view
@@ -0,0 +1,35 @@+module ID3.Parser.Tag+ (+ -- * Tag type+ ID3Tag(..)+ -- * Tag parser+ , run+ , parseTag+ , parseTag_+ )+where++{-- IMPORTS -}+import Data.Accessor++import ID3.Parser.Header+import ID3.Parser.ExtHeader+import ID3.Parser.Frame+import ID3.Parser.General++import ID3.Type+-- --}++parseTag :: TagParser ID3Tag+parseTag = do+ h <- parseHeader `err` "header"+ parseTag_ h++parseTag_ :: ID3Header -> TagParser ID3Tag+parseTag_ h = do+ ext <- if (h^.tagFlags^.extended)+ then parseExtHeader >>= return . Just+ else return Nothing `err` "ext header"+ (idList, fs) <- parseFrames `err` "frames"+ if (h^.tagFlags^.footed) then parseFooter else return h `err` "footer"+ return $ initID3Tag [header^=h, extHeader^=ext, frames^=fs, framesOrder^=idList, padding^=(h^.tagSize) - (framesSize fs)]
+ src/ID3/Parser/UnSync.hs view
@@ -0,0 +1,137 @@+{- | UNSYNCHRONISATION++ This module contents a couple of functions to convert readed bytes (as ['Word8']) of synchronized values to unsynchronised 'Integer'.+++ /UNSYNCRONISATION/+++ The only purpose of unsynchronisation is to make the ID3v2 tag as+ compatible as possible with existing software and hardware. There is+ no use in 'unsynchronising' tags if the file is only to be processed+ only by ID3v2 aware software and hardware. Unsynchronisation is only+ useful with tags in MPEG 1/2 layer I, II and III, MPEG 2.5 and AAC+ files.++ 1. /The unsynchronisation scheme/++ Whenever a false synchronisation is found within the tag, one zeroed+ byte is inserted after the first false synchronisation byte. The+ format of synchronisations that should be altered by ID3 syncIntegerrs is+ as follows:++@+ %11111111 111xxxxx+@++ and should be replaced with:++@+ %11111111 00000000 111xxxxx+@++ This has the side effect that all $FF 00 combinations have to be+ altered, so they will not be affected by the decoding process.+ Therefore all the $FF 00 combinations have to be replaced with the+ $FF 00 00 combination during the unsynchronisation.++ To indicate usage of the unsynchronisation, the unsynchronisation+ flag in the frame header should be set. This bit MUST be set if the+ frame was altered by the unsynchronisation and SHOULD NOT be set if+ unaltered. If all frames in the tag are unsynchronised the+ unsynchronisation flag in the tag header SHOULD be set. It MUST NOT+ be set if the tag has a frame which is not unsynchronised.++ Assume the first byte of the audio to be $FF. The special case when+ the last byte of the last frame is $FF and no padding nor footer is+ used will then introduce a false synchronisation. This can be solved+ by adding a footer, adding padding or unsynchronising the frame and+ add $00 to the end of the frame data, thus adding more byte to the+ frame size than a normal unsynchronisation would. Although not+ preferred, it is allowed to apply the last method on all frames+ ending with $FF.++ It is preferred that the tag is either completely unsynchronised or+ not unsynchronised at all. A completely unsynchronised tag has no+ false synchonisations in it, as defined above, and does not end with+ $FF. A completely non-unsynchronised tag contains no unsynchronised+ frames, and thus the unsynchronisation flag in the header is cleared.++ Do bear in mind, that if compression or encryption is used, the+ unsynchronisation scheme MUST be applied afterwards. When decoding an+ unsynchronised frame, the unsynchronisation scheme MUST be reversed+ first, encryption and decompression afterwards.++ 2. /Synchsafe integers/++ In some parts of the tag it is inconvenient to use the+ unsychronisation scheme because the size of unsynchronised data is+ not known in advance, which is particularly problematic with size+ descriptors. The solution in ID3v2 is to use synchsafe integers, in+ which there can never be any false synchs. Synchsafe integers are+ integers that keep its highest bit (bit 7) zeroed, making seven bits+ out of eight available. Thus a 32 bit synchsafe integer can store 28+ bits of information.++ Example:++@+ 255 (%11111111) syncIntegerd as a 16 bit synchsafe integer is 383+ (%00000001 01111111).+@+++(<http://www.id3.org/id3v2.4.0-structure>)+-}++module ID3.Parser.UnSync+ (+ wordsToInteger+ , unSyncInteger+ , unSynchronise+ , integerToWords+ , syncInteger+ , synchronise+ )+where++import Data.Bits+import Data.Word (Word8)++-- | converting list of bytes to 'Integer' value+wordsToInteger :: [Word8] -> Integer+wordsToInteger = sum . (zipWith (*) (iterate (*16^2) 1)) . reverse . map toInteger++-- | unsynchronisation between 'Integer's+unSyncInteger :: Integer -> Integer+unSyncInteger n = (n .&. 0x7f)+ .|.(n .&. 0x7f00) `shiftR` 1+ .|.(n .&. 0x7f0000) `shiftR` 2+ .|.(n .&. 0x7f000000) `shiftR` 3++-- | unsychronisation (just @unSyncInteger . wordsToInteger@)+unSynchronise :: [Word8] -> Integer+unSynchronise = unSyncInteger . wordsToInteger++---------------------------------------------------------------------------------------++-- | converting 'Integer' value to list of bytes+integerToWords :: Int -> Integer -> [Word8]+integerToWords n x = map (fromInteger . getByte x) $ reverse [0..(n-1)]+ where+ byte n = 2^(8*n) * (2^8 - 1)+ x `getByte` n = (x .&. (byte n)) `shiftR` (8*n)+++-- | synchronisation between 'Integer's+syncInteger :: Integer -> Integer+syncInteger n = (n .&. 0x7f)+ .|.(n .&. 0x3f80) `shiftL` 1+ .|.(n .&. 0x1fc000) `shiftL` 2+ .|.(n .&. 0xfe00000) `shiftL` 3++{-prop x = x == (wordsToInteger $ integerToWords 4 x)-}++-- | sychronisation (just @integerToWords 4 . syncInteger@)+synchronise :: Integer -> [Word8]+synchronise = integerToWords 4 . syncInteger
+ src/ID3/ReadTag.hs view
@@ -0,0 +1,26 @@+module ID3.ReadTag+( hReadTag+, readTag+) where++import Data.Accessor+import ID3.Parser.Tag+import ID3.Parser.Header+import ID3.Type.Header+import System.IO+import System.IO.Binary++hReadTag :: Handle -> IO (Maybe ID3Tag)+hReadTag hdl = do+ hSeek hdl AbsoluteSeek 0+ beginning <- hGetBufStr hdl 10+ case run parseHeader beginning of+ (Left _ , _) -> return Nothing+ (Right header, _) -> do+ chunk <- hGetBufStr hdl $ fromInteger (header^.tagSize)+ case run (parseTag_ header) chunk of+ (Left _ , _) -> return Nothing+ (Right tag, _) -> return (Just tag)++readTag :: FilePath -> IO (Maybe ID3Tag)+readTag file = withBinaryFile file ReadWriteMode hReadTag
+ src/ID3/Simple.hs view
@@ -0,0 +1,83 @@+module ID3.Simple+( Tag++, setArtist+, setTitle+, setAlbum+, setYear+, setTrack++, getArtist+, getTitle+, getAlbum+, getYear+, getTrack++, readTag+, writeTag++) where++import Data.Accessor+import Data.Maybe+import ID3.Type+import ID3.ReadTag+import ID3.WriteTag++type Tag = ID3Tag++getFrameText :: FrameID -> Tag -> Maybe String+getFrameText id tag = case tag^.frame id of+ Nothing -> Nothing+ Just fr -> Just (fr^.textContent)++setFrameText :: FrameID -> String -> Tag -> Tag+setFrameText id x tag = edit $ fromMaybe (initFrame id) (tag^.frame id)+ where edit f = (frame id) ^= Just (updateSize $ textContent^=x $ f ) $ tag++-----------------------------------++getArtist :: Tag -> Maybe String+getArtist = getFrameText "TPE1"++setArtist :: String -> Tag -> Tag+setArtist = setFrameText "TPE1"++--artist = accessor getArtist setArtist+-----------------------------------++getTitle :: Tag -> Maybe String+getTitle = getFrameText "TIT2"++setTitle :: String -> Tag -> Tag+setTitle = setFrameText "TIT2"+-----------------------------------++getAlbum :: Tag -> Maybe String+getAlbum = getFrameText "TALB"++setAlbum :: String -> Tag -> Tag+setAlbum = setFrameText "TALB"+-----------------------------------++getYear :: Tag -> Maybe String+getYear = getFrameText "TDRC"++setYear :: String -> Tag -> Tag+setYear = setFrameText "TDRC"+-----------------------------------++getTrack :: Tag -> Maybe String+getTrack = getFrameText "TRCK"++setTrack :: String -> Tag -> Tag+setTrack = setFrameText "TRCK"+-----------------------------------+{-+get:: Tag -> Maybe String+get= getFrameText ""++set:: String -> Tag -> Tag+set= setFrameText ""+-----------------------------------+-}
+ src/ID3/Type.hs view
@@ -0,0 +1,19 @@+module ID3.Type+(+ module ID3.Type.Tag+, module ID3.Type.Header+, module ID3.Type.ExtHeader+, module ID3.Type.Frame+, module ID3.Type.FrameInfo+, module ID3.Type.Flags+, module ID3.Type.Unparse+)+where++import ID3.Type.Tag+import ID3.Type.Header+import ID3.Type.ExtHeader+import ID3.Type.Frame+import ID3.Type.FrameInfo+import ID3.Type.Flags+import ID3.Type.Unparse
+ src/ID3/Type/ExtHeader.hs view
@@ -0,0 +1,205 @@+module ID3.Type.ExtHeader+ (+ -- * ID3 Extended Header+ -- ** Types+ ID3ExtHeader+ , emptyID3ExtHeader+ , initID3ExtHeader+ , ExtFlags+ , emptyExtFlags+ , initExtFlags+ -- ** Accessors+ , extSize+ , extFlags+ , isUpdate+ , crc+ , restrictions+ )+where++import Data.Accessor+import Data.Accessor.Basic (compose)+import ID3.Type.Flags+import ID3.Type.Unparse++import Data.Word (Word8)++{- | /EXTENDED HEADER OVERVIEW/ (optional)++ The extended header contains information that can provide further+ insight in the structure of the tag, but is not vital to the correct+ parsing of the tag information; hence the extended header is+ optional.++@+ Extended header size 4 * %0xxxxxxx+ Number of flag bytes $01+ Extended Flags $xx+@++ Where the 'Extended header size' is the size of the whole extended+ header, stored as a 32 bit synchsafe integer. An extended header can+ thus never have a size of fewer than six bytes.+-}+data ID3ExtHeader = ID3ExtHeader+ { extSize_ :: Integer -- ^ size of extended header+ , extFlags_ :: ExtFlags -- ^ flags+ } deriving Eq++-- | Forming empty value to return, if there is no Extended Header+emptyID3ExtHeader = ID3ExtHeader 0 emptyExtFlags+initID3ExtHeader = flip compose emptyID3ExtHeader++extSize = accessor extSize_ (\x e -> e {extSize_ = x})+extFlags = accessor extFlags_ (\x e -> e {extFlags_ = x})++instance Show ID3ExtHeader where+ show eh = if (eh^.extSize)==0 then "" else+ "Extended Header:\n"+++ "Size: "++(show $ eh^.extSize)++" bytes\n"+++ (show $ eh^.extFlags)++instance Parsed ID3ExtHeader where+ unparse eh = (unparse $ eh^.extSize) +++ [0x01] +++ (unparse $ initFlags [ (accessFlag 2)^=(eh^.extFlags^.isUpdate )+ , (accessFlag 3)^=(eh^.extFlags^.crc == [])+ , (accessFlag 4)^=(eh^.extFlags^.restrictions == [])+ ]) +++ (unparse $ eh^.extFlags)++{- | /Extended Header Flags Meaning/++ The extended flags field, with its size described by 'number of flag+ bytes', is defined as:++@+ %0bcd0000+@++ Each flag that is set in the extended header has data attached, which+ comes in the order in which the flags are encountered (i.e. the data+ for flag 'b' comes before the data for flag 'c'). Unset flags cannot+ have any attached data. All unknown flags MUST be unset and their+ corresponding data removed when a tag is modified.++ Every set flag's data starts with a length byte, which contains a+ value between 0 and 128 ($00 - $7f), followed by data that has the+ field length indicated by the length byte. If a flag has no attached+ data, the value $00 is used as length byte.+++ b - Tag is an update++ If this flag is set, the present tag is an update of a tag found+ earlier in the present file or stream. If frames defined as unique+ are found in the present tag, they are to override any+ corresponding ones found in the earlier tag. This flag has no+ corresponding data.++@+ Flag data length $00+@+++ c - CRC data present++ If this flag is set, a CRC-32 [ISO-3309] data is included in the+ extended header. The CRC is calculated on all the data between the+ header and footer as indicated by the header's tag length field,+ minus the extended header. Note that this includes the padding (if+ there is any), but excludes the footer. The CRC-32 is stored as an+ 35 bit synchsafe integer, leaving the upper four bits always+ zeroed.++@+ Flag data length $05+ Total frame CRC 5 * %0xxxxxxx+@+++ d - Tag restrictions++ For some applications it might be desired to restrict a tag in more+ ways than imposed by the ID3v2 specification. Note that the+ presence of these restrictions does not affect how the tag is+ decoded, merely how it was restricted before encoding. If this flag+ is set the tag is restricted as follows:++@+ Flag data length $01+ Restrictions %ppqrrstt+@+++ p - Tag size restrictions++@+ 00 No more than 128 frames and 1 MB total tag size.+ 01 No more than 64 frames and 128 KB total tag size.+ 10 No more than 32 frames and 40 KB total tag size.+ 11 No more than 32 frames and 4 KB total tag size.+@++ q - Text encoding restrictions++@+ 0 No restrictions+ 1 Strings are only encoded with ISO-8859-1 [ISO-8859-1] or+ UTF-8 [UTF-8].+@++ r - Text fields size restrictions++@+ 00 No restrictions+ 01 No string is longer than 1024 characters.+ 10 No string is longer than 128 characters.+ 11 No string is longer than 30 characters.+@++ Note that nothing is said about how many bytes is used to+ represent those characters, since it is encoding dependent. If a+ text frame consists of more than one string, the sum of the+ strungs is restricted as stated.++ s - Image encoding restrictions++@+ 0 No restrictions+ 1 Images are encoded only with PNG [PNG] or JPEG [JFIF].+@++ t - Image size restrictions++@+ 00 No restrictions+ 01 All images are 256x256 pixels or smaller.+ 10 All images are 64x64 pixels or smaller.+ 11 All images are exactly 64x64 pixels, unless required+ otherwise.+@+-}+data ExtFlags = ExtFlags+ { extIsUpdate :: Bool -- ^ True if tag is an update+ , extCrc :: [Word8] -- ^ CRC data present+ , extRestrictions :: [Bool] -- ^ Tag restrictions+ } deriving Eq++emptyExtFlags = ExtFlags False [] []+initExtFlags = flip compose emptyExtFlags++isUpdate = accessor extIsUpdate (\x ef -> ef { extIsUpdate = x})+crc = accessor extCrc (\x ef -> ef { extCrc = x})+restrictions = accessor extRestrictions (\x ef -> ef { extRestrictions = x})++instance Show ExtFlags where+ show ef = "Extended Flags:\n"+++ (if ef^.isUpdate then "\t- This tag is an update\n" else "")+++ (if ef^.crc /= [] then "\t- There is some CRC data...\n" else "")+++ (if ef^.restrictions /= [] then "\t- There are some restrictions...\n" else "")++instance Parsed ExtFlags where+ unparse ef = (if ef^.isUpdate then [0x00] else []) +++ (if ef^.crc /= [] then [0x05]++(ef^.crc) else []) +++ (if ef^.restrictions /= [] then [0x01]++(unparse $ Flags $ ef^.restrictions) else [])
+ src/ID3/Type/Flags.hs view
@@ -0,0 +1,30 @@+module ID3.Type.Flags+where++import Data.Accessor+import Data.Accessor.Basic (compose)+import Data.Bits+import Data.Word (Word8)+import ID3.Type.Unparse++data Flags = Flags [Bool] deriving Eq++emptyFlags :: Flags+emptyFlags = Flags $ replicate 8 False++initFlags = flip compose emptyFlags++-- It works as 'initFlags', but changes only specified values+mkFlags ns fs = initFlags $ zipWith access ns fs+ where access n f = (accessFlag n) ^= f++allFlags :: Accessor Flags [Bool]+allFlags = accessor (\(Flags fs) -> fs) (\x _ -> Flags x)++accessFlag :: Int -> Accessor Flags Bool+accessFlag n = accessor (\(Flags fs) -> fs!!(n-1)) (\x (Flags fs) -> Flags $ (take (n-1) fs)++[x]++(drop n fs))++instance Parsed Flags where+ unparse fs = [foldr fromBool 0 (zip [0..] (fs^.allFlags))]+ where fromBool (i, True) = flip setBit i+ fromBool (i, False) = flip clearBit i
+ src/ID3/Type/Frame.hs view
@@ -0,0 +1,323 @@+module ID3.Type.Frame where++import Data.Accessor+import Data.Accessor.Basic (compose)+import ID3.Type.Flags+import ID3.Type.Unparse+import ID3.Type.FrameInfo+import ID3.Parser.NativeFrames++{-- | /ID3V2 FRAME OVERVIEW/++ All ID3v2 frames consists of one frame header followed by one or more+ fields containing the actual information. The header is always 10+ bytes and laid out as follows:++@+ Frame ID $xx xx xx xx (four characters)+ Size 4 * %0xxxxxxx+ Flags $xx xx+@+--}+++data ID3Frame = ID3Frame+ { frHeader_ :: FrameHeader -- ^ frame Header+ , frInfo_ :: FrameInfo -- ^ frame Information Value+ } deriving Eq++emptyID3Frame = ID3Frame emptyFrameHeader (Unknown "")+initID3Frame = flip compose emptyID3Frame++frHeader = accessor frHeader_ (\x fr -> fr {frHeader_ = x})+frInfo = accessor frInfo_ (\x fr -> fr {frInfo_ = x})++instance HasSize ID3Frame where+ size = accessor (toInteger . length . unparse . getVal frInfo) (setVal $ frHeader .> frSize)++--content :: (FrameInfo -> a) -> Accessor ID3Frame a+--content a = accessor (\f -> a (f^.frInfo)) (\x f -> frInfo^=((f^.frInfo) {a=x}) $ f)+textContent = frInfo .> infoTextContent++instance Show ID3Frame where+ show fr = (show $ fr^.frHeader) ++"\n"+++ (show $ fr^.frInfo )++"\n"++{-showFrameInfo info = concatMap showRec info+ where showRec (s, bs) = "\t"++s++":\t"++bs++"\n"-}++instance Parsed ID3Frame where+ unparse fr = (unparse $ fr^.frHeader) +++ (unparse $ fr^.frInfo )++type FrameName = String++{-type FrameInfo = [(String, String)]-}++{- | Frame Header+-}+data FrameHeader = FrameHeader+ { frID_ :: FrameID -- ^ frame ID+ , frSize_ :: FrameSize -- ^ frame Size+ , frFlags_ :: FrameFlags -- ^ frame Flags+ } deriving Eq++emptyFrameHeader = FrameHeader "" 0 emptyFrameFlags+initFrameHeader = flip compose emptyFrameHeader++frID = accessor frID_ (\x h -> h {frID_ = x})+frSize = accessor frSize_ (\x h -> h {frSize_ = x})+frFlags = accessor frFlags_ (\x h -> h {frFlags_ = x})+++instance Show FrameHeader where+ show (FrameHeader i s fs) = "\tFrame ID:\t"++i++"\n"+++ "\tFrame size:\t"++(show s)+++ (show fs)++instance Parsed FrameHeader where+ unparse fh = (unparse $ Str $ fh^.frID ) +++ (unparse $ fh^.frSize ) +++ (unparse $ fh^.frFlags )++{-- | /FRAME ID/++ The frame ID is made out of the characters capital A-Z and 0-9.+ Identifiers beginning with "X", "Y" and "Z" are for experimental+ frames and free for everyone to use, without the need to set the+ experimental bit in the tag header. Bear in mind that someone else+ might have used the same identifier as you. All other identifiers are+ either used or reserved for future use.+--}+type FrameID = String++{-- | /SIZE BYTES/++ The frame ID is followed by a size descriptor containing the size of+ the data in the final frame, after encryption, compression and+ unsynchronisation. The size is excluding the frame header ('total+ frame size' - 10 bytes) and stored as a 32 bit synchsafe integer.+--}+type FrameSize = Integer++{-- | /Frame header flags/++ In the frame header the size descriptor is followed by two flag+ bytes. All unused flags MUST be cleared. The first byte is for+ 'status messages' and the second byte is a format description. If an+ unknown flag is set in the first byte the frame MUST NOT be changed+ without that bit cleared. If an unknown flag is set in the second+ byte the frame is likely to not be readable. Some flags in the second+ byte indicates that extra information is added to the header. These+ fields of extra information is ordered as the flags that indicates+ them. The flags field is defined as follows (l and o left out because+ ther resemblence to one and zero):++@+ %0abc0000 %0h00kmnp+@++ Some frame format flags indicate that additional information fields+ are added to the frame. This information is added after the frame+ header and before the frame data in the same order as the flags that+ indicates them. I.e. the four bytes of decompressed size will precede+ the encryption method byte. These additions affects the 'frame size'+ field, but are not subject to encryption or compression.++ The default status flags setting for a frame is, unless stated+ otherwise, 'preserved if tag is altered' and 'preserved if file is+ altered', i.e. @%00000000@.+--}+data FrameFlags = FrameFlags+ { statusF :: StatusFlags -- ^ Frame status flags+ , formatF :: FormatFlags -- ^ Frame format flags+ } deriving Eq++emptyFrameFlags = FrameFlags emptyFlags emptyFlags+initFrameFlags = flip compose emptyFrameFlags++status = accessor statusF (\x fs -> fs {statusF = x})+format = accessor formatF (\x fs -> fs {formatF = x})++instance Show FrameFlags where+ show fs = if not ((or $ fs^.status^.allFlags) || (or $ fs^.format^.allFlags)) then "" else+ "\tFlags:\n"+++ (showStatusFlags $ fs^.status)++"\n"+++ (showFormatFlags $ fs^.format)++instance Parsed FrameFlags where+ unparse fs = (unparse $ fs^.status ) +++ (unparse $ fs^.format )++{-- | /Frame status flags/++ Format: @%0abc0000@ where++ a - /Tag alter preservation/++ This flag tells the tag parser what to do with this frame if it is+ unknown and the tag is altered in any way. This applies to all+ kinds of alterations, including adding more padding and reordering+ the frames.++@+ 0 Frame should be preserved.+ 1 Frame should be discarded.+@++ b - /File alter preservation/++ This flag tells the tag parser what to do with this frame if it is+ unknown and the file, excluding the tag, is altered. This does not+ apply when the audio is completely replaced with other audio data.++@+ 0 Frame should be preserved.+ 1 Frame should be discarded.+@++ c - /Read only/++ This flag, if set, tells the software that the contents of this+ frame are intended to be read only. Changing the contents might+ break something, e.g. a signature. If the contents are changed,+ without knowledge of why the frame was flagged read only and+ without taking the proper means to compensate, e.g. recalculating+ the signature, the bit MUST be cleared.+--}+type StatusFlags = Flags++frameDiscard = accessFlag 1+fileDiscard = accessFlag 2+readOnly = accessFlag 3++showStatusFlags stat = if not (or $ stat^.allFlags) then "" else+ "\t\tStatus Flags:\n"+++ (if stat^.frameDiscard then "\t\t\t- Frame should be discarded\n" else "")+++ (if stat^.fileDiscard then "\t\t\t- Frame should be discarded\n" else "")+++ (if stat^.readOnly then "\t\t\t- Read only!\n" else "")+++{-- | /Frame format flags/++ Format: @%0h00kmnp@ where++ h - /Grouping identity/++ This flag indicates whether or not this frame belongs in a group+ with other frames. If set, a group identifier byte is added to the+ frame. Every frame with the same group identifier belongs to the+ same group.++@+ 0 Frame does not contain group information+ 1 Frame contains group information+@++ k - /Compression/++ This flag indicates whether or not the frame is compressed.+ A 'Data Length Indicator' byte MUST be included in the frame.++@+ 0 Frame is not compressed.+ 1 Frame is compressed using zlib [zlib] deflate method.+ If set, this requires the 'Data Length Indicator' bit+ to be set as well.+@++ m - /Encryption/++ This flag indicates whether or not the frame is encrypted. If set,+ one byte indicating with which method it was encrypted will be+ added to the frame. See description of the ENCR frame for more+ information about encryption method registration. Encryption+ should be done after compression. Whether or not setting this flag+ requires the presence of a 'Data Length Indicator' depends on the+ specific algorithm used.++@+ 0 Frame is not encrypted.+ 1 Frame is encrypted.+@++ n - /Unsynchronisation/++ This flag indicates whether or not unsynchronisation was applied+ to this frame. See section 6 for details on unsynchronisation.+ If this flag is set all data from the end of this header to the+ end of this frame has been unsynchronised. Although desirable, the+ presence of a 'Data Length Indicator' is not made mandatory by+ unsynchronisation.++@+ 0 Frame has not been unsynchronised.+ 1 Frame has been unsyrchronised.+@++ p - /Data length indicator/++ This flag indicates that a data length indicator has been added to+ the frame. The data length indicator is the value one would write+ as the 'Frame length' if all of the frame format flags were+ zeroed, represented as a 32 bit synchsafe integer.+@+ 0 There is no Data Length Indicator.+ 1 A data length Indicator has been added to the frame.+@+--}+type FormatFlags = Flags++groupPart = accessFlag 1 -- Grouping identity+compressed = accessFlag 2 -- Compression+encrypted = accessFlag 3 -- Encryption+unsychronised = accessFlag 4 -- Unsynchronisation+dataLengthId = accessFlag 5 -- Data length indicator++showFormatFlags form = if not (or $ form^.allFlags) then "" else+ "\t\tFormat Flags:\n"+++ (if form^.groupPart then "\t\t\t- frame is a part of group\n" else "")+++ (if form^.compressed then "\t\t\t- frame is compressed\n" else "")+++ (if form^.encrypted then "\t\t\t- frame is encrypted\n" else "")+++ (if form^.unsychronised then "\t\t\t- frame is unsynchronised\n" else "")+++ (if form^.dataLengthId then "\t\t\t- frame has data length indicator\n" else "")++--------------------------------------------------------------------------------------------+++initFrame id = updateSize $ initID3Frame [ frHeader.>frID ^= id, frInfo ^= inf ]+ where inf = case id of+ "UFID" -> UFID "" ""+ "TXXX" -> TXXX 03 "" ""+ ('T':_)-> Text 03 ""+ "WXXX" -> WXXX 03 "" ""+ ('W':_)-> URL ""+ --MCDI -- TODO+ --ETCO -- { format :: Integer+ -- , events :: [Event]} -- TODO+ --MLLT -- TODO+ --SYTC -- TODO+ "USLT" -> USLT 03 "eng" "" ""+ --SYLT enc lang timeFormat content descr+ "COMM" -> COMM 03 "eng" "" ""+ --RVA2 -- TODO+ --EQU2 -- TODO+ --RVRB -- TODO+ "APIC" -> APIC 03 "" 00 "" []+ --GEOB -- TODO+ "PCNT" -> PCNT 00+ "POPM" -> POPM "" 00 00+ --RBUF -- TODO+ --AENC -- TODO+ --LINK -- TODO+ --POSS -- TODO+ "USER" -> USER 03 "eng" ""+ --OWNE -- TODO+ --COMR -- TODO+ --ENCR -- TODO+ --GRID -- TODO+ --PRIV -- TODO+ --SIGN -- TODO+ --ASPI -- TODO+ "TCMP" -> TCMP False+ _ -> Unknown ""
+ src/ID3/Type/FrameInfo.hs view
@@ -0,0 +1,114 @@+module ID3.Type.FrameInfo where++import ID3.Parser.UnSync (synchronise, integerToWords)+import ID3.Type.Unparse+import Codec.Binary.UTF8.String (encode, encodeString, decode)+import Data.Accessor+import Data.Word (Word8)++data FrameInfo = UFID { owner :: String+ , id :: String }+ | Text { enc :: Integer+ , text :: String }+ | TXXX { enc :: Integer+ , descr :: String+ , text :: String }+ | URL { url :: String }+ | WXXX { enc :: Integer+ , descr :: String+ , url :: String }+ | MCDI -- TODO+ | ETCO -- { format :: Integer+ -- , events :: [Event]} -- TODO+ | MLLT -- TODO+ | SYTC -- TODO+ | USLT { enc :: Integer+ , lang :: String+ , descr :: String+ , text :: String }+ | SYLT { enc :: Integer+ , lang :: String+ , timeFormat :: Integer+ , content :: Integer+ , descr :: String } -- .... TODO+ | COMM { enc :: Integer+ , lang :: String+ , descr :: String+ , text :: String }+ | RVA2 -- TODO+ | EQU2 -- TODO+ | RVRB -- TODO+ | APIC { enc :: Integer+ , mime :: String+ , picType :: Word8+ , descr :: String+ , picData :: [Word8] } -- .... TODO+ | GEOB -- TODO+ | PCNT { counter :: Integer }+ | POPM { email :: String+ , rating :: Integer+ , counter :: Integer }+ | RBUF -- TODO+ | AENC -- TODO+ | LINK -- TODO+ | POSS -- TODO+ | USER { enc :: Integer+ , lang :: String+ , text :: String }+ | OWNE -- TODO+ | COMR -- TODO+ | ENCR -- TODO+ | GRID -- TODO+ | PRIV -- TODO+ | SIGN -- TODO+ | ASPI -- TODO++ -- not native+ | TCMP { isPart :: Bool }+ | Unknown { value :: String }+ deriving (Eq, Show)+++encodeAll = concatMap encode++infoTextContent = accessor text (\x f -> f {text = x})+--url = accessor (encode . url) (\x f -> f {url = decode x})++instance Parsed FrameInfo where+ unparse inf = case inf of+ UFID owner id -> (encode owner) ++ [0x00] ++ (encode id)+ Text enc text -> (fromInteger enc) : (encode text)+ TXXX enc descr text -> (fromInteger enc) : (encode descr) ++ [0x00] ++ (encode text)+ URL url -> encode url+ WXXX enc descr url -> (fromInteger enc) : (encode descr) ++ [0x00] ++ (encode url)+ --MCDI -- TODO+ --ETCO -- { format :: Integer+ -- , events :: [Event]} -- TODO+ --MLLT -- TODO+ --SYTC -- TODO+ USLT enc lang descr text -> (fromInteger enc) : (encodeAll [lang, descr]) ++ [0x00] ++ (encode text)+ --SYLT enc lang timeFormat content descr+ COMM enc lang descr text -> (fromInteger enc) : (encodeAll [lang, descr]) ++ [0x00] ++ (encode text)+ --RVA2 -- TODO+ --EQU2 -- TODO+ --RVRB -- TODO+ APIC enc mime picType descr picData -> (fromInteger enc) : (encode mime) ++ [0x00,picType] ++ (encode descr) ++[0x00]++ picData+ --GEOB -- TODO+ PCNT counter -> integerToWords 4 counter+ POPM email rating counter -> (encode email) ++ [0x00, fromInteger rating] ++ (integerToWords 4 counter)+ --RBUF -- TODO+ --AENC -- TODO+ --LINK -- TODO+ --POSS -- TODO+ USER enc lang text -> (fromInteger enc) : (encode lang) ++ [0x00] ++ (encode text)+ --OWNE -- TODO+ --COMR -- TODO+ --ENCR -- TODO+ --GRID -- TODO+ --PRIV -- TODO+ --SIGN -- TODO+ --ASPI -- TODO+ TCMP isPart -> 0x03 : (encode $ if isPart then "1" else "0")+ Unknown x -> encode x+ _ -> encode "unknown!!!"+
+ src/ID3/Type/Header.hs view
@@ -0,0 +1,122 @@+module ID3.Type.Header+where++import ID3.Type.Unparse+import ID3.Type.Flags+import Data.Word (Word8)+import Data.Accessor+import Data.Accessor.Basic (compose)++{- | /ID3v2 HEADER OVERVIEW/++ The first part of the ID3v2 tag is the 10 byte tag header, laid out+ as follows:++@+ ID3v2/file identifier \"ID3\"+ ID3v2 version $04 00+ ID3v2 flags %abcd0000+ ID3v2 size 4 * %0xxxxxxx+@++ The first three bytes of the tag are always \"ID3\", to indicate that+ this is an ID3v2 tag, directly followed by the two version bytes. The+ first byte of ID3v2 version is its major version, while the second+ byte is its revision number. In this case this is ID3v2.4.0. All+ revisions are backwards compatible while major versions are not. If+ software with ID3v2.4.0 and below support should encounter version+ five or higher it should simply ignore the whole tag.+-}+data ID3Header = ID3Header+ { tagVersion_ :: TagVersion -- ^ id3v2 version: @[major version, revision number]@+ , tagFlags_ :: TagFlags -- ^ header flags as Bool values+ , tagSize_ :: TagSize -- ^ full size of tag+ } deriving Eq++emptyID3Header = ID3Header [4,0] emptyFlags 0+initID3Header = flip compose emptyID3Header++tagVersion = accessor tagVersion_ (\v h -> h {tagVersion_ = v})+tagFlags = accessor tagFlags_ (\f h -> h {tagFlags_ = f})+tagSize = accessor tagSize_ (\s h -> h {tagSize_ = s})++instance Show ID3Header where+ show header = "ID3v2"++"."++(show v1)++"."++(show v2)++"\n"+++ (showTagFlags $ header^.tagFlags)+++ "Tag size: "++(show $ header^.tagSize )++" bytes\n"+ where (v1:v2:_) = header^.tagVersion++instance Parsed ID3Header where+ unparse h = (unparse $ Str "ID3" ) +++ ( h^.tagVersion) +++ (unparse $ h^.tagFlags ) +++ (unparse $ h^.tagSize )++{- | id3v2 version+ @major version . revision number@+-}+type TagVersion = [Word8]+++{- | /MEANING OF FLAGS/++@+ ID3v2 flags %abcd0000+@++ The version is followed by the ID3v2 flags field, of which currently+ four flags are used:++ @a@ - /Unsynchronisation/++ Bit 7 in the 'ID3v2 flags' indicates whether or not+ unsynchronisation is applied on all frames (see section 6.1 for+ details); a set bit indicates usage.++ @b@ - /Extended header/++ The second bit (bit 6) indicates whether or not the header is+ followed by an extended header. The extended header is described in+ section 3.2. A set bit indicates the presence of an extended+ header.++ @c@ - /Experimental indicator/++ The third bit (bit 5) is used as an 'experimental indicator'. This+ flag SHALL always be set when the tag is in an experimental stage.++ @d@ - /Footer present/++ Bit 4 indicates that a footer (section 3.4) is present at the very+ end of the tag. A set bit indicates the presence of a footer.+++ All the other flags MUST be cleared. If one of these undefined flags+ are set, the tag might not be readable for a parser that does not+ know the flags function.+-}+type TagFlags = Flags++unsynch = accessFlag 1+extended = accessFlag 2+experimental = accessFlag 3+footed = accessFlag 4++showTagFlags f = if not (or $ f^.allFlags) then "" else+ "Flags: \n"+++ (if f^.unsynch then "\t- all frames are unsynchronised\n" else "")+++ (if f^.extended then "\t- tag has extended header\n" else "")+++ (if f^.experimental then "\t- tag is in experimental stage\n" else "")+++ (if f^.footed then "\t- tag has footer at the very end\n" else "")++{- | /SIZE BYTES/++ The ID3v2 tag size is stored as a 32 bit synchsafe integer (section+ 6.2), making a total of 28 effective bits (representing up to 256MB).++ The ID3v2 tag size is the sum of the byte length of the extended+ header, the padding and the frames after unsynchronisation. If a+ footer is present this equals to ('total size' - 20) bytes, otherwise+ ('total size' - 10) bytes.+-}+type TagSize = Integer
+ src/ID3/Type/Tag.hs view
@@ -0,0 +1,123 @@+module ID3.Type.Tag+where++import Data.List ((\\))+import Data.Maybe+import Data.Map (Map)+import qualified Data.Map as Map+import Data.Accessor+import Data.Accessor.Basic (compose)++import ID3.Type.Header+import ID3.Type.ExtHeader+import ID3.Type.Frame+import ID3.Type.Unparse++{-- /ID3v2 Format Overview/++ ID3v2 is a general tagging format for audio, which makes it possible+ to store meta data about the audio inside the audio file itself. The+ ID3 tag described in this document is mainly targeted at files+ encoded with MPEG-1/2 layer I, MPEG-1/2 layer II, MPEG-1/2 layer III+ and MPEG-2.5, but may work with other types of encoded audio or as a+ stand alone format for audio meta data.++ ID3v2 is designed to be as flexible and expandable as possible to+ meet new meta information needs that might arise. To achieve that+ ID3v2 is constructed as a container for several information blocks,+ called frames, whose format need not be known to the software that+ encounters them. At the start of every frame is an unique and+ predefined identifier, a size descriptor that allows software to skip+ unknown frames and a flags field. The flags describes encoding+ details and if the frame should remain in the tag, should it be+ unknown to the software, if the file is altered.++ The bitorder in ID3v2 is most significant bit first (MSB). The+ byteorder in multibyte numbers is most significant byte first (e.g.+ $12345678 would be encoded $12 34 56 78), also known as big endian+ and network byte order.++ Overall tag structure:++ +-----------------------------++ | Header (10 bytes) |+ +-----------------------------++ | Extended Header |+ | (variable length, OPTIONAL) |+ +-----------------------------++ | Frames (variable length) |+ +-----------------------------++ | Padding |+ | (variable length, OPTIONAL) |+ +-----------------------------++ | Footer (10 bytes, OPTIONAL) |+ +-----------------------------+++ In general, padding and footer are mutually exclusive.+--}++data ID3Tag = ID3Tag+ { tagHeader :: ID3Header+ , tagExtHeader :: Maybe ID3ExtHeader+ , tagFrames :: Map FrameID ID3Frame+ , tagFramesOrder :: [FrameID]+ , tagPadding :: Integer+ } deriving Eq++emptyID3Tag = ID3Tag emptyID3Header Nothing Map.empty [] 0+initID3Tag = flip compose emptyID3Tag++header = accessor tagHeader (\x t -> t {tagHeader = x})+version = header .> tagVersion++---------------------+instance HasSize ID3Tag where+ size = accessor getFullSize setSize++setSize = setVal $ header .> tagSize+getFullSize t = getActualSize t + (t^.padding)++getActualSize t = (footerSize t) + (framesSize (t^.frames)) + (extHSize t)++framesSize fs = Map.fold (\fr x -> fr^.frHeader^.frSize + 10 + x) 0 fs+footerSize t = if t^.flags^.footed then 10 else 0+extHSize t = case t^.extHeader of+ Just eH -> eH^.extSize+ Nothing -> 0+padding = accessor tagPadding (\x t -> t {tagPadding = x})++---------------------+flags = header .> tagFlags++extHeader = accessor tagExtHeader (\x t -> t {tagExtHeader = x})+frames = accessor tagFrames (\x t -> t {tagFrames = x})++framesOrder = accessor tagFramesOrder (\x t -> t {tagFramesOrder = x})++frame :: FrameID -> Accessor ID3Tag (Maybe ID3Frame)+frame id = accessor (\t -> getFrame t id) (\x t -> setFrame t id x)++getFrame t f = Map.lookup f (t^.frames)+setFrame t f x = updateSize $ frames ^= Map.alter (\_ -> x) f (t^.frames) $ t++---------------------------------------------------------++sortFrames fs ids = mapMaybe (\id -> Map.lookup id fs) $ ids ++ (Map.keys fs \\ ids)++instance Show ID3Tag where+ show t = ( show $ t^.header) ++"\n"+++ ( "Full tag size: "++(show $ getFullSize t)) ++"\n"+++ ( "Actual tag size: "++(show $ getActualSize t)) ++"\n"+++ ( "Padding size: "++(show $ t^.padding)) ++"\n"+++ ( unwords $ t^.framesOrder ) ++"\n"+++ ( maybe "" show $ t^.extHeader ) ++"\n"+++ ( concatMap show $ sortFrames (t^.frames) (t^.framesOrder) )++instance Parsed ID3Tag where+ unparse t = ( unparse $ t^.header ) +++ ( maybe [] unparse $ t^.extHeader ) +++ ( concatMap unparse $ sortFrames (t^.frames) (t^.framesOrder) ) +++ ( if t^.flags^.footed then unparseFooter ++ (drop 10 unparsePadding) else unparsePadding )+ where+ unparseFooter = (unparse $ Str "3DI") ++ (drop 3 $ unparse $ t^.header)+ unparsePadding = replicate (fromInteger $ t^.padding) 0x00
+ src/ID3/Type/Unparse.hs view
@@ -0,0 +1,33 @@+module ID3.Type.Unparse where++import ID3.Parser.UnSync (synchronise)+import Codec.Binary.UTF8.String (encode, encodeString)+import Data.List (intersperse)+import Data.Word (Word8)+import Data.Accessor+import System.IO.UTF8 as U++class Parsed a where+ unparse :: a -> [Word8]++instance Parsed Integer where+ unparse i = synchronise i++data Str = Str String deriving Eq+instance Parsed Str where+ unparse (Str s) = encode s++data Inf = Inf [(String, String)] deriving Eq+instance Show Inf where+ show (Inf xs) = concatMap (encodeString . snd) xs++instance Parsed Inf where+ unparse _ = undefined+ -- unparse (Inf xs) = 0x03 : (concat $ intersperse [0x00] $ map (\(_,s) -> unparse $ Str s) xs)++-----------------------------++class HasSize a where+ size :: Accessor a Integer+ updateSize :: a -> a+ updateSize x = size ^= (x^.size) $ x
+ src/ID3/WriteTag.hs view
@@ -0,0 +1,38 @@+module ID3.WriteTag+( hWriteTag+, writeTag+) where++import ID3.Type+import ID3.Parser+import ID3.ReadTag+import Data.Accessor+import System.IO+import System.IO.Binary+--import Data.Word (Word8)++hWriteTag :: ID3Tag -> Handle -> IO ()+hWriteTag newTag hdl = do+ smth <- hReadTag hdl+ case smth of+ Nothing -> insertTag (padding^=pad $ newTag) 0+ Just oldTag ->+ let diff = (getFullSize oldTag) - (getActualSize newTag)+ in if diff <= 0+ then insertTag (padding^=pad $ newTag) $ 10 + (oldTag^.size)+ else do+ hSeek hdl AbsoluteSeek 0+ hPutBufStr hdl (unparse (padding^=diff $ newTag))+ --rest <- readFrom $ 10+(oldTag^.size) :: IO [Word8]+ --withBinaryFile "_m.mp3" WriteMode $ \h -> hPutBufStr h rest+ where+ pad = 4096 -- default padding size+ insertTag t pos = do+ hSeek hdl AbsoluteSeek pos+ rest <- hGetBufStr hdl . fromInteger =<< hFileSize hdl+ --withBinaryFile "_m.mp3" WriteMode $ \h -> hPutBufStr h rest+ hSeek hdl AbsoluteSeek 0+ hPutBufStr hdl (unparse t ++ rest)++writeTag :: FilePath -> ID3Tag -> IO ()+writeTag file = withBinaryFile file ReadWriteMode . hWriteTag