mp4-atom.lisp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. ;;; -*- Mode: Lisp; show-trailing-whitespace: t; Base: 10; indent-tabs: nil; Syntax: ANSI-Common-Lisp; Package: MP4-ATOM; -*-
  2. ;;; Copyright (c) 2013, Mark VandenBrink. All rights reserved.
  3. (in-package #:mp4-atom)
  4. (log5:defcategory cat-log-mp4-atom)
  5. (defmacro log-mp4-atom (&rest log-stuff) `(log5:log-for (cat-log-mp4-atom) ,@log-stuff))
  6. (define-condition mp4-atom-condition ()
  7. ((location :initarg :location :reader location :initform nil)
  8. (object :initarg :object :reader object :initform nil)
  9. (messsage :initarg :message :reader message :initform "Undefined Condition"))
  10. (:report (lambda (condition stream)
  11. (format stream "mp4-atom condition at location: <~a> with object: <~a>: message: <~a>"
  12. (location condition) (object condition) (message condition)))))
  13. (defmethod print-object ((me mp4-atom-condition) stream)
  14. (format stream "location: <~a>, object: <~a>, message: <~a>" (location me) (object me) (message me)))
  15. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ATOMS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  16. ;;;
  17. ;;; A word about atoms (aka "boxes"). There are three kinds of atoms: ones that are containers, ones
  18. ;;; that are data, and ones that are both. A lot of the source code for taggers out there mostly ignore
  19. ;;; the third class and treat "container atoms that also have data" as a big blob of data that they
  20. ;;; rummage around in via indices. Seems sort of broken, IMHO, so we'll try to handle all three if
  21. ;;; at all possible.
  22. ;;;
  23. (defun as-int (str)
  24. "Given a 4-byte string, return an integer type equivalent.
  25. (eg (as-int \"hdlr\" == +audioprop-hdlr+))"
  26. (declare #.utils:*standard-optimize-settings*)
  27. (let ((int 0))
  28. (declare (integer int))
  29. (setf (ldb (byte 8 24) int) (char-code (aref str 0)))
  30. (setf (ldb (byte 8 16) int) (char-code (aref str 1)))
  31. (setf (ldb (byte 8 8) int) (char-code (aref str 2)))
  32. (setf (ldb (byte 8 0) int) (char-code (aref str 3)))
  33. int))
  34. (defun as-string (atom-type)
  35. (declare #.utils:*standard-optimize-settings*)
  36. (with-output-to-string (s nil)
  37. (write-char (code-char (ldb (byte 8 24) atom-type)) s)
  38. (write-char (code-char (ldb (byte 8 16) atom-type)) s)
  39. (write-char (code-char (ldb (byte 8 8) atom-type)) s)
  40. (write-char (code-char (ldb (byte 8 0) atom-type)) s)))
  41. (utils:memoize 'as-string)
  42. (defun mk-atom-class-name (name)
  43. (string-upcase (concatenate 'string "atom-" (as-string name))))
  44. (utils:memoize 'mk-atom-class-name)
  45. ;; (defmethod as-string ((atom-type integer))
  46. ;; "Given an integer representing an atom type, return the string form"
  47. ;; (with-output-to-string (s nil)
  48. ;; (write-char (code-char (ldb (byte 8 24) atom-type)) s)
  49. ;; (write-char (code-char (ldb (byte 8 16) atom-type)) s)
  50. ;; (write-char (code-char (ldb (byte 8 8) atom-type)) s)
  51. ;; (write-char (code-char (ldb (byte 8 0) atom-type)) s)))
  52. (eval-when (:compile-toplevel :load-toplevel :execute)
  53. (defun as-octet (c)
  54. "Used below so that we can create atom 'types' from char/ints"
  55. (declare #.utils:*standard-optimize-settings*)
  56. (cond ((typep c 'standard-char) (coerce (char-code c) '(unsigned-byte 8)))
  57. ((typep c 'integer) (coerce c '(unsigned-byte 8)))
  58. (t (error "can any handle characters and integers"))))
  59. (defmacro mk-mp4-atom-type (l1 l2 l3 l4)
  60. "Given 4 chars/ints, create a 32-bit word representing an atom 'type' (aka name)"
  61. `(let ((retval 0))
  62. (setf (ldb (byte 8 24) retval) ,(as-octet l1))
  63. (setf (ldb (byte 8 16) retval) ,(as-octet l2))
  64. (setf (ldb (byte 8 8) retval) ,(as-octet l3))
  65. (setf (ldb (byte 8 0) retval) ,(as-octet l4))
  66. retval)))
  67. (defconstant +itunes-album+ (mk-mp4-atom-type #xa9 #\a #\l #\b) "text: album name")
  68. (defconstant +itunes-album-artist+ (mk-mp4-atom-type #\a #\A #\R #\T) "text: album artist")
  69. (defconstant +itunes-artist+ (mk-mp4-atom-type #xa9 #\A #\R #\T) "text: artist name")
  70. (defconstant +itunes-comment+ (mk-mp4-atom-type #xa9 #\c #\m #\t) "text: comment, commonly used by iTunes for sound info, etc")
  71. (defconstant +itunes-compilation+ (mk-mp4-atom-type #\c #\p #\i #\l) "byte/boolean: is this file part of a compilation?")
  72. (defconstant +itunes-composer+ (mk-mp4-atom-type #xa9 #\c #\o #\m) "text: composer name")
  73. (defconstant +itunes-copyright+ (mk-mp4-atom-type #\c #\p #\r #\t) "text: copyright info")
  74. (defconstant +itunes-cover-art+ (mk-mp4-atom-type #\c #\o #\v #\r) "octets: cover art, PNG, etc")
  75. (defconstant +itunes-disk+ (mk-mp4-atom-type #\d #\i #\s #\k) "octets: disk number, can be n of N")
  76. (defconstant +itunes-encoder+ (mk-mp4-atom-type #xa9 #\e #\n #\c) "text: who encoded")
  77. (defconstant +itunes-genre+ (mk-mp4-atom-type #\g #\n #\r #\e) "octets: genre of file")
  78. (defconstant +itunes-genre-x+ (mk-mp4-atom-type #xa9 #\n #\r #\e) "text: yet another genre atom")
  79. (defconstant +itunes-groups+ (mk-mp4-atom-type #xa9 #\g #\r #\p) "text: ???")
  80. (defconstant +itunes-lyrics+ (mk-mp4-atom-type #xa9 #\l #\y #\r) "text: lyrics tag")
  81. (defconstant +itunes-purchased-date+ (mk-mp4-atom-type #\p #\u #\r #\d) "text: when song was purchased")
  82. (defconstant +itunes-tempo+ (mk-mp4-atom-type #\t #\m #\p #\o) "octet: tempo of song")
  83. (defconstant +itunes-title+ (mk-mp4-atom-type #xa9 #\n #\a #\m) "text: title of song")
  84. (defconstant +itunes-tool+ (mk-mp4-atom-type #xa9 #\t #\o #\o) "text: what tool encoded this file")
  85. (defconstant +itunes-track+ (mk-mp4-atom-type #xa9 #\t #\r #\k) "octet: track number")
  86. (defconstant +itunes-track-n+ (mk-mp4-atom-type #\t #\r #\k #\n) "octet: yet another track number")
  87. (defconstant +itunes-writer+ (mk-mp4-atom-type #xa9 #\w #\r #\t) "text: who wrote the song")
  88. (defconstant +itunes-year+ (mk-mp4-atom-type #xa9 #\d #\a #\y) "text: year album was released")
  89. (defconstant +itunes-ilst-data+ (mk-mp4-atom-type #\d #\a #\t #\a) "Carries the actual data under an ilst atom")
  90. (defconstant +m4-ftyp+ (mk-mp4-atom-type #\f #\t #\y #\p) "This should be the first atom type found in file")
  91. (defconstant +audioprop-hdlr+ (mk-mp4-atom-type #\h #\d #\l #\r) "Found under trak.mdia and tells what kind of handler it is")
  92. (defconstant +audioprop-mdhd+ (mk-mp4-atom-type #\m #\d #\h #\d) "Found under trak.mdia and holds data to calculate length of audio")
  93. (defconstant +audioprop-stsd+ (mk-mp4-atom-type #\s #\t #\s #\d) "Container atom: found under trak.mdia.minf.stbl and holds bit-rate, etc")
  94. (defconstant +audioprop-mp4a+ (mk-mp4-atom-type #\m #\p #\4 #\a) "Found under trak.mdia.minf.stbl")
  95. (defconstant +audioprop-esds+ (mk-mp4-atom-type #\e #\s #\d #\s) "Found under trak.mdia.minf.stbl.mp4a")
  96. (defconstant +mp4-atom-ilst+ (mk-mp4-atom-type #\i #\l #\s #\t))
  97. (defconstant +mp4-atom-mdia+ (mk-mp4-atom-type #\m #\d #\i #\a))
  98. (defconstant +mp4-atom-meta+ (mk-mp4-atom-type #\m #\e #\t #\a))
  99. (defconstant +mp4-atom-minf+ (mk-mp4-atom-type #\m #\i #\n #\f))
  100. (defconstant +mp4-atom-moov+ (mk-mp4-atom-type #\m #\o #\o #\v))
  101. (defconstant +mp4-atom-stbl+ (mk-mp4-atom-type #\s #\t #\b #\l))
  102. (defconstant +mp4-atom-trak+ (mk-mp4-atom-type #\t #\r #\a #\k))
  103. (defconstant +mp4-atom-udta+ (mk-mp4-atom-type #\u #\d #\t #\a))
  104. (defun atom-read-loop (mp4-file end func)
  105. "Loop from start to end through a file and call FUNC for every ATOM we find. Used
  106. at top-level and also for container ATOMs that need to read their contents."
  107. (declare #.utils:*standard-optimize-settings*)
  108. (log5:with-context "atom-read-loop"
  109. (do ()
  110. ((>= (stream-seek mp4-file) end))
  111. (log-mp4-atom "atom-read-loop: @~:d before dispatch" (stream-seek mp4-file))
  112. (funcall func)
  113. (log-mp4-atom "atom-read-loop: @~:d after dispatch" (stream-seek mp4-file)))))
  114. (defclass mp4-atom ()
  115. ((atom-file-position :accessor atom-file-position :initarg :atom-file-position)
  116. (atom-size :accessor atom-size :initarg :atom-size)
  117. (atom-type :accessor atom-type :initarg :atom-type)
  118. (atom-children :accessor atom-children :initform nil))
  119. (:documentation "The minimal mp4-atom. Note: not all atoms have children, but we put them here anyway to make things 'simple'"))
  120. (defmethod addc ((me mp4-atom) value)
  121. "Want to add children atoms to end of ATOM-CHILDREN to preserve in-file order."
  122. (declare #.utils:*standard-optimize-settings*)
  123. (with-slots (atom-children) me
  124. (if (null atom-children)
  125. (setf atom-children (list value))
  126. (nconc atom-children (list value)))))
  127. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Concreate atoms ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  128. (defclass atom-skip (mp4-atom) ())
  129. (defmethod initialize-instance :after ((me atom-skip) &key (mp4-file nil) &allow-other-keys)
  130. "The 'skip' atom. Used when we want to capture the header of atom, but don't want/need
  131. to read the payload of an atom."
  132. (declare #.utils:*standard-optimize-settings*)
  133. (with-slots (atom-size atom-type) me
  134. (stream-seek mp4-file (- atom-size 8) :current)))
  135. (defclass atom-raw-mixin ()
  136. ((raw-data :accessor raw-data)))
  137. (defmethod initialize-instance :after ((me atom-raw-mixin) &key (mp4-file nil) &allow-other-keys)
  138. "The 'don't need to know contents, but want 'blob' of data read in' atom"
  139. (declare #.utils:*standard-optimize-settings*)
  140. (log5:with-context "atom-raw-mixin"
  141. (with-slots (raw-data atom-type atom-size) me
  142. (log-mp4-atom "atom-raw-mixin: reading in ~d raw bytes for ~a" (- atom-size 8) (vpprint me nil))
  143. (setf raw-data (stream-read-sequence mp4-file (- atom-size 8)))
  144. ;;(utils:dump-data "/tmp/o.txt" raw-data)
  145. )))
  146. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ILST ATOMS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  147. (defclass atom-ilst (mp4-atom) ())
  148. (defmethod initialize-instance :after ((me atom-ilst) &key (mp4-file nil) &allow-other-keys)
  149. "Construct an ilst atom. ILST atoms are containers that hold data elements related to tagging.
  150. Loop through this container and construct constituent atoms"
  151. (declare #.utils:*standard-optimize-settings*)
  152. (log5:with-context "atom-ilst-initializer"
  153. (with-slots (atom-size atom-type atom-children) me
  154. (log-mp4-atom "atom-ilst-init: found ilst atom <~a> @ ~:d, looping for ~:d bytes"
  155. (as-string atom-type) (stream-seek mp4-file) (- atom-size 8))
  156. (atom-read-loop mp4-file (+ (stream-seek mp4-file) (- atom-size 8))
  157. (lambda ()
  158. (let ((child (make-mp4-atom mp4-file atom-type)))
  159. ;(log-mp4-atom "adding new child ~a" (vpprint child nil))
  160. (addc me child))))))
  161. ;(log-mp4-atom "returning ilst atom: ~a" (vpprint me nil))
  162. )
  163. (defclass atom-©alb (atom-ilst) ())
  164. (defclass atom-aART (atom-ilst) ())
  165. (defclass atom-©art (atom-ilst) ())
  166. (defclass atom-©cmt (atom-ilst) ())
  167. (defclass atom-cpil (atom-ilst) ())
  168. (defclass atom-©com (atom-ilst) ())
  169. (defclass atom-cprt (atom-ilst) ())
  170. (defclass atom-covr (atom-ilst) ())
  171. (defclass atom-disk (atom-ilst) ())
  172. (defclass atom-©enc (atom-ilst) ())
  173. (defclass atom-gnre (atom-ilst) ())
  174. (defclass atom-©nre (atom-ilst) ())
  175. (defclass atom-©grp (atom-ilst) ())
  176. (defclass atom-©lyr (atom-ilst) ())
  177. (defclass atom-purd (atom-ilst) ())
  178. (defclass atom-tmpo (atom-ilst) ())
  179. (defclass atom-©nam (atom-ilst) ())
  180. (defclass atom-©too (atom-ilst) ())
  181. (defclass atom-©trk (atom-ilst) ())
  182. (defclass atom-trkn (atom-ilst) ())
  183. (defclass atom-©wrt (atom-ilst) ())
  184. (defclass atom-©day (atom-ilst) ())
  185. (defclass atom-data (mp4-atom)
  186. ((atom-version :accessor atom-version :initarg :atom-version)
  187. (atom-flags :accessor atom-flags :initarg :atom-flags)
  188. (atom-value :accessor atom-value :initarg :atom-value)
  189. (atom-parent-type :accessor atom-parent-type :initarg :atom-parent-type :initform nil))
  190. (:documentation "Represents the 'data' portion of ilst data atom"))
  191. (defmethod initialize-instance :after ((me atom-data) &key mp4-file &allow-other-keys)
  192. (declare #.utils:*standard-optimize-settings*)
  193. (log5:with-context "atom-data-init"
  194. (with-slots (atom-size atom-type atom-version atom-flags atom-value atom-parent-type) me
  195. (setf atom-version (stream-read-u8 mp4-file))
  196. (setf atom-flags (stream-read-u24 mp4-file))
  197. (assert (= 0 (stream-read-u32 mp4-file)) () "a data atom lacks the required null field") ; XXX is this true?
  198. (log-mp4-atom "atom-data-init: size = ~:d, name = ~a, version = ~d, flags = ~x" atom-size (as-string atom-type) atom-version atom-flags)
  199. (setf atom-value (decode-ilst-data-atom atom-type me atom-parent-type mp4-file))
  200. (log-mp4-atom "atom-data-init: made an ilst atom-data: ~a" (vpprint me nil)))))
  201. ;;; the ILST atom decoders. First, a lot of the decoders do the same thing, so we define a macros
  202. ;;; and use those for the relevants atoms.
  203. (defgeneric decode-ilst-data-atom (type atom atom-parent-type mp4-file))
  204. ;;; Quicktime spec says strings are stored as UTF-8...
  205. (defmacro simple-text-decode (type)
  206. `(defmethod decode-ilst-data-atom ((type (eql +itunes-ilst-data+)) atom (atom-parent-type (eql ,type)) mp4-file)
  207. (stream-read-utf-8-string-with-len mp4-file (- (atom-size atom) 16))))
  208. (simple-text-decode +itunes-album+)
  209. (simple-text-decode +itunes-album-artist+)
  210. (simple-text-decode +itunes-artist+)
  211. (simple-text-decode +itunes-comment+)
  212. (simple-text-decode +itunes-composer+)
  213. (simple-text-decode +itunes-copyright+)
  214. (simple-text-decode +itunes-year+)
  215. (simple-text-decode +itunes-encoder+)
  216. (simple-text-decode +itunes-groups+)
  217. (simple-text-decode +itunes-genre-x+)
  218. (simple-text-decode +itunes-lyrics+)
  219. (simple-text-decode +itunes-purchased-date+)
  220. (simple-text-decode +itunes-title+)
  221. (simple-text-decode +itunes-tool+)
  222. (simple-text-decode +itunes-writer+)
  223. ;;; for reasons I'm not clear on, there may or may not be extra bytes after the data in these atoms
  224. ;;; hence, the seek at the end to get us by any unread bytes.
  225. (defmacro simple-a-b-decode (type)
  226. `(defmethod decode-ilst-data-atom ((type (eql +itunes-ilst-data+)) atom (atom-parent-type (eql ,type)) mp4-file)
  227. (let ((tmp (stream-read-u16 mp4-file)))
  228. (declare (ignore tmp)))
  229. ;(format t "ilist decode, parent = ~a: ~x~%" (as-string atom-parent-type) tmp))
  230. (let ((a) (b))
  231. (setf a (stream-read-u16 mp4-file))
  232. (setf b (stream-read-u16 mp4-file))
  233. (stream-seek mp4-file (- (atom-size atom) 16 6) :current) ; seek to end of atom: 16 == header; 4 is a, b, skip read above
  234. (list a b))))
  235. (simple-a-b-decode +itunes-track+)
  236. (simple-a-b-decode +itunes-track-n+)
  237. (simple-a-b-decode +itunes-disk+)
  238. (defmacro simple-u16-decode (type)
  239. `(defmethod decode-ilst-data-atom ((type (eql +itunes-ilst-data+)) atom (atom-parent-type (eql ,type)) mp4-file)
  240. (declare (ignore atom))
  241. (stream-read-u16 mp4-file)))
  242. (simple-u16-decode +itunes-tempo+)
  243. (simple-u16-decode +itunes-genre+)
  244. (defmethod decode-ilst-data-atom ((type (eql +itunes-ilst-data+)) atom (atom-parent-type (eql +itunes-compilation+)) mp4-file)
  245. (declare (ignore atom))
  246. (stream-read-u8 mp4-file))
  247. (defmethod decode-ilst-data-atom ((type (eql +itunes-ilst-data+)) atom (atom-parent-type (eql +itunes-cover-art+)) mp4-file)
  248. (stream-read-sequence mp4-file (- (atom-size atom) 16)))
  249. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; AUDIO PROPERTY ATOMS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  250. ;;; the pure container classes we need recurse into
  251. (defclass atom-trak (mp4-atom) ())
  252. (defmethod initialize-instance :after ((me atom-trak) &key (mp4-file nil) &allow-other-keys)
  253. (read-container-atoms mp4-file me))
  254. (defclass atom-minf (mp4-atom) ())
  255. (defmethod initialize-instance :after ((me atom-minf) &key (mp4-file nil) &allow-other-keys)
  256. (read-container-atoms mp4-file me))
  257. (defclass atom-moov (mp4-atom) ())
  258. (defmethod initialize-instance :after ((me atom-moov) &key (mp4-file nil) &allow-other-keys)
  259. (read-container-atoms mp4-file me))
  260. (defclass atom-udta (mp4-atom) ())
  261. (defmethod initialize-instance :after ((me atom-udta) &key (mp4-file nil) &allow-other-keys)
  262. (read-container-atoms mp4-file me))
  263. (defclass atom-mdia (mp4-atom) ())
  264. (defmethod initialize-instance :after ((me atom-mdia) &key (mp4-file nil) &allow-other-keys)
  265. (read-container-atoms mp4-file me))
  266. (defclass atom-stbl (mp4-atom) ())
  267. (defmethod initialize-instance :after ((me atom-stbl) &key (mp4-file nil) &allow-other-keys)
  268. (read-container-atoms mp4-file me))
  269. (defclass atom-hdlr (mp4-atom)
  270. ((version :accessor version) ; 1 byte
  271. (flags :accessor flags) ; 3 bytes
  272. (qtype :accessor qtype) ; 4 bytes
  273. (mtype :accessor mtype) ; 4 bytes
  274. (resv :accessor resv) ; 4 bytes
  275. (rflag :accessor rflag) ; 4 bytes
  276. (rmask :accessor rmask) ; 4 bytes
  277. (mhdlr :accessor mhdlr))) ; null-terminated string (XXX but we're reading it as octets)
  278. (defmethod initialize-instance :after ((me atom-hdlr) &key (mp4-file nil) &allow-other-keys)
  279. (with-slots (version flags qtype mtype resv rflag rmask mhdlr atom-size) me
  280. (setf version (stream-read-u8 mp4-file))
  281. (setf flags (stream-read-u24 mp4-file))
  282. (setf qtype (stream-read-u32 mp4-file))
  283. (setf mtype (stream-read-u32 mp4-file))
  284. (setf resv (stream-read-u32 mp4-file))
  285. (setf rflag (stream-read-u32 mp4-file))
  286. (setf rmask (stream-read-u32 mp4-file))
  287. (setf mhdlr (stream-read-sequence mp4-file (- atom-size 32))))) ; 32 is 8-bytes of header plus fields above
  288. (defclass atom-mdhd (mp4-atom)
  289. ((version :accessor version)
  290. (flags :accessor flags)
  291. (c-time :accessor c-time)
  292. (m-time :accessor m-time)
  293. (scale :accessor scale)
  294. (duration :accessor duration)
  295. (lang :accessor lang)
  296. (quality :accessor quality)))
  297. (defmethod initialize-instance :after ((me atom-mdhd) &key (mp4-file nil) &allow-other-keys)
  298. (declare #.utils:*standard-optimize-settings*)
  299. (with-slots (version flags c-time m-time scale duration lang quality) me
  300. (setf version (stream-read-u8 mp4-file))
  301. (setf flags (stream-read-u24 mp4-file))
  302. (setf c-time (stream-read-u32 mp4-file))
  303. (setf m-time (stream-read-u32 mp4-file))
  304. (setf scale (stream-read-u32 mp4-file))
  305. (setf duration (if (= 0 version) (stream-read-u32 mp4-file) (stream-read-u64 mp4-file)))
  306. (setf lang (stream-read-u16 mp4-file))
  307. (setf quality (stream-read-u16 mp4-file))))
  308. (defclass atom-esds (mp4-atom)
  309. ((version :accessor version) ; 1 byte
  310. (flags :accessor flags) ; 3 bytes
  311. (esid :accessor esid) ; 2 bytes
  312. (s-priority :accessor s-priority) ; 1 byte
  313. (obj-id :accessor obj-id) ; 1 byte
  314. (s-type :accessor s-type) ; 1 byte (1 bit up-stream, 1-but reservered, 6-bits stream type
  315. (buf-size :accessor buf-size) ; 3 bytes
  316. (max-bit-rate :accessor max-bit-rate) ; 4 bytes
  317. (avg-bit-rate :accessor avg-bit-rate)) ; 4 bytes
  318. (:documentation "XXX-partial definition for Elementary Stream Descriptors (ESDs)"))
  319. ;;; 3 bytes extended descriptor type tag string = 3 * 8-bit hex value
  320. ;;; types are Start = 0x80 ; End = 0xFE
  321. ;;; then, one byte of length
  322. ;;; Note: start types are optional
  323. (defun read-descriptor-len (instream)
  324. "Get the ES descriptor's length."
  325. (declare #.utils:*standard-optimize-settings*)
  326. (let* ((tmp (stream-read-u8 instream))
  327. (len (logand tmp #x7f)))
  328. (declare (type (unsigned-byte 8) tmp))
  329. (while (not (zerop (logand #x80 tmp)))
  330. (setf tmp (stream-read-u8 instream))
  331. (setf len (logior (ash len 7) (logand tmp #x7f))))
  332. len))
  333. ;;; one-byte descriptor tags
  334. (defconstant +mp4-odescrtag+ #x01)
  335. (defconstant +mp4-iodescrtag+ #x02)
  336. (defconstant +mp4-esdescrtag+ #x03)
  337. (defconstant +mp4-decconfigdescrtag+ #x04)
  338. (defconstant +mp4-decspecificdescrtag+ #x05)
  339. (defconstant +mp4-slconfigdescrtag+ #x06)
  340. (defconstant +mp4-contentiddescrtag+ #x07)
  341. (defconstant +mp4-supplcontentiddescrtag+ #x08)
  342. (defconstant +mp4-ipiptrdescrtag+ #x09)
  343. (defconstant +mp4-ipmpptrdescrtag+ #x0a)
  344. (defconstant +mp4-ipmpdescrtag+ #x0b)
  345. (defconstant +mp4-registrationdescrtag+ #x0d)
  346. (defconstant +mp4-esidincdescrtag+ #x0e)
  347. (defconstant +mp4-esidrefdescrtag+ #x0f)
  348. (defconstant +mp4-fileiodescrtag+ #x10)
  349. (defconstant +mp4-fileodescrtag+ #x11)
  350. (defconstant +mp4-extprofileleveldescrtag+ #x13)
  351. (defconstant +mp4-extdescrtagsstart+ #x80)
  352. (defconstant +mp4-extdescrtagsend+ #xfe)
  353. (defmethod initialize-instance :after ((me atom-esds) &key (mp4-file nil) &allow-other-keys)
  354. (declare #.utils:*standard-optimize-settings*)
  355. (with-slots (version flags esid s-priority obj-id s-type buf-size max-bit-rate avg-bit-rate) me
  356. (setf version (stream-read-u8 mp4-file))
  357. (setf flags (stream-read-u24 mp4-file))
  358. (assert (= +MP4-ESDescrTag+ (stream-read-u8 mp4-file)) () "Expected description tag of ESDescrTag")
  359. (let* ((len (read-descriptor-len mp4-file))
  360. (end-of-atom (+ (stream-seek mp4-file) len)))
  361. (setf esid (stream-read-u16 mp4-file))
  362. (setf s-priority (stream-read-u8 mp4-file))
  363. (assert (= +MP4-DecConfigDescrTag+ (stream-read-u8 mp4-file)) () "Expected tag type of DecConfigDescrTag")
  364. (setf len (read-descriptor-len mp4-file))
  365. (setf obj-id (stream-read-u8 mp4-file))
  366. (setf s-type (stream-read-u8 mp4-file))
  367. (setf buf-size (stream-read-u24 mp4-file))
  368. (setf max-bit-rate (stream-read-u32 mp4-file))
  369. (setf avg-bit-rate (stream-read-u32 mp4-file))
  370. ;; XXX should do checking here and/or read rest of atom,
  371. ;; but for now, we have what we want, so just seek to end of atom
  372. (stream-seek mp4-file end-of-atom :start))))
  373. (defclass atom-stsd (mp4-atom)
  374. ((flags :accessor flags)
  375. (version :accessor version)
  376. (num-entries :accessor num-entries)))
  377. (defmethod initialize-instance :after ((me atom-stsd) &key (mp4-file nil) &allow-other-keys)
  378. (declare #.utils:*standard-optimize-settings*)
  379. (log5:with-context "atom-stsd"
  380. (with-slots (flags version num-entries) me
  381. (setf version (stream-read-u8 mp4-file))
  382. (setf flags (stream-read-u24 mp4-file))
  383. (setf num-entries (stream-read-u32 mp4-file))
  384. (log-mp4-atom "atom-stsd: version = ~d, flags = ~x, num-fields = ~d" version flags num-entries))))
  385. (defclass atom-mp4a (mp4-atom)
  386. ((reserved :accessor reserved) ; 6 bytes
  387. (d-ref-idx :accessor d-ref-idx) ; 2 bytes
  388. (version :accessor version) ; 2 bytes
  389. (revision :accessor revision) ; 2 bytes
  390. (vendor :accessor vendor) ; 4 bytes
  391. (num-chans :accessor num-chans) ; 2 bytes
  392. (samp-size :accessor samp-size) ; 2 bytes
  393. (comp-id :accessor comp-id) ; 2 bytes
  394. (packet-size :accessor packet-size) ; 2 bytes
  395. (samp-rate :accessor samp-rate))) ; 4 bytes
  396. (defmethod initialize-instance :after ((me atom-mp4a) &key (mp4-file nil) &allow-other-keys)
  397. (declare #.utils:*standard-optimize-settings*)
  398. (log5:with-context "atom-mp4a"
  399. (with-slots (reserved d-ref-idx version revision vendor num-chans samp-size comp-id packet-size samp-rate) me
  400. (setf reserved (stream-read-sequence mp4-file 6))
  401. (setf d-ref-idx (stream-read-u16 mp4-file))
  402. (setf version (stream-read-u16 mp4-file))
  403. (setf revision (stream-read-u16 mp4-file))
  404. (setf vendor (stream-read-u32 mp4-file))
  405. (setf num-chans (stream-read-u16 mp4-file))
  406. (setf samp-size (stream-read-u16 mp4-file))
  407. (setf comp-id (stream-read-u16 mp4-file))
  408. (setf packet-size (stream-read-u16 mp4-file))
  409. (setf samp-rate (stream-read-u32 mp4-file)) ; fixed 16.16 floating point number
  410. (read-container-atoms mp4-file me))))
  411. (defun read-container-atoms (mp4-file parent-atom)
  412. "Loop through a container atom and add it's children to it"
  413. (declare #.utils:*standard-optimize-settings*)
  414. (with-slots (atom-children atom-file-position atom-of-interest atom-size atom-type atom-decoded) parent-atom
  415. (atom-read-loop mp4-file (+ atom-file-position atom-size)
  416. (lambda ()
  417. (let ((child (make-mp4-atom mp4-file atom-type)))
  418. (log-mp4-atom "read-container-atoms: adding new child ~a" (vpprint child nil))
  419. (addc parent-atom child))))))
  420. (defclass atom-meta (mp4-atom)
  421. ((version :accessor version)
  422. (flags :accessor flags)))
  423. (defmethod initialize-instance :after ((me atom-meta) &key (mp4-file nil) &allow-other-keys)
  424. (declare #.utils:*standard-optimize-settings*)
  425. (with-slots (version flags) me
  426. (setf version (stream-read-u8 mp4-file))
  427. (setf flags (stream-read-u24 mp4-file))
  428. (read-container-atoms mp4-file me)))
  429. (defun find-atom-class (id)
  430. "Search by concatenating 'atom-' with ID and look for that symbol in this package"
  431. (declare #.utils:*standard-optimize-settings*)
  432. (log5:with-context "find-atom-class"
  433. (log-mp4-atom "find-atom-class: looking for class <~a>" (as-string id))
  434. (let ((found-class-symbol (find-symbol (mk-atom-class-name id) :MP4-ATOM))
  435. (found-class))
  436. ;; if we found the class name, return the class (to be used for MAKE-INSTANCE)
  437. (when found-class-symbol
  438. (setf found-class (find-class found-class-symbol))
  439. (log-mp4-atom "find-atom-class: found class: ~a" found-class)
  440. (return-from find-atom-class (find-class found-class-symbol))))
  441. ;; didn't find a class, so return ATOM-SKIP class
  442. (log-mp4-atom "find-atom-class: class not found")
  443. 'atom-skip))
  444. (defun make-mp4-atom (mp4-file &optional parent-type)
  445. "Get current file position, read in size/type, then construct the correct atom."
  446. (declare #.utils:*standard-optimize-settings*)
  447. (log5:with-context "make-mp4-atom"
  448. (let* ((pos (stream-seek mp4-file))
  449. (siz (stream-read-u32 mp4-file))
  450. (typ (stream-read-u32 mp4-file))
  451. (atom))
  452. (declare (type integer pos siz typ))
  453. (log-mp4-atom "make-mp4-atom: @ pos = ~:d of size = ~:d and type = ~a" pos siz (as-string typ))
  454. (when (= 0 siz)
  455. (error "trying to make an atom ~a with size of 0 at offset ~:d in file ~a"
  456. (as-string typ) pos (stream-filename mp4-file)))
  457. (setf atom (make-instance (find-atom-class typ) :atom-size siz :atom-type typ :atom-file-position pos :mp4-file mp4-file :atom-parent-type parent-type))
  458. (log-mp4-atom "make-mp4-atom: made ~a" (vpprint atom nil))
  459. atom)))
  460. (defmethod vpprint ((me mp4-atom) stream)
  461. (format stream "~a" (with-output-to-string (s)
  462. (with-slots (atom-children atom-file-position atom-size atom-type) me
  463. (format s "ATOM: type: <~a> @ ~:d of size ~:d and child count of ~d"
  464. (as-string atom-type) atom-file-position atom-size (length atom-children)))
  465. (if (typep me 'atom-data)
  466. (with-slots (atom-version atom-flags atom-value atom-type atom-parent-type) me
  467. (format s " having ilst fields: atom-parent-type = ~a, verison = ~d, flags = ~x, data = ~x"
  468. (as-string atom-parent-type) atom-version atom-flags
  469. (if (typep atom-value 'array) (printable-array atom-value) atom-value)))))))
  470. (defun is-valid-m4-file (mp4-file)
  471. "Make sure this is an MP4 file. Quick check: is first atom (at file-offset 4) == FSTYP?
  472. Written in this fashion so as to be 'crash-proof' when passed an arbitrary file."
  473. (declare #.utils:*standard-optimize-settings*)
  474. (let ((valid)
  475. (size)
  476. (header))
  477. (when (> (stream-size mp4-file) 8)
  478. (unwind-protect
  479. (handler-case
  480. (progn
  481. (stream-seek mp4-file 0 :start)
  482. (setf size (stream-read-u32 mp4-file))
  483. (setf header (stream-read-u32 mp4-file))
  484. (setf valid (and (<= size (stream-size mp4-file))
  485. (= header +m4-ftyp+))))
  486. (condition (c)
  487. (utils:warn-user "File:~a~%is-valid-mp4-file got condition ~a" (stream-filename mp4-file) c)))
  488. (stream-seek mp4-file 0 :start)))
  489. valid))
  490. (defmethod find-mp4-atoms ((mp4-file mp4-file-stream))
  491. "Given a valid MP4 file MP4-FILE, look for the 'right' atoms and return them."
  492. (declare #.utils:*standard-optimize-settings*)
  493. (log5:with-context "find-mp4-atoms"
  494. (log-mp4-atom "find-mp4-atoms: ~a, before read-file loop, file-position = ~:d, end = ~:d"
  495. (stream-filename mp4-file) (stream-seek mp4-file) (stream-size mp4-file))
  496. (let ((atoms))
  497. (atom-read-loop mp4-file (stream-size mp4-file)
  498. (lambda ()
  499. (let ((new-atom (make-mp4-atom mp4-file)))
  500. (when new-atom
  501. (push new-atom atoms)))))
  502. (setf (mp4-atoms mp4-file) (nreverse atoms))) ; preserve in-file-order
  503. (log-mp4-atom "find-mp4-atoms: returning list of size ~d" (length (mp4-atoms mp4-file)))))
  504. (defmethod map-mp4-atom ((atoms list) &key (func nil) (depth nil))
  505. "Given a list of atoms, call map-mp4-atom for each one"
  506. (declare #.utils:*standard-optimize-settings*)
  507. (log5:with-context "map-mp4-atom"
  508. (dolist (a atoms)
  509. (map-mp4-atom a :func func :depth depth))))
  510. (defmethod map-mp4-atom ((me mp4-atom) &key (func nil) (depth nil))
  511. "Traverse all atoms under a given atom"
  512. (declare #.utils:*standard-optimize-settings*)
  513. (log5:with-context "map-mp4-atom(single)"
  514. (labels ((_indented-atom (atom depth)
  515. (format t "~vt~a~%" (if (null depth) 0 depth) (vpprint atom nil))))
  516. (with-slots (atom-type atom-children) me
  517. (log-mp4-atom "map-mp4-atom: begining traversal with ~a, I have ~d children" (as-string atom-type) (length atom-children))
  518. (when (null func)
  519. (setf func #'_indented-atom))
  520. (funcall func me depth)
  521. (map-mp4-atom atom-children :func func :depth (if (null depth) nil (+ 1 depth)))))))
  522. (defmethod traverse ((me mp4-atom) path)
  523. (declare #.utils:*standard-optimize-settings*)
  524. (traverse (atom-children me) path))
  525. (defmethod traverse ((me list) path)
  526. "Used in finding nested atoms. Search MP4-ATOMS and if we find a match with first of path,
  527. call traverse atom (unless length of path == 1, in which case, we've found our match)"
  528. (declare #.utils:*standard-optimize-settings*)
  529. (log5:with-context "traverse"
  530. (log-mp4-atom "traverse: entering with ~a ~a" me path)
  531. (dolist (sibling me)
  532. (with-slots (atom-type atom-children) sibling
  533. (log-mp4-atom "traverse: comparing ~a to ~a" (as-string atom-type) (as-string (first path)))
  534. (when (= atom-type (first path))
  535. (cond
  536. ((= 1 (length path))
  537. (log-mp4-atom "traverse: matched: ~a" sibling)
  538. (return-from traverse sibling))
  539. (t
  540. (log-mp4-atom "traverse: path matches, recursing")
  541. (let ((found (traverse atom-children (rest path))))
  542. (if found (return-from traverse found))))))))
  543. (log-mp4-atom "traverse: ~a not found" path)
  544. nil))
  545. (defmethod tag-get-value (atoms node)
  546. "Helper function to extract text from ILST atom's data atom"
  547. (declare #.utils:*standard-optimize-settings*)
  548. (aif (traverse atoms
  549. (list +mp4-atom-moov+ +mp4-atom-udta+ +mp4-atom-meta+ +mp4-atom-ilst+ node +itunes-ilst-data+))
  550. (atom-value it)
  551. nil))
  552. (defun mp4-show-raw-tag-atoms (mp4-file-stream out-stream)
  553. (declare #.utils:*standard-optimize-settings*)
  554. (map-mp4-atom (traverse (mp4-atoms mp4-file-stream)
  555. (list +mp4-atom-moov+ +mp4-atom-udta+ +mp4-atom-meta+ +mp4-atom-ilst+))
  556. :depth 0
  557. :func (lambda (atom depth)
  558. (when (= (atom-type atom) +itunes-ilst-data+)
  559. (format out-stream "~vt~a~%" depth (vpprint atom nil))))))
  560. (defun find-all (base name)
  561. "Starting as BASE atom, recursively search for all instances of NAME"
  562. (declare #.utils:*standard-optimize-settings*)
  563. (let* ((search-name (if (typep name 'string) (as-int name) name))
  564. (found))
  565. (map-mp4-atom base
  566. :func (lambda (atom depth)
  567. (declare (ignore depth))
  568. (when (= (atom-type atom) search-name)
  569. (push atom found))))
  570. (nreverse found)))
  571. (defun get-audio-properties-atoms (mp4-file)
  572. "First, find all TRAKs under moov. For the one that contains a HDLR atom with DATA of 'soun',
  573. return trak.mdia.mdhd and trak.mdia.minf.stbl.stsd"
  574. (declare #.utils:*standard-optimize-settings*)
  575. (dolist (track (find-all (traverse (mp4-atoms mp4-file) (list +mp4-atom-moov+)) "trak"))
  576. (let ((hdlr (traverse track (list +mp4-atom-mdia+ +audioprop-hdlr+))))
  577. (when (and (not (null hdlr))
  578. (not (null (mtype hdlr)))
  579. (string= "soun" (as-string (mtype hdlr))))
  580. ;; we've found the correct track, extract atoms
  581. (return-from get-audio-properties-atoms (values (traverse track (list +mp4-atom-mdia+ +audioprop-mdhd+))
  582. (traverse track (list +mp4-atom-mdia+ +mp4-atom-minf+ +mp4-atom-stbl+ +audioprop-mp4a+))
  583. (traverse track (list +mp4-atom-mdia+ +mp4-atom-minf+ +mp4-atom-stbl+ +audioprop-mp4a+ +audioprop-esds+)))))))
  584. nil)
  585. (defclass audio-info ()
  586. ((seconds :accessor seconds :initform nil)
  587. (channels :accessor channels :initform nil)
  588. (bits-per-sample :accessor bits-per-sample :initform nil)
  589. (sample-rate :accessor sample-rate :initform nil)
  590. (max-bit-rate :accessor max-bit-rate :initform nil)
  591. (avg-bit-rate :accessor avg-bit-rate :initform nil))
  592. (:documentation "Holds extracted audio information about an MP4 file."))
  593. (defmethod vpprint ((me audio-info) stream)
  594. (with-slots (seconds channels bits-per-sample sample-rate max-bit-rate avg-bit-rate) me
  595. (format stream "sample rate: ~:d Hz, # channels: ~d, bits-per-sample: ~:d, max bit-rate: ~:d Kbps, avg bit-rate: ~:d Kbps, duration: ~:d:~2,'0d"
  596. (if sample-rate sample-rate 0)
  597. (if channels channels 0)
  598. (if bits-per-sample bits-per-sample 0)
  599. (if max-bit-rate (round (/ max-bit-rate 1000)) 0)
  600. (if avg-bit-rate (round (/ avg-bit-rate 1000)) 0)
  601. (if seconds (floor (/ seconds 60)) 0)
  602. (if seconds (round (mod seconds 60)) 0))))
  603. (defun get-mp4-audio-info (mp4-file)
  604. "MP4A audio info is held in under the trak.mdia.mdhd/trak.mdia.minf.stbl/trak.mdia.minf.stbl.mp4a atoms."
  605. (declare #.utils:*standard-optimize-settings*)
  606. (let ((info (make-instance 'audio-info)))
  607. (multiple-value-bind (mdhd mp4a esds) (get-audio-properties-atoms mp4-file)
  608. (with-slots (seconds channels bits-per-sample sample-rate max-bit-rate avg-bit-rate) info
  609. (when mdhd
  610. (setf seconds (/ (float (duration mdhd)) (float (scale mdhd)))))
  611. (when mp4a
  612. (setf channels (num-chans mp4a))
  613. (setf bits-per-sample (samp-size mp4a))
  614. (let* ((upper (ash (samp-rate mp4a) -16))
  615. (lower (logand (samp-rate mp4a) #xffff)))
  616. (setf sample-rate (+ (float upper) (/ (float lower) 1000))))
  617. (when esds
  618. (setf avg-bit-rate (avg-bit-rate esds))
  619. (setf max-bit-rate (max-bit-rate esds))))))
  620. info))