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

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 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
13 #include "base/callback.h"
14 #include "base/memory/ref_counted.h"
15 #include "media/base/data_buffer.h"
16 #include "media/blink/lru.h"
17 #include "media/blink/rangemap.h"
18 #include "media/blink/url_index.h"
19 #include "media/blink/waiter_index.h"
20
21 namespace media {
22
23 typedef scoped_refptr<UrlData> MultiBufferUrlId;
24 typedef int32_t MultiBufferBlockNum;
25
26 const int kMaxFreesPerAdd = 10;
27 const int kMaxWaitForWriterOffset = 5;
28 #define kUnknownUrlId nullptr
29
30 // This is the key for the multibuffer cache, it's made up of an
31 // refcounted UrlData pointer and a block ID.
liberato (no reviews please) 2015/10/09 17:36:09 if !url_id has special meaning, might want to ment
hubbe 2015/10/13 23:08:17 Done.
32 class MultiBufferBlockId {
33 public:
34 MultiBufferBlockId();
35 MultiBufferBlockId(const MultiBufferBlockId& block_id);
36 MultiBufferBlockId(MultiBufferUrlId url_id,
37 MultiBufferBlockNum block_num);
38 ~MultiBufferBlockId();
liberato (no reviews please) 2015/10/09 17:36:10 why declare this?
hubbe 2015/10/13 23:08:17 Because chrome-style demands it?
39 bool SameUrl(const MultiBufferBlockId& other) const {
40 return url_id_ == other.url_id_;
41 }
42 bool operator<(const MultiBufferBlockId& other) const {
43 if (SameUrl(other)) {
44 return block_num_ < other.block_num_;
45 }
46 return url_id_cmp() < other.url_id_cmp();
47 }
48 bool operator>(const MultiBufferBlockId& other) const {
49 if (SameUrl(other)) {
50 return block_num_ > other.block_num_;
51 }
52 return url_id_cmp() > other.url_id_cmp();
53 }
54 bool operator<=(const MultiBufferBlockId& other) const {
55 if (SameUrl(other)) {
56 return block_num_ <= other.block_num_;
57 }
58 return url_id_cmp() <= other.url_id_cmp();
59 }
60 bool operator>=(const MultiBufferBlockId& other) const {
61 if (SameUrl(other)) {
62 return block_num_ >= other.block_num_;
63 }
64 return url_id_cmp() >= other.url_id_cmp();
65 }
66 bool operator==(const MultiBufferBlockId& other) const {
67 return SameUrl(other) && block_num_ == other.block_num_;
68 }
69 bool operator!=(const MultiBufferBlockId& other) const {
70 return !SameUrl(other) || block_num_ != other.block_num_;
71 }
72 int64_t operator-(const MultiBufferBlockId& other) const {
73 if (SameUrl(other)) {
74 return block_num_ - other.block_num_;
75 }
76 // Blocks from different URLs are "infinitely" distant.
77 return std::numeric_limits<int64_t>::max();
78 }
79 MultiBufferBlockId operator-(int32_t n) const {
80 return MultiBufferBlockId(url_id_, block_num_ - n);
81 }
82 MultiBufferBlockId operator+(int32_t n) const {
83 return MultiBufferBlockId(url_id_, block_num_ + n);
84 }
85
86 void operator++() {
87 block_num_++;
88 }
89
90 MultiBufferUrlId url_id() const { return url_id_; }
91 MultiBufferBlockNum block_num() const { return block_num_; }
92
93 private:
94 // We represent the minimum block ID as {0, 0} and the
95 // minimum as {0, max_int64}. This helper function lets
liberato (no reviews please) 2015/10/09 17:36:09 maximum
hubbe 2015/10/13 23:08:17 Done.
96 // us compare the URLs and get the sort order right.
97 uint64_t url_id_cmp() const {
98 DCHECK_GE(sizeof(uint64_t), sizeof(UrlData*));
99 if (url_id_) return reinterpret_cast<uint64_t>(url_id_.get());
100 if (block_num_ == std::numeric_limits<MultiBufferBlockNum>::max())
101 return std::numeric_limits<uint64_t>::max();
102 return 0;
103 }
104 MultiBufferUrlId url_id_;
105 MultiBufferBlockNum block_num_;
106 };
107
108 } // namespace media
109
110 namespace std {
111 ostream& operator<<(ostream& o, const media::MultiBufferBlockId& id);
112
113 template<>
114 class numeric_limits<media::MultiBufferBlockId> {
115 public:
116 static media::MultiBufferBlockId min() {
117 return media::MultiBufferBlockId(
118 numeric_limits<media::MultiBufferUrlId>::min(),
119 numeric_limits<media::MultiBufferBlockNum>::min());
120 }
121
122 static media::MultiBufferBlockId max() {
123 return media::MultiBufferBlockId(
124 numeric_limits<media::MultiBufferUrlId>::max(),
liberato (no reviews please) 2015/10/09 17:36:09 should this be 0 rather than ::max? (probably als
hubbe 2015/10/13 23:08:17 Hmm, not sure what is best here. Originally, Multi
125 numeric_limits<media::MultiBufferBlockNum>::max());
126 }
127 };
128
129 } // namespace std
130
131 namespace media {
132
133
134 // MultiBufferDataProvider is the interface that MultiBuffer
135 // uses to get data into the cache.
136 class MultiBufferDataProvider {
137 public:
138 virtual ~MultiBufferDataProvider();
liberato (no reviews please) 2015/10/09 17:36:09 why not {}?
hubbe 2015/10/13 23:08:17 Done.
139
140 // Returns the block number that is to be returned
141 // by the next Read() call.
142 virtual MultiBufferBlockId Tell() const = 0;
143
144 // Returns true if one (or more) blocks are
145 // availble to read.
146 virtual bool Available() const = 0;
147
148 // Returns the next block. Only valid if Available()
149 // returns true. Last block might be of a smaller size
150 // and after the last block we will get an end-of-stream
151 // DataBuffer.
152 virtual scoped_refptr<DataBuffer> Read() = 0;
153
154 // |cb| is called every time Available() becomes true.
155 virtual void SetAvailableCallback(base::Closure cb) = 0;
liberato (no reviews please) 2015/10/09 17:36:09 const base::Closure& ?
hubbe 2015/10/13 23:08:17 Done.
156
157 // Ask the data provider to stop giving us data.
liberato (no reviews please) 2015/10/09 17:36:09 does this mean that it may no longer call the avai
hubbe 2015/10/13 23:08:17 Clarified.
158 virtual void SetDeferred(bool deferred) = 0;
159 };
160
161 class Reader {
liberato (no reviews please) 2015/10/09 17:36:10 comment here would help. also, MultiBufferReader?
hubbe 2015/10/13 23:08:16 Comment added, moved into MultiBuffer.
162 public:
163 Reader() {}
liberato (no reviews please) 2015/10/09 17:36:09 why?
hubbe 2015/10/13 23:08:17 because: ../../media/blink/multibuffer.cc:398:20:
164 virtual ~Reader() {}
165 // Tell the reader that we have a new URL ID. There may be several
166 // reasons for this:
167 // o We encountered a redirect.
168 // o An error occured, in this case the new_url_id will be kUnknownUrlId
169 // o We discovered a better UrlID. This happens when expired data
170 // exists in the cache, but the expired data was found to be still
171 // valid after sending the first request.
172 virtual void UpdateURLId(MultiBufferUrlId old_url_id,
liberato (no reviews please) 2015/10/09 17:36:09 might want to include what a typical reader action
hubbe 2015/10/13 23:08:17 Done.
173 MultiBufferUrlId new_url_id) = 0;
174
175 // Notifies the reader that the range of available blocks has changed.
176 // The reader must call Observe() to activate this callback.
177 virtual void NotifyAvailableRange(
178 const Range<MultiBufferBlockId>& range) = 0;
179 private:
180 DISALLOW_COPY_AND_ASSIGN(Reader);
181 };
182
183
184 class ReaderIndex {
liberato (no reviews please) 2015/10/09 17:36:09 please comment. Also, MultiBufferReaderIndex?
hubbe 2015/10/13 23:08:17 Gone.
185 public:
186 ReaderIndex();
187 ~ReaderIndex();
188 // Register a waiter at position |pos|.
189 // Returns true if this is the first Reader waiting for
190 // this particular position.
191 bool WaitFor(MultiBufferBlockId pos, Reader* waiter);
192
193 // Unregister a waiter, |pos| should be the same
194 // position as given to WaitFor().
195 // Returns true if this is the last Reader waiting for
196 // this particular position.
197 bool StopWaitFor(MultiBufferBlockId pos, Reader* waiter);
198
199 // Return the distance from pos to the next waiting reader.
200 int64_t DistToNext(MultiBufferBlockId pos) const;
201
202 // Tell all readers working on |old_url_id| to go read from
203 // |new_url_id| instead. See Reader::UpdateURLId for more info.
204 void UpdateURLId(MultiBufferUrlId old_url_id,
205 MultiBufferUrlId new_url_id);
206
207 // Call NotifyAvailableRange(new_range) on all readers waiting
208 // for a block in |observer_range|
209 void NotifyAvailableRange(
210 const Range<MultiBufferBlockId>& observer_range,
211 const Range<MultiBufferBlockId>& new_range);
212
213 const std::map<MultiBufferBlockId, std::set<Reader*> >& map() const {
214 return readers_;
215 }
216
217 private:
218 std::map<MultiBufferBlockId, std::set<Reader*> > readers_;
219 };
220
221 // MultiBuffers are multi-reader multi-writer cache/buffers with
222 // prefetching and pinning. Data is stored internally in ref-counted
223 // blocks of identical size. |block_size_shift| is log2 of the block
224 // size.
225 //
226 // Users should inherit this class and implement StartWriter().
liberato (no reviews please) 2015/10/09 17:36:10 s/Start/Create/ also, this might be better if a M
hubbe 2015/10/13 23:08:17 Fixed.
227 // TODO(hubbe): Make the multibuffer respond to memory pressure.
228 class MultiBuffer {
229 public:
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 // Wait for block |pos| to become available. Starts new Writers as needed.
240 void WaitFor(BlockId pos, Reader* reader);
241
242 // Let the buffer that we're going to want to read block |pos|, but we're ok
243 // with the current level of buffering.
liberato (no reviews please) 2015/10/09 17:36:09 "ok with the current level of buffering" isn't ver
hubbe 2015/10/13 23:08:17 DeferredWaitFor is gone.
244 void DeferredWaitFor(BlockId pos, Reader* reader);
245
246 // Stop waiting for block |pos|.
247 // Often followed by a call to WaitFor(pos + 1, ...);
248 // Cancels a previous WaitFor() or DeferredWaitFor().
249 // Idempotent.
250 void StopWaitFor(BlockId pos, Reader* reader);
251
252 // Immediately remove writers at or before |pos| if nobody needs them.
253 void CleanupWriters(BlockId pos);
254
255 // Register |reader| for NotifyAvailableRange calls. If the range of available
256 // blocks before or after |pos| changes, we'll call NotifyAvailableRange on
liberato (no reviews please) 2015/10/09 17:36:10 this isn't clear. all blocks are either before, a
hubbe 2015/10/13 23:08:17 Updated comment, better?
257 // the reader to let it know.
258 void Observe(BlockId pos, Reader* reader);
259 void StopObserve(BlockId pos, Reader* reader);
260
261 // Returns true if block |pos| is available in the cache.
262 bool Contains(BlockId pos) const;
263
264 // Returns the next unavailable block at or after |pos|.
265 BlockId FindNextUnavailable(BlockId pos) const;
266
267 // Change the pin count for a range of data blocks.
268 // Note that blocks do not have to be present in the
269 // cache to be pinned.
270 // Examples:
271 // Pin block 3, 4 & 5: PinRange(3, 6, 1);
272 // Unpin block 4 & 5: PinRange(4, 6, -1);
273 void PinRange(BlockId from, BlockId to, int32_t howmuch);
274
275 // Increment max cache size by |size| (counted in blocks).
276 void IncrementMaxSize(int32_t size);
277
278 // Caller takes ownership of 'provider', cache will
279 // not call it anymore.
280 scoped_ptr<MultiBufferDataProvider> RemoveProvider(
281 MultiBufferDataProvider* provider);
282
283 // Add a writer to this cache. Cache takes ownership and
284 // may choose to destroy it.
285 void AddProvider(scoped_ptr<MultiBufferDataProvider> provider);
286
287 // Tell all reader workin on |old_url_id| about a new url.
288 // See Reader::UpdateURLId for more info.
289 void UpdateURLId(MultiBufferUrlId old_url_id,
290 MultiBufferUrlId new_url_id);
291
292 // Accessors.
293 const DataMap& map() const { return data_; }
294 int32_t block_size_shift() const { return block_size_shift_; }
295
296 protected:
297 // Create a new writer at |pos| and return it.
298 // Users needs to implemement this method.
299 virtual MultiBufferDataProvider* CreateWriter(BlockId pos) = 0;
300
301 private:
302 // For testing.
303 friend class TestMultiBuffer;
304
305 // Callback which notifies us that a data provider has
306 // some data for us. Also called when it might be apprperiate
307 // for a provider in a deferred state to wake up.
308 void DataProviderEvent(MultiBufferDataProvider *provider);
309
310 // Free elements from cache if needed and possible.
311 // Don't free more than |max_to_free| blocks.
312 void Prune(size_t max_to_free);
313
314 // Max number of blocks.
315 size_t max_size_;
316
317 // log2 of block size.
318 int32_t block_size_shift_;
319
320 // Stores the actual data.
321 DataMap data_;
322
323 // Keeps track of readers waiting for data.
324 ReaderIndex reader_index_;
325
326 // Keeps track of readers that will want data soon.
327 ReaderIndex deferred_reader_index_;
328
329 // Observers are notified when the surrounding ranges
330 // of available blocks change.
331 ReaderIndex observer_index_;
332
333 // Keeps track of writers by their position.
334 // The writers are owned by this class.
335 std::map<BlockId, MultiBufferDataProvider*> writer_index_;
336
337 // The LRU should contain all blocks which are not pinned.
338 LRU<BlockId> lru_;
339
340 // Keeps track of what blocks are pinned. If block p is pinned,
341 // then pinned_[p] > 0. Pinned blocks cannot be freed and should not
342 // be present in |lru_|.
343 RangeMap<BlockId, int32_t> pinned_;
344
345 // present_[block] should be 1 for all blocks that are present
346 // and 0 for all blocks that are not. Used to quickly figure out
347 // ranges of available blocks without iterating.
348 RangeMap<BlockId, int32_t> present_;
349 };
350
351 // Wrapper for MultiBuffer that offers a simple byte-reading
352 // interface with prefetch.
353 class MultiBufferReader : public Reader {
liberato (no reviews please) 2015/10/09 17:36:10 this is a confusing name. StreamingMultiBufferRea
hubbe 2015/10/13 23:08:17 I like the shorter name, but I moved it to a separ
354 public:
355 // Note that |progress_callback| is guaranteed to be called if
356 // a redirect happens and the url_id is updated. Otherwise
357 // origin checks will become insecure.
liberato (no reviews please) 2015/10/09 17:36:10 please document processs_callback args.
hubbe 2015/10/13 23:08:17 Done.
358 MultiBufferReader(MultiBuffer* multibuffer,
359 MultiBufferUrlId url_id,
360 int64_t start,
361 int64_t end,
362 int64_t preload_high,
363 int64_t preload_low,
364 int64_t max_buffer_forward,
365 int64_t max_buffer_backward,
366 base::Callback<void(int64_t, int64_t)> progress_callback);
367
368 ~MultiBufferReader() override;
369
370 // Returns number of bytes available for reading. When the rest of the file
371 // is available, the number returned will be greater than the number
372 // or readable bytes. If an error occurs, -1 is returned.
373 int64_t Available() const;
374
375 // Seek to a different position.
376 // If there is a pending Wait(), it will be cancelled.
377 void Seek(int64_t pos);
378
379 // Returns the current position.
380 int64_t Tell() const { return pos_; }
381
382 // Tries to read |len| bytes and advance position.
383 // Returns number of bytes read.
384 // If there is a pending Wait(), it will be cancelled.
385 int64_t TryRead(unsigned char *data, int64_t len);
386
387 // Wait until |len| bytes are available for reading.
388 // Returns net::OK if |len| bytes are already available, otherwise it will
389 // return net::ERR_IO_PENDING and call |cb| at some point later.
390 // |len| must be smaller or equal to max_buffer_forward.
391 int Wait(int64_t len, base::Closure cb);
392
393 // Set how much data we try to preload into the cache ahead of our current
394 // location. Normally, we preload until we have preload_high bytes, then
395 // stop until we fall below preload_low bytes. Note that preload can be
396 // set higher than max_buffer_forward, but the result is usually that
397 // some blocks will be freed between the current position and the preload
398 // position.
399 void SetPreload(int64_t preload_high, int64_t preload_low);
400
401 // Adjusts max_buffer_forward and max_buffer_backsard.
402 void SetMaxBuffer(int64_t backward, int64_t forward);
403
404 // Returns true if we are currently loading data.
405 bool IsLoading() const;
406
407 // Reader implementation.
408 void NotifyAvailableRange(
409 const Range<MultiBufferBlockId>& range) override;
410 void UpdateURLId(MultiBufferUrlId old_url_id,
411 MultiBufferUrlId new_url_id) override;
412
413 // Getters
414 MultiBufferUrlId GetURLId() const { return url_id_; }
415 int64_t preload_high() const { return preload_high_; }
416 int64_t preload_low() const { return preload_low_; }
417
418 private:
419 // Returns the block for a particular byte position.
420 MultiBufferBlockId block(int64_t byte_pos) const;
421
422 // Returns the block for a particular byte position, rounding up.
423 MultiBufferBlockId block_ceil(int64_t byte_pos) const;
424
425 // Check if wait operation can complete now.
426 // Returns false if this object was destroyed while calling the
427 // wait callback, true otherwise.
428 bool CheckWait();
429
430 // Increment preload position if data has been added to the buffer.
431 // Returns false if this object was destroyed, true otherwise.
432 bool IncrementPreloadPos();
433
434 // The ID of the url we're accessing.
435 MultiBufferUrlId url_id_;
436
437 // We're not interested in reading past this position.
438 int64_t end_;
439
440 // Defer reading once we have this much data.
441 int64_t preload_high_;
442 // Stop deferring once we have this much data.
443 int64_t preload_low_;
444
445 // Pin this much data in the cache from the current position.
446 int64_t max_buffer_forward_;
447 int64_t max_buffer_backward_;
448
449 // Current position in bytes.
450 int64_t pos_;
451
452 // [block(pos_)..preload_pos_) are known to be in the cache.
453 // preload_pos_ is only allowed to point to a filled
454 // cache position if it is equal to end_ or pos_+preload_.
455 // This is a pointer to a slot in the cache, so the unit is
456 // blocks.
457 MultiBufferBlockId preload_pos_;
458
459 // True if we've requested data from the cache by calling WaitFor().
460 bool loading_;
461
462 // When Available() > current_wait_size_ we call cb_.
463 int64_t current_wait_size_;
464 base::Closure cb_;
465
466 // Progress callback.
467 base::Callback<void(int64_t, int64_t)> progress_callback_;
468
469 // Hack to let us detect if we've been deleted when calling a callback.
470 bool* clear_on_delete_;
471
472 // The multibuffer we're wrapping, not owned.
473 MultiBuffer* multibuffer_;
474 };
475
476 } // namespace media
477
478 #endif // MEDIA_BLINK_MULTIBUFFER_H_
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698