audio-streams.lisp 18 KB

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