Home | History | Annotate | Download | only in audio
      1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #ifndef MEDIA_AUDIO_AUDIO_OUTPUT_CONTROLLER_H_
      6 #define MEDIA_AUDIO_AUDIO_OUTPUT_CONTROLLER_H_
      7 
      8 #include "base/atomic_ref_count.h"
      9 #include "base/callback.h"
     10 #include "base/cancelable_callback.h"
     11 #include "base/memory/ref_counted.h"
     12 #include "media/audio/audio_io.h"
     13 #include "media/audio/audio_manager.h"
     14 #include "media/audio/audio_power_monitor.h"
     15 #include "media/audio/audio_source_diverter.h"
     16 #include "media/audio/simple_sources.h"
     17 #include "media/base/media_export.h"
     18 
     19 // An AudioOutputController controls an AudioOutputStream and provides data
     20 // to this output stream. It has an important function that it executes
     21 // audio operations like play, pause, stop, etc. on a separate thread,
     22 // namely the audio manager thread.
     23 //
     24 // All the public methods of AudioOutputController are non-blocking.
     25 // The actual operations are performed on the audio manager thread.
     26 //
     27 // Here is a state transition diagram for the AudioOutputController:
     28 //
     29 //   *[ Empty ]  -->  [ Created ]  -->  [ Playing ]  -------.
     30 //        |                |               |    ^           |
     31 //        |                |               |    |           |
     32 //        |                |               |    |           v
     33 //        |                |               |    `-----  [ Paused ]
     34 //        |                |               |                |
     35 //        |                v               v                |
     36 //        `----------->  [      Closed       ]  <-----------'
     37 //
     38 // * Initial state
     39 //
     40 // At any time after reaching the Created state but before Closed, the
     41 // AudioOutputController may be notified of a device change via
     42 // OnDeviceChange().  As the OnDeviceChange() is processed, state transitions
     43 // will occur, ultimately ending up in an equivalent pre-call state.  E.g., if
     44 // the state was Paused, the new state will be Created, since these states are
     45 // all functionally equivalent and require a Play() call to continue to the next
     46 // state.
     47 //
     48 // The AudioOutputStream can request data from the AudioOutputController via the
     49 // AudioSourceCallback interface. AudioOutputController uses the SyncReader
     50 // passed to it via construction to synchronously fulfill this read request.
     51 //
     52 
     53 namespace media {
     54 
     55 class MEDIA_EXPORT AudioOutputController
     56     : public base::RefCountedThreadSafe<AudioOutputController>,
     57       public AudioOutputStream::AudioSourceCallback,
     58       public AudioSourceDiverter,
     59       NON_EXPORTED_BASE(public AudioManager::AudioDeviceListener)  {
     60  public:
     61   // An event handler that receives events from the AudioOutputController. The
     62   // following methods are called on the audio manager thread.
     63   class MEDIA_EXPORT EventHandler {
     64    public:
     65     virtual void OnCreated() = 0;
     66     virtual void OnPlaying() = 0;
     67     virtual void OnPowerMeasured(float power_dbfs, bool clipped) = 0;
     68     virtual void OnPaused() = 0;
     69     virtual void OnError() = 0;
     70     virtual void OnDeviceChange(int new_buffer_size, int new_sample_rate) = 0;
     71 
     72    protected:
     73     virtual ~EventHandler() {}
     74   };
     75 
     76   // A synchronous reader interface used by AudioOutputController for
     77   // synchronous reading.
     78   // TODO(crogers): find a better name for this class and the Read() method
     79   // now that it can handle synchronized I/O.
     80   class SyncReader {
     81    public:
     82     virtual ~SyncReader() {}
     83 
     84     // Notify the synchronous reader the number of bytes in the
     85     // AudioOutputController not yet played. This is used by SyncReader to
     86     // prepare more data and perform synchronization.
     87     virtual void UpdatePendingBytes(uint32 bytes) = 0;
     88 
     89     // Attempt to completely fill |dest|, return the actual number of frames
     90     // that could be read.  |source| may optionally be provided for input data.
     91     // If |block| is specified, the Read() will block until data is available
     92     // or a timeout is reached.
     93     virtual int Read(bool block, const AudioBus* source, AudioBus* dest) = 0;
     94 
     95     // Close this synchronous reader.
     96     virtual void Close() = 0;
     97   };
     98 
     99   // Factory method for creating an AudioOutputController.
    100   // This also creates and opens an AudioOutputStream on the audio manager
    101   // thread, and if this is successful, the |event_handler| will receive an
    102   // OnCreated() call from the same audio manager thread.  |audio_manager| must
    103   // outlive AudioOutputController.
    104   static scoped_refptr<AudioOutputController> Create(
    105       AudioManager* audio_manager, EventHandler* event_handler,
    106       const AudioParameters& params, const std::string& input_device_id,
    107       SyncReader* sync_reader);
    108 
    109   // Methods to control playback of the stream.
    110 
    111   // Starts the playback of this audio output stream.
    112   void Play();
    113 
    114   // Pause this audio output stream.
    115   void Pause();
    116 
    117   // Closes the audio output stream. The state is changed and the resources
    118   // are freed on the audio manager thread. closed_task is executed after that.
    119   // Callbacks (EventHandler and SyncReader) must exist until closed_task is
    120   // called.
    121   //
    122   // It is safe to call this method more than once. Calls after the first one
    123   // will have no effect.
    124   void Close(const base::Closure& closed_task);
    125 
    126   // Sets the volume of the audio output stream.
    127   void SetVolume(double volume);
    128 
    129   // AudioSourceCallback implementation.
    130   virtual int OnMoreData(AudioBus* dest,
    131                          AudioBuffersState buffers_state) OVERRIDE;
    132   virtual int OnMoreIOData(AudioBus* source,
    133                            AudioBus* dest,
    134                            AudioBuffersState buffers_state) OVERRIDE;
    135   virtual void OnError(AudioOutputStream* stream) OVERRIDE;
    136 
    137   // AudioDeviceListener implementation.  When called AudioOutputController will
    138   // shutdown the existing |stream_|, transition to the kRecreating state,
    139   // create a new stream, and then transition back to an equivalent state prior
    140   // to being called.
    141   virtual void OnDeviceChange() OVERRIDE;
    142 
    143   // AudioSourceDiverter implementation.
    144   virtual const AudioParameters& GetAudioParameters() OVERRIDE;
    145   virtual void StartDiverting(AudioOutputStream* to_stream) OVERRIDE;
    146   virtual void StopDiverting() OVERRIDE;
    147 
    148  protected:
    149   // Internal state of the source.
    150   enum State {
    151     kEmpty,
    152     kCreated,
    153     kPlaying,
    154     kPaused,
    155     kClosed,
    156     kError,
    157   };
    158 
    159   friend class base::RefCountedThreadSafe<AudioOutputController>;
    160   virtual ~AudioOutputController();
    161 
    162  private:
    163   // We are polling sync reader if data became available.
    164   static const int kPollNumAttempts;
    165   static const int kPollPauseInMilliseconds;
    166 
    167   AudioOutputController(AudioManager* audio_manager, EventHandler* handler,
    168                         const AudioParameters& params,
    169                         const std::string& input_device_id,
    170                         SyncReader* sync_reader);
    171 
    172   // The following methods are executed on the audio manager thread.
    173   void DoCreate(bool is_for_device_change);
    174   void DoPlay();
    175   void DoPause();
    176   void DoClose();
    177   void DoSetVolume(double volume);
    178   void DoReportError();
    179   void DoStartDiverting(AudioOutputStream* to_stream);
    180   void DoStopDiverting();
    181 
    182   // Calls EventHandler::OnPowerMeasured() with the current power level and then
    183   // schedules itself to be called again later.
    184   void ReportPowerMeasurementPeriodically();
    185 
    186   // Helper method that stops the physical stream.
    187   void StopStream();
    188 
    189   // Helper method that stops, closes, and NULLs |*stream_|.
    190   void DoStopCloseAndClearStream();
    191 
    192   // Sanity-check that entry/exit to OnMoreIOData() by the hardware audio thread
    193   // happens only between AudioOutputStream::Start() and Stop().
    194   void AllowEntryToOnMoreIOData();
    195   void DisallowEntryToOnMoreIOData();
    196 
    197   AudioManager* const audio_manager_;
    198   const AudioParameters params_;
    199   EventHandler* const handler_;
    200 
    201   // Used by the unified IO to open the correct input device.
    202   std::string input_device_id_;
    203 
    204   AudioOutputStream* stream_;
    205 
    206   // When non-NULL, audio is being diverted to this stream.
    207   AudioOutputStream* diverting_to_stream_;
    208 
    209   // The current volume of the audio stream.
    210   double volume_;
    211 
    212   // |state_| is written on the audio manager thread and is read on the
    213   // hardware audio thread. These operations need to be locked. But lock
    214   // is not required for reading on the audio manager thread.
    215   State state_;
    216 
    217   // Binary semaphore, used to ensure that only one thread enters the
    218   // OnMoreIOData() method, and only when it is valid to do so.  This is for
    219   // sanity-checking the behavior of platform implementations of
    220   // AudioOutputStream.  In other words, multiple contention is not expected,
    221   // nor in the design here.
    222   base::AtomicRefCount num_allowed_io_;
    223 
    224   // SyncReader is used only in low latency mode for synchronous reading.
    225   SyncReader* const sync_reader_;
    226 
    227   // The message loop of audio manager thread that this object runs on.
    228   const scoped_refptr<base::MessageLoopProxy> message_loop_;
    229 
    230   // When starting stream we wait for data to become available.
    231   // Number of times left.
    232   int number_polling_attempts_left_;
    233 
    234   // Scans audio samples from OnMoreIOData() as input to compute power levels.
    235   AudioPowerMonitor power_monitor_;
    236 
    237   // Periodic callback to report power levels during playback.
    238   base::CancelableClosure power_poll_callback_;
    239 
    240   DISALLOW_COPY_AND_ASSIGN(AudioOutputController);
    241 };
    242 
    243 }  // namespace media
    244 
    245 #endif  // MEDIA_AUDIO_AUDIO_OUTPUT_CONTROLLER_H_
    246