mp4-atom.lisp 32 KB

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