audio-streams.lisp 17 KB

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