7 #include "packager/media/file/io_cache.h"
13 #include "packager/base/logging.h"
15 namespace edash_packager {
18 using base::AutoUnlock;
22 IoCache::IoCache(uint64_t cache_size)
23 : cache_size_(cache_size),
24 read_event_(false, false),
25 write_event_(false, false),
28 circular_buffer_(cache_size + 1),
29 end_ptr_(&circular_buffer_[0] + cache_size + 1),
30 r_ptr_(&circular_buffer_[0]),
31 w_ptr_(&circular_buffer_[0]),
42 while (!closed_ && (BytesCachedInternal() == 0)) {
43 AutoUnlock unlock(lock_);
47 size = std::min(size, BytesCachedInternal());
48 uint64_t first_chunk_size(std::min(size, static_cast<uint64_t>(
50 memcpy(buffer, r_ptr_, first_chunk_size);
51 r_ptr_ += first_chunk_size;
52 DCHECK_GE(end_ptr_, r_ptr_);
53 if (r_ptr_ == end_ptr_)
54 r_ptr_ = &circular_buffer_[0];
55 uint64_t second_chunk_size(size - first_chunk_size);
56 if (second_chunk_size) {
57 memcpy(static_cast<uint8_t*>(buffer) + first_chunk_size, r_ptr_,
59 r_ptr_ += second_chunk_size;
60 DCHECK_GT(end_ptr_, r_ptr_);
69 const uint8_t* r_ptr(static_cast<const uint8_t*>(buffer));
70 uint64_t bytes_left(size);
73 while (!closed_ && (BytesFreeInternal() == 0)) {
74 AutoUnlock unlock(lock_);
80 uint64_t write_size(std::min(bytes_left, BytesFreeInternal()));
81 uint64_t first_chunk_size(std::min(write_size, static_cast<uint64_t>(
83 memcpy(w_ptr_, r_ptr, first_chunk_size);
84 w_ptr_ += first_chunk_size;
85 DCHECK_GE(end_ptr_, w_ptr_);
86 if (w_ptr_ == end_ptr_)
87 w_ptr_ = &circular_buffer_[0];
88 r_ptr += first_chunk_size;
89 uint64_t second_chunk_size(write_size - first_chunk_size);
90 if (second_chunk_size) {
91 memcpy(w_ptr_, r_ptr, second_chunk_size);
92 w_ptr_ += second_chunk_size;
93 DCHECK_GT(end_ptr_, w_ptr_);
94 r_ptr += second_chunk_size;
96 bytes_left -= write_size;
97 write_event_.Signal();
103 AutoLock lock(lock_);
104 r_ptr_ = w_ptr_ = &circular_buffer_[0];
106 read_event_.Signal();
110 AutoLock lock(lock_);
112 read_event_.Signal();
113 write_event_.Signal();
117 AutoLock lock(lock_);
118 return BytesCachedInternal();
122 AutoLock lock(lock_);
123 return BytesFreeInternal();
126 uint64_t IoCache::BytesCachedInternal() {
127 return (r_ptr_ <= w_ptr_) ?
129 (end_ptr_ - r_ptr_) + (w_ptr_ - &circular_buffer_[0]);
132 uint64_t IoCache::BytesFreeInternal() {
133 return cache_size_ - BytesCachedInternal();
137 AutoLock lock(lock_);
138 while (!closed_ && BytesCachedInternal()) {
139 AutoUnlock unlock(lock_);