audio-streams.lisp 17 KB

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