mp4-atom.lisp 32 KB

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