1// Copyright 2013 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 CONTENT_RENDERER_MEDIA_BUFFERED_DATA_SOURCE_H_
6#define CONTENT_RENDERER_MEDIA_BUFFERED_DATA_SOURCE_H_
7
8#include <string>
9
10#include "base/callback.h"
11#include "base/memory/scoped_ptr.h"
12#include "base/synchronization/lock.h"
13#include "content/common/content_export.h"
14#include "content/renderer/media/buffered_resource_loader.h"
15#include "content/renderer/media/preload.h"
16#include "media/base/data_source.h"
17#include "media/base/ranges.h"
18#include "url/gurl.h"
19
20namespace base {
21class MessageLoopProxy;
22}
23
24namespace media {
25class MediaLog;
26}
27
28namespace content {
29
30class CONTENT_EXPORT BufferedDataSourceHost {
31 public:
32  // Notify the host of the total size of the media file.
33  virtual void SetTotalBytes(int64 total_bytes) = 0;
34
35  // Notify the host that byte range [start,end] has been buffered.
36  // TODO(fischman): remove this method when demuxing is push-based instead of
37  // pull-based.  http://crbug.com/131444
38  virtual void AddBufferedByteRange(int64 start, int64 end) = 0;
39
40 protected:
41  virtual ~BufferedDataSourceHost() {};
42};
43
44// A data source capable of loading URLs and buffering the data using an
45// in-memory sliding window.
46//
47// BufferedDataSource must be created and initialized on the render thread
48// before being passed to other threads. It may be deleted on any thread.
49class CONTENT_EXPORT BufferedDataSource : public media::DataSource {
50 public:
51  typedef base::Callback<void(bool)> DownloadingCB;
52
53  // |url| and |cors_mode| are passed to the object. Buffered byte range changes
54  // will be reported to |host|. |downloading_cb| will be called whenever the
55  // downloading/paused state of the source changes.
56  BufferedDataSource(const GURL& url,
57                     BufferedResourceLoader::CORSMode cors_mode,
58                     const scoped_refptr<base::MessageLoopProxy>& render_loop,
59                     blink::WebFrame* frame,
60                     media::MediaLog* media_log,
61                     BufferedDataSourceHost* host,
62                     const DownloadingCB& downloading_cb);
63  virtual ~BufferedDataSource();
64
65  // Executes |init_cb| with the result of initialization when it has completed.
66  //
67  // Method called on the render thread.
68  typedef base::Callback<void(bool)> InitializeCB;
69  void Initialize(const InitializeCB& init_cb);
70
71  // Adjusts the buffering algorithm based on the given preload value.
72  void SetPreload(Preload preload);
73
74  // Returns true if the media resource has a single origin, false otherwise.
75  // Only valid to call after Initialize() has completed.
76  //
77  // Method called on the render thread.
78  bool HasSingleOrigin();
79
80  // Returns true if the media resource passed a CORS access control check.
81  bool DidPassCORSAccessCheck() const;
82
83  // Cancels initialization, any pending loaders, and any pending read calls
84  // from the demuxer. The caller is expected to release its reference to this
85  // object and never call it again.
86  //
87  // Method called on the render thread.
88  void Abort();
89
90  // Notifies changes in playback state for controlling media buffering
91  // behavior.
92  void MediaPlaybackRateChanged(float playback_rate);
93  void MediaIsPlaying();
94  void MediaIsPaused();
95
96  // Returns true if the resource is local.
97  bool assume_fully_buffered() { return !url_.SchemeIsHTTPOrHTTPS(); }
98
99  // media::DataSource implementation.
100  // Called from demuxer thread.
101  virtual void Stop(const base::Closure& closure) OVERRIDE;
102
103  virtual void Read(int64 position, int size, uint8* data,
104                    const media::DataSource::ReadCB& read_cb) OVERRIDE;
105  virtual bool GetSize(int64* size_out) OVERRIDE;
106  virtual bool IsStreaming() OVERRIDE;
107  virtual void SetBitrate(int bitrate) OVERRIDE;
108
109 protected:
110  // A factory method to create a BufferedResourceLoader based on the read
111  // parameters. We can override this file to object a mock
112  // BufferedResourceLoader for testing.
113  virtual BufferedResourceLoader* CreateResourceLoader(
114      int64 first_byte_position, int64 last_byte_position);
115
116 private:
117  friend class BufferedDataSourceTest;
118
119  // Task posted to perform actual reading on the render thread.
120  void ReadTask();
121
122  // Cancels oustanding callbacks and sets |stop_signal_received_|. Safe to call
123  // from any thread.
124  void StopInternal_Locked();
125
126  // Stops |loader_| if present. Used by Abort() and Stop().
127  void StopLoader();
128
129  // Tells |loader_| the bitrate of the media.
130  void SetBitrateTask(int bitrate);
131
132  // The method that performs actual read. This method can only be executed on
133  // the render thread.
134  void ReadInternal();
135
136  // BufferedResourceLoader::Start() callback for initial load.
137  void StartCallback(BufferedResourceLoader::Status status);
138
139  // BufferedResourceLoader::Start() callback for subsequent loads (i.e.,
140  // when accessing ranges that are outside initial buffered region).
141  void PartialReadStartCallback(BufferedResourceLoader::Status status);
142
143  // BufferedResourceLoader callbacks.
144  void ReadCallback(BufferedResourceLoader::Status status, int bytes_read);
145  void LoadingStateChangedCallback(BufferedResourceLoader::LoadingState state);
146  void ProgressCallback(int64 position);
147
148  // Update |loader_|'s deferring strategy in response to a play/pause, or
149  // change in playback rate.
150  void UpdateDeferStrategy(bool paused);
151
152  // URL of the resource requested.
153  GURL url_;
154  // crossorigin attribute on the corresponding HTML media element, if any.
155  BufferedResourceLoader::CORSMode cors_mode_;
156
157  // The total size of the resource. Set during StartCallback() if the size is
158  // known, otherwise it will remain kPositionNotSpecified until the size is
159  // determined by reaching EOF.
160  int64 total_bytes_;
161
162  // This value will be true if this data source can only support streaming.
163  // i.e. range request is not supported.
164  bool streaming_;
165
166  // A webframe for loading.
167  blink::WebFrame* frame_;
168
169  // A resource loader for the media resource.
170  scoped_ptr<BufferedResourceLoader> loader_;
171
172  // Callback method from the pipeline for initialization.
173  InitializeCB init_cb_;
174
175  // Read parameters received from the Read() method call. Must be accessed
176  // under |lock_|.
177  class ReadOperation;
178  scoped_ptr<ReadOperation> read_op_;
179
180  // This buffer is intermediate, we use it for BufferedResourceLoader to write
181  // to. And when read in BufferedResourceLoader is done, we copy data from
182  // this buffer to |read_buffer_|. The reason for an additional copy is that
183  // we don't own |read_buffer_|. But since the read operation is asynchronous,
184  // |read_buffer| can be destroyed at any time, so we only copy into
185  // |read_buffer| in the final step when it is safe.
186  // Memory is allocated for this member during initialization of this object
187  // because we want buffer to be passed into BufferedResourceLoader to be
188  // always non-null. And by initializing this member with a default size we can
189  // avoid creating zero-sized buffered if the first read has zero size.
190  scoped_ptr<uint8[]> intermediate_read_buffer_;
191  int intermediate_read_buffer_size_;
192
193  // The message loop of the render thread.
194  const scoped_refptr<base::MessageLoopProxy> render_loop_;
195
196  // Protects |stop_signal_received_| and |read_op_|.
197  base::Lock lock_;
198
199  // Whether we've been told to stop via Abort() or Stop().
200  bool stop_signal_received_;
201
202  // This variable is true when the user has requested the video to play at
203  // least once.
204  bool media_has_played_;
205
206  // This variable holds the value of the preload attribute for the video
207  // element.
208  Preload preload_;
209
210  // Bitrate of the content, 0 if unknown.
211  int bitrate_;
212
213  // Current playback rate.
214  float playback_rate_;
215
216  scoped_refptr<media::MediaLog> media_log_;
217
218  // Host object to report buffered byte range changes to.
219  BufferedDataSourceHost* host_;
220
221  DownloadingCB downloading_cb_;
222
223  // NOTE: Weak pointers must be invalidated before all other member variables.
224  base::WeakPtrFactory<BufferedDataSource> weak_factory_;
225
226  DISALLOW_COPY_AND_ASSIGN(BufferedDataSource);
227};
228
229}  // namespace content
230
231#endif  // CONTENT_RENDERER_MEDIA_BUFFERED_DATA_SOURCE_H_
232