mp4-atom.lisp 27 KB

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