audio-streams.lisp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. ;;; -*- Mode: Lisp; show-trailing-whitespace: t; Base: 10; indent-tabs: nil; Syntax: ANSI-Common-Lisp; Package: AUDIO-STREAMS; -*-
  2. ;;; Copyright (c) 2013, Mark VandenBrink. All rights reserved.
  3. (in-package #:audio-streams)
  4. (log5:defcategory cat-log-stream)
  5. (defmacro log-stream (&rest log-stuff) `(log5:log-for (cat-log-stream) ,@log-stuff))
  6. (deftype octet () '(unsigned-byte 8))
  7. (defmacro make-octets (len) `(make-array ,len :element-type 'octet))
  8. (defclass mem-stream ()
  9. ((stream-filename :accessor stream-filename :initform nil :initarg :stream-filename :documentation "if set, then MMAP file")
  10. (index :accessor index :initform 0)
  11. (stream-size :accessor stream-size :initform 0)
  12. (vect :accessor vect :initform nil :initarg :vect :documentation "if set, then the vector we want STREAM-ize"))
  13. (:documentation "A thin-wrapper class over mmaped-files and/or vectors."))
  14. (defmacro with-mem-stream-slots ((instance) &body body)
  15. `(with-slots (stream-filename index stream-size vect) ,instance
  16. (declare (integer index stream-size)
  17. (type (array (unsigned-byte 8) 1) vect))
  18. ,@body))
  19. (defun make-mem-stream (v) (make-instance 'mem-stream :vect v))
  20. (defun make-mmap-stream (f) (make-instance 'mem-stream :stream-filename f))
  21. (defmethod initialize-instance :after ((stream mem-stream) &key)
  22. "Stream initializer. If STREAM-FILENAME is set, MMAP a the file. Else, we assume VECT was set."
  23. (with-mem-stream-slots (stream)
  24. (when stream-filename
  25. #+CCL (setf vect (ccl:map-file-to-octet-vector stream-filename))
  26. #-CCL (error "Not Yet!")
  27. )
  28. (setf stream-size (length vect))))
  29. (defmethod stream-close ((stream mem-stream))
  30. "Close a stream, making the underlying object (file or vector) inaccessible."
  31. (declare #.utils:*standard-optimize-settings*)
  32. (with-mem-stream-slots (stream)
  33. (when stream-filename
  34. #+CCL (ccl:unmap-octet-vector vect)
  35. #-CCL (error "Not Yet")
  36. )
  37. (setf vect nil)))
  38. (defmethod stream-seek ((stream mem-stream) &optional (offset 0) (from :current))
  39. "Set INDEX to requested value. No error checking done here, but subsequent reads will fail if INDEX is out-of-bounds.
  40. As a convenience, OFFSET and FROM are optional, so (STREAM-SEEK stream) returns the current read-offset in stream."
  41. (declare #.utils:*standard-optimize-settings*)
  42. (with-mem-stream-slots (stream)
  43. (ecase from
  44. (:start ; INDEX set to OFFSET from start of stream
  45. (setf index offset))
  46. (:current ; INDEX set relative to current INDEX, by OFFSET bytes
  47. (if (zerop offset)
  48. index
  49. (incf index offset)))
  50. (:end ; INDEX set to OFFSET from end of stream
  51. (setf index (- stream-size offset))))))
  52. (declaim (inline read-n-bytes))
  53. (defun read-n-bytes (stream n-bytes &key (bits-per-byte 8) (endian :little-endian))
  54. "Returns a FIXNUM constructed by reading N-BYTES. BITS-PER-BYTE contols how many bits should be used from each read byte."
  55. (declare #.utils:*standard-optimize-settings*)
  56. (with-mem-stream-slots (stream)
  57. (when (<= (+ index n-bytes) stream-size)
  58. (ecase endian
  59. (:little-endian
  60. (loop with value = 0
  61. for low-bit downfrom (* bits-per-byte (1- n-bytes)) to 0 by bits-per-byte do
  62. (setf (ldb (byte bits-per-byte low-bit) value) (aref vect index))
  63. (incf index)
  64. finally (return-from read-n-bytes value)))
  65. (:big-endian
  66. (loop with value = 0
  67. for low-bit upfrom 0 to (* bits-per-byte (1- n-bytes)) by bits-per-byte do
  68. (setf (ldb (byte bits-per-byte low-bit) value) (aref vect index))
  69. (incf index)
  70. finally (return-from read-n-bytes value))))))
  71. nil)
  72. (defmethod stream-read-u8 ((stream mem-stream) &key (bits-per-byte 8)) (read-n-bytes stream 1 :bits-per-byte bits-per-byte))
  73. (defmethod stream-read-u16 ((stream mem-stream) &key (bits-per-byte 8) (endian :little-endian)) (read-n-bytes stream 2 :bits-per-byte bits-per-byte :endian endian))
  74. (defmethod stream-read-u24 ((stream mem-stream) &key (bits-per-byte 8) (endian :little-endian)) (read-n-bytes stream 3 :bits-per-byte bits-per-byte :endian endian))
  75. (defmethod stream-read-u32 ((stream mem-stream) &key (bits-per-byte 8) (endian :little-endian)) (read-n-bytes stream 4 :bits-per-byte bits-per-byte :endian endian))
  76. (defmethod stream-read-u64 ((stream mem-stream) &key (bits-per-byte 8) (endian :little-endian)) (read-n-bytes stream 8 :bits-per-byte bits-per-byte :endian endian))
  77. (defmethod stream-read-u128 ((stream mem-stream) &key (bits-per-byte 8) (endian :little-endian)) (read-n-bytes stream 16 :bits-per-byte bits-per-byte :endian endian))
  78. (defmethod stream-read-sequence ((stream mem-stream) size &key (bits-per-byte 8))
  79. "Read in a sequence of octets at BITS-PER-BYTE. If BITS-PER-BYTE == 8, then simply return
  80. a displaced array from STREAMs underlying vector. If it is == 7, then we have to create a new vector and read into that."
  81. (declare #.utils:*standard-optimize-settings*)
  82. (with-mem-stream-slots (stream)
  83. (when (> (+ index size) stream-size)
  84. (setf size (- stream-size index)))
  85. (ecase bits-per-byte
  86. (8 (let ((octets (make-array size :element-type 'octet :displaced-to vect :displaced-index-offset index :adjustable nil)))
  87. (incf index size)
  88. (values octets size)))
  89. (7
  90. (let* ((last-byte-was-FF nil)
  91. (byte nil)
  92. (octets
  93. #-CCL (error "Not yet")
  94. #+CCL (ccl:with-output-to-vector (out)
  95. (dotimes (i size)
  96. (setf byte (stream-read-u8 stream))
  97. (if last-byte-was-FF
  98. (if (not (zerop byte))
  99. (write-byte byte out))
  100. (write-byte byte out))
  101. (setf last-byte-was-FF (= byte #xFF))))
  102. ))
  103. (values octets size))))))
  104. (defclass mp3-file-stream (mem-stream)
  105. ((id3-header :accessor id3-header :initform nil :documentation "holds all the ID3 info")
  106. (audio-info :accessor audio-info :initform nil :documentation "holds the bit-rate, etc info"))
  107. (:documentation "Stream for parsing MP3 files"))
  108. (defclass mp4-file-stream (mem-stream)
  109. ((mp4-atoms :accessor mp4-atoms :initform nil :documentation "holds tree of parsed MP4 atoms/boxes")
  110. (audio-info :accessor audio-info :initform nil :documentation "holds the bit-rate, etc info"))
  111. (:documentation "Stream for parsing MP4 audio files"))
  112. (defclass flac-file-stream (mem-stream)
  113. ((flac-headers :accessor flac-headers :initform nil :documentation "holds all the flac headers in file")
  114. (audio-info :accessor audio-info :initform nil :documentation "parsed audio info")
  115. (flac-tags :accessor flac-tags :initform nil :documentation "parsed comment tags."))
  116. (:documentation "Stream for parsing flac files"))
  117. (defun make-file-stream (filename)
  118. "Convenience function for creating a file stream. Detects file type and returns proper type stream."
  119. (declare #.utils:*standard-optimize-settings*)
  120. (log5:with-context "make-file-stream"
  121. (let* ((new-stream (make-mmap-stream filename))
  122. (ret-stream))
  123. (log-stream "Looking at ~a" filename)
  124. ;; detect file type and make RET-STREAM. if we don't recognize stream, RET-STREAM will be NULL
  125. (cond ((mp4-atom:is-valid-m4-file new-stream)
  126. (log-stream "~a is an MP4 file" filename)
  127. (setf ret-stream (make-instance 'mp4-file-stream :vect (vect new-stream) :stream-filename (stream-filename new-stream))))
  128. ((flac-frame:is-valid-flac-file new-stream)
  129. (log-stream "~a is a FLAC file" filename)
  130. (setf ret-stream (make-instance 'flac-file-stream :vect (vect new-stream) :stream-filename (stream-filename new-stream))))
  131. ((id3-frame:is-valid-mp3-file new-stream)
  132. (log-stream "~a is an ID3 file" filename)
  133. (setf ret-stream (make-instance 'mp3-file-stream :vect (vect new-stream) :stream-filename (stream-filename new-stream))))
  134. (t
  135. (log-stream "Unkown file type")))
  136. (stream-close new-stream)
  137. ret-stream)))
  138. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Strings ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  139. ;;; Decode octets as an iso-8859-1 string (encoding == 0)
  140. (defun stream-decode-iso-string (octets &key (start 0) (end nil))
  141. (declare #.utils:*standard-optimize-settings*)
  142. #+CCL (ccl:decode-string-from-octets octets :start start :end end :external-format :iso-8859-1)
  143. #-CCL (error "Not Yet")
  144. )
  145. ;;;
  146. ;;; XXX: Coded this way because I can't seem to get a simple :external-format :ucs-2 to work correctly
  147. ;;; AND some taggers encode a UCS-2 empty string w/o a byte-order mark (i.e. null strings are
  148. ;;; sometimes encoded as #(00 00))
  149. (defun stream-decode-ucs-string (octets &key (start 0) (end nil))
  150. "Decode octets as a UCS string with a BOM (encoding == 1)"
  151. (declare #.utils:*standard-optimize-settings*)
  152. (labels ((get-byte-order-mark (octets)
  153. (let ((retval 0))
  154. (setf (ldb (byte 8 0) retval) (aref octets 1)
  155. (ldb (byte 8 8) retval) (aref octets 0))
  156. (when (not (or (= #xfffe retval) (= #xfeff retval)))
  157. (error "Got invalid byte-order mark of ~x in STREAM-DECODE-UCS-STRING" retval))
  158. retval)))
  159. ;; special case: empty (and mis-coded) string
  160. (cond ((zerop (length octets))
  161. (make-string 0))
  162. (t
  163. ;;
  164. ;; else, we have a (hopefully) properly encoded string
  165. (let ((bom (get-byte-order-mark octets)))
  166. (ecase (the fixnum bom)
  167. (#xfffe #+CCL (ccl:decode-string-from-octets octets :start (+ 2 start) :end end :external-format :ucs-2le)
  168. #-CCL (error "Not Yet")
  169. )
  170. (#xfeff #+CCL (ccl:decode-string-from-octets octets :start (+ 2 start) :end end :external-format :ucs-2be)
  171. #-CCL (error "Not Yet")
  172. )
  173. (0 (make-string 0))))))))
  174. (defun stream-decode-ucs-be-string (octets &key (start 0) (end nil))
  175. "Decode octets as a UCS-BE string (encoding == 2)"
  176. (declare #.utils:*standard-optimize-settings*)
  177. #+CCL (ccl:decode-string-from-octets octets :start start :end end :external-format :ucs-2be)
  178. #-CCL (error "Not Yet")
  179. )
  180. (defun stream-decode-utf-8-string (octets &key (start 0) (end nil))
  181. "Decode octets as a utf-8 string"
  182. (declare #.utils:*standard-optimize-settings*)
  183. #+CCL (ccl:decode-string-from-octets octets :start start :end end :external-format :utf-8)
  184. #-CCL (error "Not Yet")
  185. )
  186. (defun stream-decode-string (octets &key (start 0) (end nil) (encoding 0))
  187. "Decode octets depending on encoding"
  188. (declare #.utils:*standard-optimize-settings*)
  189. (ecase encoding
  190. (0 (stream-decode-iso-string octets :start start :end end))
  191. (1 (stream-decode-ucs-string octets :start start :end end))
  192. (2 (stream-decode-ucs-be-string octets :start start :end end))
  193. (3 (stream-decode-utf-8-string octets :start start :end end))))
  194. (defmethod stream-read-iso-string-with-len ((instream mem-stream) len)
  195. "Read an iso-8859-1 string of length 'len' (encoding = 0)"
  196. (declare #.utils:*standard-optimize-settings*)
  197. (stream-decode-iso-string (stream-read-sequence instream len)))
  198. (defmethod stream-read-ucs-string-with-len ((instream mem-stream) len)
  199. "Read an ucs-2 string of length 'len' (encoding = 1)"
  200. (declare #.utils:*standard-optimize-settings*)
  201. (stream-decode-ucs-string (stream-read-sequence instream len)))
  202. (defmethod stream-read-ucs-be-string-with-len ((instream mem-stream) len)
  203. "Read an ucs-2-be string of length 'len' (encoding = 2)"
  204. (declare #.utils:*standard-optimize-settings*)
  205. (stream-decode-ucs-be-string (stream-read-sequence instream len)))
  206. (defmethod stream-read-utf-8-string-with-len ((instream mem-stream) len)
  207. "Read an utf-8 string of length 'len' (encoding = 3)"
  208. (declare #.utils:*standard-optimize-settings*)
  209. (stream-decode-utf-8-string (stream-read-sequence instream len)))
  210. (defmethod stream-read-string-with-len ((instream mem-stream) len &key (encoding 0))
  211. "Read in a string of a given encoding of length 'len'"
  212. (declare #.utils:*standard-optimize-settings*)
  213. (ecase encoding
  214. (0 (stream-read-iso-string-with-len instream len))
  215. (1 (stream-read-ucs-string-with-len instream len))
  216. (2 (stream-read-ucs-be-string-with-len instream len))
  217. (3 (stream-read-utf-8-string-with-len instream len))))
  218. (defmethod stream-read-iso-string ((instream mem-stream))
  219. "Read in a null terminated iso-8859-1 string"
  220. (declare #.utils:*standard-optimize-settings*)
  221. (let ((octets #+CCL (ccl:with-output-to-vector (out)
  222. (do ((b (stream-read-u8 instream) (stream-read-u8 instream)))
  223. (nil)
  224. (when (zerop b)
  225. (return)) ; leave loop w/o writing
  226. (write-byte b out)))
  227. #-CCL (error "Not Yet")
  228. ))
  229. (stream-decode-iso-string octets)))
  230. (defmethod stream-read-ucs-string ((instream mem-stream))
  231. "Read in a null terminated UCS string."
  232. (declare #.utils:*standard-optimize-settings*)
  233. (let ((octets #+CCL (ccl:with-output-to-vector (out)
  234. (do* ((b0 (stream-read-u8 instream)
  235. (stream-read-u8 instream))
  236. (b1 (stream-read-u8 instream)
  237. (stream-read-u8 instream)))
  238. (nil)
  239. (when (and (zerop b0) (zerop b1))
  240. (return))
  241. (write-byte b0 out)
  242. (write-byte b1 out)))
  243. #-CCL (error "Not Yet")
  244. ))
  245. (stream-decode-ucs-string octets)))
  246. (defmethod stream-read-ucs-be-string ((instream mem-stream))
  247. "Read in a null terminated UCS-BE string."
  248. (declare #.utils:*standard-optimize-settings*)
  249. (let ((octets #+CCL (ccl:with-output-to-vector (out)
  250. (do* ((b0 (stream-read-u8 instream)
  251. (stream-read-u8 instream))
  252. (b1 (stream-read-u8 instream)
  253. (stream-read-u8 instream)))
  254. (nil)
  255. (when (and (zerop b0) (zerop b1))
  256. (return))
  257. (write-byte b0 out)
  258. (write-byte b1 out)))
  259. #-CCL (error "Not Yet")
  260. ))
  261. (stream-decode-ucs-be-string octets)))
  262. (defmethod stream-read-utf-8-string ((instream mem-stream))
  263. "Read in a null terminated utf-8 string (encoding == 3)"
  264. (declare #.utils:*standard-optimize-settings*)
  265. (let ((octets #+CCL (ccl:with-output-to-vector (out)
  266. (do ((b (stream-read-u8 instream)
  267. (stream-read-u8 instream)))
  268. (nil)
  269. (when (zerop b)
  270. (return))
  271. (write-byte b out)))
  272. #-CCL (error "Not Yet")
  273. ))
  274. (stream-decode-utf-8-string octets)))
  275. (defmethod stream-read-string ((instream mem-stream) &key (encoding 0))
  276. "Read in a null terminated string of a given encoding."
  277. (declare #.utils:*standard-optimize-settings*)
  278. (ecase encoding
  279. (0 (stream-read-iso-string instream))
  280. (1 (stream-read-ucs-string instream))
  281. (2 (stream-read-ucs-be-string instream))
  282. (3 (stream-read-utf-8-string instream))))
  283. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Files ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  284. (defvar *get-audio-info* t "controls whether the parsing functions also parse audio info like bit-rate, etc")
  285. (defmethod parse-audio-file ((stream mp4-file-stream) &key (get-audio-info *get-audio-info*) &allow-other-keys)
  286. "Parse an MP4A file by reading it's ATOMS and decoding them."
  287. (declare #.utils:*standard-optimize-settings*)
  288. (handler-case
  289. (progn
  290. (mp4-atom:find-mp4-atoms stream)
  291. (when get-audio-info
  292. (setf (audio-info stream) (mp4-atom:get-mp4-audio-info stream))))
  293. (condition (c)
  294. (utils:warn-user "make-mp4-stream got condition: ~a" c))))
  295. (defmethod parse-audio-file ((stream flac-file-stream) &key (get-audio-info *get-audio-info*) &allow-other-keys)
  296. "Parse a flac file by reading it's headers and decoding them."
  297. (declare #.utils:*standard-optimize-settings*)
  298. (declare (ignore get-audio-info)) ; audio info comes for "free" by parsing headers
  299. (handler-case
  300. (flac-frame:find-flac-frames stream)
  301. (condition (c)
  302. (utils:warn-user "make-flac-stream got condition: ~a" c))))
  303. (defmethod parse-audio-file ((stream mp3-file-stream) &key (get-audio-info *get-audio-info*) &allow-other-keys)
  304. "Parse an MP3 file by reading it's FRAMES and decoding them."
  305. (declare #.utils:*standard-optimize-settings*)
  306. (handler-case
  307. (progn
  308. (id3-frame:find-id3-frames stream)
  309. (when get-audio-info
  310. (setf (audio-info stream) (mpeg:get-mpeg-audio-info stream))))
  311. (condition (c)
  312. (utils:warn-user "make-mp3-stream got condition: ~a" c))))