mp4-atom.lisp 29 KB

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