audio_stream.h 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. /*
  2. * This file is part of the FreeStreamer project,
  3. * (C)Copyright 2011-2018 Matias Muhonen <mmu@iki.fi> 穆马帝
  4. * See the file ''LICENSE'' for using the code.
  5. *
  6. * https://github.com/muhku/FreeStreamer
  7. */
  8. #ifndef ASTREAMER_AUDIO_STREAM_H
  9. #define ASTREAMER_AUDIO_STREAM_H
  10. #import "input_stream.h"
  11. #include "audio_queue.h"
  12. #include <AudioToolbox/AudioToolbox.h>
  13. #include <list>
  14. namespace astreamer {
  15. typedef struct queued_packet {
  16. UInt64 identifier;
  17. AudioStreamPacketDescription desc;
  18. struct queued_packet *next;
  19. char data[];
  20. } queued_packet_t;
  21. typedef struct {
  22. float offset;
  23. float timePlayed;
  24. } AS_Playback_Position;
  25. enum Audio_Stream_Error {
  26. AS_ERR_OPEN = 1, // Cannot open the audio stream
  27. AS_ERR_STREAM_PARSE = 2, // Parse error
  28. AS_ERR_NETWORK = 3, // Network error
  29. AS_ERR_UNSUPPORTED_FORMAT = 4,
  30. AS_ERR_BOUNCING = 5,
  31. AS_ERR_TERMINATED = 6
  32. };
  33. class Audio_Stream_Delegate;
  34. class File_Output;
  35. #define kAudioStreamBitrateBufferSize 50
  36. class Audio_Stream : public Input_Stream_Delegate, public Audio_Queue_Delegate {
  37. public:
  38. Audio_Stream_Delegate *m_delegate;
  39. enum State {
  40. STOPPED,
  41. BUFFERING,
  42. PLAYING,
  43. PAUSED,
  44. SEEKING,
  45. FAILED,
  46. END_OF_FILE,
  47. PLAYBACK_COMPLETED
  48. };
  49. Audio_Stream();
  50. virtual ~Audio_Stream();
  51. void open();
  52. void open(Input_Stream_Position *position);
  53. void close(bool closeParser);
  54. void pause();
  55. void rewind(unsigned seconds);
  56. void startCachedDataPlayback();
  57. AS_Playback_Position playbackPosition();
  58. UInt64 audioDataByteCount();
  59. float durationInSeconds();
  60. void seekToOffset(float offset);
  61. Input_Stream_Position streamPositionForOffset(float offset);
  62. float currentVolume();
  63. void setDecoderRunState(bool decoderShouldRun);
  64. void setVolume(float volume);
  65. void setPlayRate(float playRate);
  66. void setUrl(CFURLRef url);
  67. void setStrictContentTypeChecking(bool strictChecking);
  68. void setDefaultContentType(CFStringRef defaultContentType);
  69. void setSeekOffset(float offset);
  70. void setDefaultContentLength(UInt64 defaultContentLength);
  71. void setContentLength(UInt64 contentLength);
  72. void setPreloading(bool preloading);
  73. bool isPreloading();
  74. void setOutputFile(CFURLRef url);
  75. CFURLRef outputFile();
  76. State state();
  77. CFStringRef sourceFormatDescription();
  78. CFStringRef contentType();
  79. CFStringRef createCacheIdentifierForURL(CFURLRef url);
  80. size_t cachedDataSize();
  81. bool strictContentTypeChecking();
  82. float bitrate();
  83. UInt64 defaultContentLength();
  84. UInt64 contentLength();
  85. int playbackDataCount();
  86. AudioQueueLevelMeterState levels();
  87. /* Audio_Queue_Delegate */
  88. void audioQueueStateChanged(Audio_Queue::State state);
  89. void audioQueueBuffersEmpty();
  90. void audioQueueInitializationFailed();
  91. void audioQueueFinishedPlayingPacket();
  92. /* Input_Stream_Delegate */
  93. void streamIsReadyRead();
  94. void streamHasBytesAvailable(UInt8 *data, UInt32 numBytes);
  95. void streamEndEncountered();
  96. void streamErrorOccurred(CFStringRef errorDesc);
  97. void streamMetaDataAvailable(std::map<CFStringRef,CFStringRef> metaData);
  98. void streamMetaDataByteSizeAvailable(UInt32 sizeInBytes);
  99. private:
  100. Audio_Stream(const Audio_Stream&);
  101. Audio_Stream& operator=(const Audio_Stream&);
  102. bool m_inputStreamRunning;
  103. bool m_audioStreamParserRunning;
  104. bool m_initialBufferingCompleted;
  105. bool m_discontinuity;
  106. bool m_preloading;
  107. bool m_audioQueueConsumedPackets;
  108. UInt64 m_defaultContentLength;
  109. UInt64 m_contentLength;
  110. UInt64 m_originalContentLength;
  111. UInt64 m_bytesReceived;
  112. State m_state;
  113. Input_Stream *m_inputStream;
  114. Audio_Queue *m_audioQueue;
  115. CFRunLoopTimerRef m_watchdogTimer;
  116. CFRunLoopTimerRef m_seekTimer;
  117. CFRunLoopTimerRef m_inputStreamTimer;
  118. CFRunLoopTimerRef m_stateSetTimer;
  119. CFRunLoopTimerRef m_decodeTimer;
  120. AudioFileStreamID m_audioFileStream; // the audio file stream parser
  121. AudioConverterRef m_audioConverter;
  122. AudioStreamBasicDescription m_srcFormat;
  123. AudioStreamBasicDescription m_dstFormat;
  124. OSStatus m_initializationError;
  125. UInt32 m_outputBufferSize;
  126. UInt8 *m_outputBuffer;
  127. UInt64 m_packetIdentifier;
  128. UInt64 m_playingPacketIdentifier;
  129. UInt64 m_dataOffset;
  130. float m_seekOffset;
  131. size_t m_bounceCount;
  132. CFAbsoluteTime m_firstBufferingTime;
  133. bool m_strictContentTypeChecking;
  134. CFStringRef m_defaultContentType;
  135. CFStringRef m_contentType;
  136. File_Output *m_fileOutput;
  137. CFURLRef m_outputFile;
  138. queued_packet_t *m_queuedHead;
  139. queued_packet_t *m_queuedTail;
  140. queued_packet_t *m_playPacket;
  141. std::list <queued_packet_t*> m_processedPackets;
  142. unsigned m_numPacketsToRewind;
  143. size_t m_cachedDataSize;
  144. UInt64 m_audioDataByteCount;
  145. UInt64 m_audioDataPacketCount;
  146. UInt32 m_bitRate;
  147. UInt32 m_metaDataSizeInBytes;
  148. double m_packetDuration;
  149. double m_bitrateBuffer[kAudioStreamBitrateBufferSize];
  150. size_t m_bitrateBufferIndex;
  151. float m_outputVolume;
  152. bool m_converterRunOutOfData;
  153. bool m_decoderShouldRun;
  154. bool m_decoderFailed;
  155. bool m_decoderThreadCreated;
  156. pthread_mutex_t m_packetQueueMutex;
  157. pthread_mutex_t m_streamStateMutex;
  158. pthread_t m_decodeThread;
  159. CFRunLoopRef m_decodeRunLoop;
  160. CFRunLoopRef m_mainRunLoop;
  161. CFStringRef createHashForString(CFStringRef str);
  162. Audio_Queue *audioQueue();
  163. void closeAudioQueue();
  164. void closeAndSignalError(int error, CFStringRef errorDescription);
  165. void setState(State state);
  166. void setCookiesForStream(AudioFileStreamID inAudioFileStream);
  167. void createWatchdogTimer();
  168. void invalidateWatchdogTimer();
  169. int cachedDataCount();
  170. void determineBufferingLimits();
  171. void cleanupCachedData();
  172. static void watchdogTimerCallback(CFRunLoopTimerRef timer, void *info);
  173. static void seekTimerCallback(CFRunLoopTimerRef timer, void *info);
  174. static void inputStreamTimerCallback(CFRunLoopTimerRef timer, void *info);
  175. static void stateSetTimerCallback(CFRunLoopTimerRef timer, void *info);
  176. bool decoderShouldRun();
  177. static void decodeSinglePacket(CFRunLoopTimerRef timer, void *info);
  178. static void *decodeLoop(void *arg);
  179. static OSStatus encoderDataCallback(AudioConverterRef inAudioConverter, UInt32 *ioNumberDataPackets, AudioBufferList *ioData, AudioStreamPacketDescription **outDataPacketDescription, void *inUserData);
  180. static void propertyValueCallback(void *inClientData, AudioFileStreamID inAudioFileStream, AudioFileStreamPropertyID inPropertyID, UInt32 *ioFlags);
  181. static void streamDataCallback(void *inClientData, UInt32 inNumberBytes, UInt32 inNumberPackets, const void *inInputData, AudioStreamPacketDescription *inPacketDescriptions);
  182. AudioFileTypeID audioStreamTypeFromContentType(CFStringRef contentType);
  183. };
  184. class Audio_Stream_Delegate {
  185. public:
  186. virtual void audioStreamStateChanged(Audio_Stream::State state) = 0;
  187. virtual void audioStreamErrorOccurred(int errorCode, CFStringRef errorDescription) = 0;
  188. virtual void audioStreamMetaDataAvailable(std::map<CFStringRef,CFStringRef> metaData) = 0;
  189. virtual void samplesAvailable(AudioBufferList *samples, UInt32 frames, AudioStreamPacketDescription description) = 0;
  190. virtual void bitrateAvailable() = 0;
  191. };
  192. } // namespace astreamer
  193. #endif // ASTREAMER_AUDIO_STREAM_H