Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(62)

Side by Side Diff: media/blink/multibuffer.h

Issue 1165903002: Multi reader/writer cache/buffer (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: more tests, comments adressed, minor refactoring + a little code cleanup Created 5 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2015 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_BLINK_MULTIBUFFER_H_
6 #define MEDIA_BLINK_MULTIBUFFER_H_
7
8 #include <stdint.h>
9
10 #include <limits>
11 #include <map>
12 #include <set>
13
14 #include "base/callback.h"
15 #include "base/memory/ref_counted.h"
16 #include "media/base/data_buffer.h"
17 #include "media/blink/lru.h"
18 #include "media/blink/rangemap.h"
19 #include "media/blink/url_index.h"
20
21 namespace media {
22
23 typedef scoped_refptr<UrlData> MultiBufferUrlData;
24 typedef int32_t MultiBufferBlockNum;
25
26 const int kMaxFreesPerAdd = 10;
27
28 // There is a simple logic for creating, destroying and deferring
29 // data providers. Every data provider has a look-ahead region and
30 // a look-behind region. If there are readers in the look-ahead
31 // region, we keep reading. If not, but there are readers in the
32 // look-behind region, we defer. If there are no readers in either
33 // region, we destroy the data provider.
34
35 // When new readers are added, new data providers are created if
36 // the new reader doesn't fall into the look-ahead region of
37 // an existing data provider.
38
39 // This is the size of the look-ahead region.
40 const int kMaxWaitForWriterOffset = 5;
41
42 // This is the size of the look-behind region.
43 const int kMaxWaitForReaderOffset = 50;
44
45 #define kUnknownUrlData nullptr
46
47 // This is the key for the multibuffer cache, it's made up of an
48 // refcounted UrlData pointer and a block ID.
49 // Uninitialized MultiBufferBlockIds will have a url equal to
50 // kUnknownUrlData. We also use kUnknownUrlData together with
51 // a block id of maxint/minint to represent the maximum and
52 // minimum possible MultiBufferBlockId. Examples, in sorted
53 // order:
54 // { url=kUnknownUrlData, block_num=-maxint } // minimum possible value
55 // { url=kUnknownUrlData, block_num=0 } // uninitialized
56 // { url=valid, block_num=1 } // valid value
57 // { url=valid, block_num=10 } // valid value
58 // { url=kUnknownUrlData, block_num=maxint } // maximum possible value
59 class MultiBufferBlockId {
60 public:
61 MultiBufferBlockId();
62 MultiBufferBlockId(const MultiBufferBlockId& block_id);
63 MultiBufferBlockId(MultiBufferUrlData url_data,
64 MultiBufferBlockNum block_num);
65 ~MultiBufferBlockId();
66 bool SameUrl(const MultiBufferBlockId& other) const {
67 return url_data_ == other.url_data_;
68 }
69 bool operator<(const MultiBufferBlockId& other) const {
70 if (SameUrl(other)) {
71 return block_num_ < other.block_num_;
72 }
73 return url_data_cmp() < other.url_data_cmp();
74 }
75 bool operator>(const MultiBufferBlockId& other) const {
76 if (SameUrl(other)) {
77 return block_num_ > other.block_num_;
78 }
79 return url_data_cmp() > other.url_data_cmp();
80 }
81 bool operator<=(const MultiBufferBlockId& other) const {
82 if (SameUrl(other)) {
83 return block_num_ <= other.block_num_;
84 }
85 return url_data_cmp() <= other.url_data_cmp();
86 }
87 bool operator>=(const MultiBufferBlockId& other) const {
88 if (SameUrl(other)) {
89 return block_num_ >= other.block_num_;
90 }
91 return url_data_cmp() >= other.url_data_cmp();
92 }
93 bool operator==(const MultiBufferBlockId& other) const {
94 return SameUrl(other) && block_num_ == other.block_num_;
95 }
96 bool operator!=(const MultiBufferBlockId& other) const {
97 return !SameUrl(other) || block_num_ != other.block_num_;
98 }
99 int64_t operator-(const MultiBufferBlockId& other) const {
100 if (SameUrl(other)) {
101 return block_num_ - other.block_num_;
102 }
103 // Blocks from different URLs are "infinitely" distant.
104 return std::numeric_limits<int64_t>::max();
105 }
106 MultiBufferBlockId operator-(int32_t n) const {
107 return MultiBufferBlockId(url_data_, block_num_ - n);
108 }
109 MultiBufferBlockId operator+(int32_t n) const {
110 return MultiBufferBlockId(url_data_, block_num_ + n);
111 }
112
113 void operator++() {
114 block_num_++;
115 }
116
117 void operator--() {
118 block_num_--;
119 }
120
121 MultiBufferUrlData url_data() const { return url_data_; }
122 MultiBufferBlockNum block_num() const { return block_num_; }
123
124 private:
125 // We represent the minimum block ID as {0, 0} and the
126 // maximum as {0, max_int64}. This helper function lets
127 // us compare the URLs and get the sort order right.
128 uint64_t url_data_cmp() const {
129 DCHECK_GE(sizeof(uint64_t), sizeof(UrlData*));
130 if (url_data_) return reinterpret_cast<uint64_t>(url_data_.get());
131 if (block_num_ == std::numeric_limits<MultiBufferBlockNum>::max())
132 return std::numeric_limits<uint64_t>::max();
133 return 0;
134 }
135 MultiBufferUrlData url_data_;
136 MultiBufferBlockNum block_num_;
137 };
138
139 } // namespace media
140
141 namespace std {
142 ostream& operator<<(ostream& o, const media::MultiBufferBlockId& id);
143
144 template<>
145 class numeric_limits<media::MultiBufferBlockId> {
146 public:
147 static media::MultiBufferBlockId min() {
148 return media::MultiBufferBlockId(
149 kUnknownUrlData,
150 numeric_limits<media::MultiBufferBlockNum>::min());
151 }
152
153 static media::MultiBufferBlockId max() {
154 return media::MultiBufferBlockId(
155 kUnknownUrlData,
156 numeric_limits<media::MultiBufferBlockNum>::max());
157 }
158 };
159
160 } // namespace std
161
162 namespace media {
163
164 // MultiBuffers are multi-reader multi-writer cache/buffers with
165 // prefetching and pinning. Data is stored internally in ref-counted
166 // blocks of identical size. |block_size_shift| is log2 of the block
167 // size.
168 //
169 // Users should inherit this class and implement CreateWriter().
170 // TODO(hubbe): Make the multibuffer respond to memory pressure.
171 class MultiBuffer {
172 public:
173
174 // Interface for clients wishing to read data out of this cache.
175 class Reader {
176 public:
177 Reader() {}
178 virtual ~Reader() {}
179 // Tell the reader that we have a new UrlData. There may be several
180 // reasons for this:
181 // o We encountered a redirect.
182 // o An error occured, in this case the new_url_data will be
183 // kUnknownUrlData
184 // o We discovered a better UrlData. This happens when expired data
185 // exists in the cache, but the expired data was found to be still
186 // valid after sending the first request.
187 // In most cases, the reader will simply update it's internal position
188 // and keep reading. (This usually involves calling
189 // RemoveReader(old position), AddReader(new position)), but in the case of
190 // an error, the reader will either retry or give up and go away.
191 virtual void UpdateUrlData(const MultiBufferUrlData& old_url_data,
192 const MultiBufferUrlData& new_url_data) = 0;
193
194 // Notifies the reader that the range of available blocks has changed.
195 // The reader must call MultiBuffer::Observe() to activate this callback.
196 virtual void NotifyAvailableRange(
197 const Range<MultiBufferBlockId>& range) = 0;
198 private:
199 DISALLOW_COPY_AND_ASSIGN(Reader);
200 };
201
202 // DataProvider is the interface that MultiBuffer
203 // uses to get data into the cache.
204 class DataProvider {
205 public:
206 virtual ~DataProvider() {}
207
208 // Returns the block number that is to be returned
209 // by the next Read() call.
210 virtual MultiBufferBlockId Tell() const = 0;
211
212 // Returns true if one (or more) blocks are
213 // availble to read.
214 virtual bool Available() const = 0;
215
216 // Returns the next block. Only valid if Available()
217 // returns true. Last block might be of a smaller size
218 // and after the last block we will get an end-of-stream
219 // DataBuffer.
220 virtual scoped_refptr<DataBuffer> Read() = 0;
221
222 // |cb| is called every time Available() becomes true.
223 virtual void SetAvailableCallback(const base::Closure& cb) = 0;
224
225 // Ask the data provider to stop giving us data.
226 // It's ok if the effect is not immediate.
227 virtual void SetDeferred(bool deferred) = 0;
228 };
229
230 explicit MultiBuffer(int32_t block_size_shift);
231 virtual ~MultiBuffer();
232
233 // Identifies a block in the cache.
234 // Block numbers can be calculated from byte positions as:
235 // block_num = byte_pos >> block_size_shift
236 typedef MultiBufferBlockId BlockId;
237 typedef std::map<BlockId, scoped_refptr<DataBuffer> > DataMap;
238
239 // Registers a reader at the given position.
240 // If the cache does not already contain |pos|, it will activate
241 // or create data providers to make sure that the block becomes
242 // available soon. If |pos| is already in the cache, no action is
243 // taken, it simply lets the cache know that this reader is likely
244 // to read pos+1, pos+2.. soon.
245 //
246 // Registered readers will be notified when the available range
247 // at their position changes. The available range at |pos| is a range
248 // from A to B where: A <= |pos|, B >= |pos| and all blocks in [A..B)
249 // are present in the cache. When this changes, we will call
250 // NotifyAvailableRange() on the reader.
251 void AddReader(const BlockId& pos, Reader* reader);
252
253 // Unregister a reader at block |pos|.
254 // Often followed by a call to AddReader(pos + 1, ...);
255 // Idempotent.
256 void RemoveReader(const BlockId& pos, Reader* reader);
257
258 // Immediately remove writers at or before |pos| if nobody needs them.
259 // Note that we can't really do this in StopWaitFor(), because it's very
260 // likely that StopWaitFor() is immediately followed by a call to WaitFor().
261 // It is also a bad idea to wait for the writers to clean themselves up when
262 // they try to provide unwanted data to the cache. Besides the obvoius
263 // inefficiency, it will also cause the http_cache to bypass the disk/memory
264 // cache if we have multiple simultaneous requests going against the same
265 // url.
266 void CleanupWriters(const BlockId& pos);
267
268 // Returns true if block |pos| is available in the cache.
269 bool Contains(const BlockId& pos) const;
270
271 // Returns the next unavailable block at or after |pos|.
272 BlockId FindNextUnavailable(const BlockId& pos) const;
273
274 // Change the pin count for a range of data blocks.
275 // Note that blocks do not have to be present in the
276 // cache to be pinned.
277 // Examples:
278 // Pin block 3, 4 & 5: PinRange(3, 6, 1);
279 // Unpin block 4 & 5: PinRange(4, 6, -1);
280 void PinRange(const BlockId& from, const BlockId& to, int32_t howmuch);
281
282 // Calls PinRange for each range in |ranges|, convenience
283 // function for applying multiple changes to the pinned ranges.
284 void PinRanges(const RangeMap<BlockId, int32_t>& ranges);
285
286 // Increment max cache size by |size| (counted in blocks).
287 void IncrementMaxSize(int32_t size);
288
289 // Caller takes ownership of 'provider', cache will
290 // not call it anymore.
291 scoped_ptr<DataProvider> RemoveProvider(DataProvider* provider);
292
293 // Add a writer to this cache. Cache takes ownership and
294 // may choose to destroy it.
295 void AddProvider(scoped_ptr<DataProvider> provider);
296
297 // Tell all reader workin on |old_url_data| about a new url.
298 // See Reader::UpdateUrlData for more info.
299 void UpdateUrlData(const MultiBufferUrlData& old_url_data,
300 const MultiBufferUrlData& new_url_data);
301
302 // Accessors.
303 const DataMap& map() const { return data_; }
304 int32_t block_size_shift() const { return block_size_shift_; }
305
306 protected:
307 // Create a new writer at |pos| and return it.
308 // Users needs to implemement this method.
309 virtual DataProvider* CreateWriter(const BlockId& pos) = 0;
310
311 private:
312 // For testing.
313 friend class TestMultiBuffer;
314
315 enum ProviderState {
316 ProviderStateDead,
317 ProviderStateDefer,
318 ProviderStateLoad
319 };
320
321 // Figure out what state a writer at |pos| should be in.
322 ProviderState SuggestProviderState(const BlockId& pos) const;
323
324 // Returns true if a writer at |pos| is colliding with
325 // output of another writer.
326 bool ProviderCollision(const BlockId& pos) const;
327
328 // Call NotifyAvailableRange(new_range) on all readers waiting
329 // for a block in |observer_range|
330 void NotifyAvailableRange(
331 const Range<MultiBufferBlockId>& observer_range,
332 const Range<MultiBufferBlockId>& new_range);
333
334 // Callback which notifies us that a data provider has
335 // some data for us. Also called when it might be apprperiate
336 // for a provider in a deferred state to wake up.
337 void DataProviderEvent(DataProvider *provider);
338
339 // Free elements from cache if needed and possible.
340 // Don't free more than |max_to_free| blocks.
341 // Virtual for testing purposes.
342 virtual void Prune(size_t max_to_free);
343
344 // Max number of blocks.
345 size_t max_size_;
346
347 // log2 of block size.
348 int32_t block_size_shift_;
349
350 // Stores the actual data.
351 DataMap data_;
352
353 // Keeps track of readers waiting for data.
354 std::map<MultiBufferBlockId, std::set<Reader*> > readers_;
355
356 // Keeps track of writers by their position.
357 // The writers are owned by this class.
358 std::map<BlockId, DataProvider*> writer_index_;
359
360 // The LRU should contain all blocks which are not pinned.
361 LRU<BlockId> lru_;
362
363 // Keeps track of what blocks are pinned. If block p is pinned,
364 // then pinned_[p] > 0. Pinned blocks cannot be freed and should not
365 // be present in |lru_|.
366 RangeMap<BlockId, int32_t> pinned_;
367
368 // present_[block] should be 1 for all blocks that are present
369 // and 0 for all blocks that are not. Used to quickly figure out
370 // ranges of available blocks without iterating.
371 RangeMap<BlockId, int32_t> present_;
372 };
373
374 } // namespace media
375
376 #endif // MEDIA_BLINK_MULTIBUFFER_H_
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698