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.
5 #ifndef MEDIA_BLINK_BUFFERED_DATA_SOURCE_H_
6 #define MEDIA_BLINK_BUFFERED_DATA_SOURCE_H_
11 #include "base/callback.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/memory/weak_ptr.h"
14 #include "base/synchronization/lock.h"
15 #include "media/base/data_source.h"
16 #include "media/base/media_export.h"
17 #include "media/base/ranges.h"
18 #include "media/blink/buffered_resource_loader.h"
22 class SingleThreadTaskRunner
;
28 class MEDIA_EXPORT BufferedDataSourceHost
{
30 // Notify the host of the total size of the media file.
31 virtual void SetTotalBytes(int64 total_bytes
) = 0;
33 // Notify the host that byte range [start,end] has been buffered.
34 // TODO(fischman): remove this method when demuxing is push-based instead of
35 // pull-based. http://crbug.com/131444
36 virtual void AddBufferedByteRange(int64 start
, int64 end
) = 0;
39 virtual ~BufferedDataSourceHost() {}
42 // A data source capable of loading URLs and buffering the data using an
43 // in-memory sliding window.
45 // BufferedDataSource must be created and destroyed on the thread associated
46 // with the |task_runner| passed in the constructor.
47 class MEDIA_EXPORT BufferedDataSource
: public DataSource
{
49 // Used to specify video preload states. They are "hints" to the browser about
50 // how aggressively the browser should load and buffer data.
51 // Please see the HTML5 spec for the descriptions of these values:
52 // http://www.w3.org/TR/html5/video.html#attr-media-preload
54 // Enum values must match the values in blink::WebMediaPlayer::Preload and
55 // there will be assertions at compile time if they do not match.
61 typedef base::Callback
<void(bool)> DownloadingCB
;
63 // |url| and |cors_mode| are passed to the object. Buffered byte range changes
64 // will be reported to |host|. |downloading_cb| will be called whenever the
65 // downloading/paused state of the source changes.
68 BufferedResourceLoader::CORSMode cors_mode
,
69 const scoped_refptr
<base::SingleThreadTaskRunner
>& task_runner
,
70 blink::WebFrame
* frame
,
72 BufferedDataSourceHost
* host
,
73 const DownloadingCB
& downloading_cb
);
74 ~BufferedDataSource() override
;
76 // Executes |init_cb| with the result of initialization when it has completed.
78 // Method called on the render thread.
79 typedef base::Callback
<void(bool)> InitializeCB
;
80 void Initialize(const InitializeCB
& init_cb
);
82 // Adjusts the buffering algorithm based on the given preload value.
83 void SetPreload(Preload preload
);
85 // Returns true if the media resource has a single origin, false otherwise.
86 // Only valid to call after Initialize() has completed.
88 // Method called on the render thread.
89 bool HasSingleOrigin();
91 // Returns true if the media resource passed a CORS access control check.
92 bool DidPassCORSAccessCheck() const;
94 // Cancels initialization, any pending loaders, and any pending read calls
95 // from the demuxer. The caller is expected to release its reference to this
96 // object and never call it again.
98 // Method called on the render thread.
101 // Notifies changes in playback state for controlling media buffering
103 void MediaPlaybackRateChanged(double playback_rate
);
104 void MediaIsPlaying();
105 void MediaIsPaused();
106 bool media_has_played() const { return media_has_played_
; }
108 // Returns true if the resource is local.
109 bool assume_fully_buffered() { return !url_
.SchemeIsHTTPOrHTTPS(); }
111 // Cancels any open network connections once reaching the deferred state for
112 // preload=metadata, non-streaming resources that have not started playback.
113 // If already deferred, connections will be immediately closed.
114 void OnBufferingHaveEnough();
116 // DataSource implementation.
117 // Called from demuxer thread.
118 void Stop() override
;
120 void Read(int64 position
,
123 const DataSource::ReadCB
& read_cb
) override
;
124 bool GetSize(int64
* size_out
) override
;
125 bool IsStreaming() override
;
126 void SetBitrate(int bitrate
) override
;
129 // A factory method to create a BufferedResourceLoader based on the read
130 // parameters. We can override this file to object a mock
131 // BufferedResourceLoader for testing.
132 virtual BufferedResourceLoader
* CreateResourceLoader(
133 int64 first_byte_position
, int64 last_byte_position
);
136 friend class BufferedDataSourceTest
;
138 // Task posted to perform actual reading on the render thread.
141 // Cancels oustanding callbacks and sets |stop_signal_received_|. Safe to call
143 void StopInternal_Locked();
145 // Stops |loader_| if present. Used by Abort() and Stop().
148 // Tells |loader_| the bitrate of the media.
149 void SetBitrateTask(int bitrate
);
151 // The method that performs actual read. This method can only be executed on
152 // the render thread.
155 // BufferedResourceLoader::Start() callback for initial load.
156 void StartCallback(BufferedResourceLoader::Status status
);
158 // BufferedResourceLoader::Start() callback for subsequent loads (i.e.,
159 // when accessing ranges that are outside initial buffered region).
160 void PartialReadStartCallback(BufferedResourceLoader::Status status
);
162 // Returns true if we can accept the new partial response.
163 bool CheckPartialResponseURL(const GURL
& partial_response_original_url
) const;
165 // BufferedResourceLoader callbacks.
166 void ReadCallback(BufferedResourceLoader::Status status
, int bytes_read
);
167 void LoadingStateChangedCallback(BufferedResourceLoader::LoadingState state
);
168 void ProgressCallback(int64 position
);
170 // Update |loader_|'s deferring strategy in response to a play/pause, or
171 // change in playback rate.
172 void UpdateDeferStrategy(bool paused
);
174 // URL of the resource requested.
176 // crossorigin attribute on the corresponding HTML media element, if any.
177 BufferedResourceLoader::CORSMode cors_mode_
;
179 // The total size of the resource. Set during StartCallback() if the size is
180 // known, otherwise it will remain kPositionNotSpecified until the size is
181 // determined by reaching EOF.
184 // This value will be true if this data source can only support streaming.
185 // i.e. range request is not supported.
188 // A webframe for loading.
189 blink::WebFrame
* frame_
;
191 // A resource loader for the media resource.
192 scoped_ptr
<BufferedResourceLoader
> loader_
;
194 // Callback method from the pipeline for initialization.
195 InitializeCB init_cb_
;
197 // Read parameters received from the Read() method call. Must be accessed
200 scoped_ptr
<ReadOperation
> read_op_
;
202 // This buffer is intermediate, we use it for BufferedResourceLoader to write
203 // to. And when read in BufferedResourceLoader is done, we copy data from
204 // this buffer to |read_buffer_|. The reason for an additional copy is that
205 // we don't own |read_buffer_|. But since the read operation is asynchronous,
206 // |read_buffer| can be destroyed at any time, so we only copy into
207 // |read_buffer| in the final step when it is safe.
208 // Memory is allocated for this member during initialization of this object
209 // because we want buffer to be passed into BufferedResourceLoader to be
210 // always non-null. And by initializing this member with a default size we can
211 // avoid creating zero-sized buffered if the first read has zero size.
212 std::vector
<uint8
> intermediate_read_buffer_
;
214 // The task runner of the render thread.
215 const scoped_refptr
<base::SingleThreadTaskRunner
> render_task_runner_
;
217 // Protects |stop_signal_received_| and |read_op_|.
220 // Whether we've been told to stop via Abort() or Stop().
221 bool stop_signal_received_
;
223 // This variable is true when the user has requested the video to play at
225 bool media_has_played_
;
227 // This variable holds the value of the preload attribute for the video
231 // Bitrate of the content, 0 if unknown.
234 // Current playback rate.
235 double playback_rate_
;
237 scoped_refptr
<MediaLog
> media_log_
;
239 // Host object to report buffered byte range changes to.
240 BufferedDataSourceHost
* host_
;
242 DownloadingCB downloading_cb_
;
244 // The original URL of the first response. If the request is redirected to
245 // another URL it is the URL after redirected. If the response is generated in
246 // a Service Worker this URL is empty. BufferedDataSource checks the original
247 // URL of each successive response. If the origin URL of it is different from
248 // the original URL of the first response, it is treated as an error.
249 GURL response_original_url_
;
251 // Disallow rebinding WeakReference ownership to a different thread by keeping
252 // a persistent reference. This avoids problems with the thread-safety of
253 // reaching into this class from multiple threads to attain a WeakPtr.
254 base::WeakPtr
<BufferedDataSource
> weak_ptr_
;
255 base::WeakPtrFactory
<BufferedDataSource
> weak_factory_
;
257 DISALLOW_COPY_AND_ASSIGN(BufferedDataSource
);
262 #endif // MEDIA_BLINK_BUFFERED_DATA_SOURCE_H_