audio-streams.lisp 17 KB

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