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

Side by Side Diff: chrome/browser/media/webrtc_rtp_dump_writer.cc

Issue 264793017: Implements RTP header dumping. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Created 6 years, 7 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 2014 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 #include "chrome/browser/media/webrtc_rtp_dump_writer.h"
6
7 #include "base/big_endian.h"
8 #include "base/file_util.h"
9 #include "base/logging.h"
10 #include "content/public/browser/browser_thread.h"
11 #include "third_party/zlib/zlib.h"
12
13 using content::BrowserThread;
14 using content::RtpDumpType;
15 using content::RTP_DUMP_BOTH;
16 using content::RTP_DUMP_INCOMING;
17 using content::RTP_DUMP_OUTGOING;
18
19 namespace {
20
21 // The header of the dump file.
22 struct RtpDumpFileHeader {
23 static const unsigned char kFirstLine[];
24
25 explicit RtpDumpFileHeader(const base::TimeTicks& start)
26 : start_sec(0), start_usec(0), source(0), port(0), padding(0) {
27 base::TimeDelta interval(start - base::TimeTicks());
28 start_sec = interval.InSeconds();
29 start_usec =
30 interval.InMilliseconds() * base::Time::kMicrosecondsPerMillisecond;
31 }
32
33 void WriteBigEndian(std::vector<uint8>* output) {
34 size_t buffer_start_pos = output->size();
35 output->resize(output->size() + sizeof(RtpDumpFileHeader));
36
37 char* buffer = reinterpret_cast<char*>(output->data() + buffer_start_pos);
38
39 base::WriteBigEndian(buffer, start_sec);
40 buffer += sizeof(start_sec);
41
42 base::WriteBigEndian(buffer, start_usec);
43 buffer += sizeof(start_usec);
44
45 base::WriteBigEndian(buffer, source);
46 buffer += sizeof(source);
47
48 base::WriteBigEndian(buffer, port);
49 buffer += sizeof(port);
50
51 base::WriteBigEndian(buffer, padding);
52 }
53
54 uint32 start_sec; // start of recording, the seconds part.
55 uint32 start_usec; // start of recording, the microseconds part.
56 uint32 source; // network source (multicast address). Always 0.
57 uint16 port; // UDP port. Always 0.
58 uint16 padding; // 2 bytes padding.
59 };
60
61 const unsigned char RtpDumpFileHeader::kFirstLine[] =
62 "#!rtpplay1.0 0.0.0.0/0\n";
63
64 // The header for each packet dump.
65 struct PacketDumpHeader {
66 PacketDumpHeader(const base::TimeTicks& start,
67 uint16 dump_length,
68 uint16 packet_length)
69 : packet_dump_length(dump_length),
70 packet_length(packet_length),
71 offset_ms((base::TimeTicks::Now() - start).InMilliseconds()) {}
72
73 void WriteBigEndian(std::vector<uint8>* output) {
74 size_t buffer_start_pos = output->size();
75 output->resize(output->size() + sizeof(PacketDumpHeader));
76
77 char* buffer = reinterpret_cast<char*>(output->data() + buffer_start_pos);
78
79 base::WriteBigEndian(buffer, packet_dump_length);
80 buffer += sizeof(packet_dump_length);
81
82 base::WriteBigEndian(buffer, packet_length);
83 buffer += sizeof(packet_length);
84
85 base::WriteBigEndian(buffer, offset_ms);
86 }
87
88 // Length of the packet dump including this header.
89 uint16 packet_dump_length;
90
91 // Length of header + payload of the RTP packet.
92 uint16 packet_length;
93
94 // Milliseconds since the start of recording.
95 uint32 offset_ms;
96 };
97
98 // Append |src_len| bytes from |src| to |dest|.
99 bool AppendToBuffer(const uint8* src,
100 size_t src_len,
101 std::vector<uint8>* dest) {
102 if (dest->capacity() < dest->size() + src_len)
103 return false;
104
105 for (size_t i = 0; i < src_len; ++i) {
106 dest->push_back(src[i]);
107 }
108 return true;
109 }
110
111 static const size_t kMinimumGzipOutputBufferSize = 256;
112
113 } // namespace
114
115 // This class is running on the FILE thread for compressing and writing the
116 // dump buffer to disk.
117 class WebRtcRtpDumpWriter::FileThreadWorker {
118 public:
119 explicit FileThreadWorker(const base::FilePath& dump_path)
120 : dump_path_(dump_path), stream_initialized_(false) {
121 thread_checker_.DetachFromThread();
122 }
123
124 ~FileThreadWorker() { DCHECK(thread_checker_.CalledOnValidThread()); }
125
126 // Compresses the data in |buffer| write to the dump file. If |end_stream| is
127 // true, the compression stream will be ended and the dump file cannot be
128 // written to any more.
129 void CompressAndWriteToFileOnFileThread(
130 const scoped_ptr<std::vector<uint8> >& buffer,
131 bool end_stream,
132 FlushResult* result,
133 size_t* bytes_written) {
134 DCHECK(thread_checker_.CalledOnValidThread());
135
136 *result = FLUSH_RESULT_SUCCESS;
137 *bytes_written = 0;
138
139 if (buffer->size()) {
140 *bytes_written = CompressAndWriteBufferToFile(buffer.get(), result);
141 } else if (!base::PathExists(dump_path_)) {
142 *result = FLUSH_RESULT_NO_DATA;
143 }
144
145 if (end_stream) {
146 if (!EndDumpFile())
147 *result = FLUSH_RESULT_FAILURE;
148 }
149 }
150
151 private:
152 // Helper for CompressAndWriteToFileOnFileThread to compress and write one
153 // dump.
154 size_t CompressAndWriteBufferToFile(std::vector<uint8>* buffer,
155 FlushResult* result) {
156 DCHECK(thread_checker_.CalledOnValidThread());
157 DCHECK(buffer->size());
158
159 *result = FLUSH_RESULT_SUCCESS;
160
161 std::vector<uint8> compressed_buffer;
162 if (!Compress(buffer, &compressed_buffer)) {
163 DVLOG(2) << "Compressing buffer failed.";
164 *result = FLUSH_RESULT_FAILURE;
165 return 0;
166 }
167
168 int bytes_written = -1;
169
170 if (base::PathExists(dump_path_)) {
171 bytes_written = base::AppendToFile(
172 dump_path_,
173 reinterpret_cast<const char*>(compressed_buffer.data()),
174 compressed_buffer.size());
175 } else {
176 bytes_written = base::WriteFile(
177 dump_path_,
178 reinterpret_cast<const char*>(compressed_buffer.data()),
179 compressed_buffer.size());
180 }
181
182 if (bytes_written == -1) {
183 DVLOG(2) << "Writing file failed: " << dump_path_.value();
184 *result = FLUSH_RESULT_FAILURE;
185 return 0;
186 }
187
188 DCHECK_EQ(static_cast<size_t>(bytes_written), compressed_buffer.size());
189
190 return bytes_written;
191 }
192
193 // Compresses |input| into |output|.
194 bool Compress(std::vector<uint8>* input, std::vector<uint8>* output) {
195 DCHECK(thread_checker_.CalledOnValidThread());
196 int result = Z_OK;
197
198 output->resize(std::max(kMinimumGzipOutputBufferSize, input->size()));
199
200 if (!stream_initialized_) {
201 memset(&stream_, 0, sizeof(stream_));
202 result = deflateInit2(&stream_,
203 Z_DEFAULT_COMPRESSION,
204 Z_DEFLATED,
205 // windowBits = 15 is default, 16 is added to
206 // produce a gzip header + trailer.
207 15 + 16,
208 8, // memLevel = 8 is default.
209 Z_DEFAULT_STRATEGY);
210 DCHECK_EQ(Z_OK, result);
211 stream_initialized_ = true;
212 }
213
214 stream_.next_in = input->data();
215 stream_.avail_in = input->size();
216 stream_.next_out = output->data();
217 stream_.avail_out = output->size();
218
219 result = deflate(&stream_, Z_SYNC_FLUSH);
220 DCHECK_EQ(Z_OK, result);
221 DCHECK_EQ(0U, stream_.avail_in);
222
223 output->resize(output->size() - stream_.avail_out);
224
225 stream_.next_in = NULL;
226 stream_.next_out = NULL;
227 stream_.avail_out = 0;
228 return true;
229 }
230
231 // Ends the compression stream and completes the dump file.
232 bool EndDumpFile() {
233 DCHECK(thread_checker_.CalledOnValidThread());
234
235 if (!stream_initialized_)
236 return true;
237
238 std::vector<uint8> output_buffer;
239 output_buffer.resize(kMinimumGzipOutputBufferSize);
240
241 stream_.next_in = NULL;
242 stream_.avail_in = 0;
243 stream_.next_out = output_buffer.data();
244 stream_.avail_out = output_buffer.size();
245
246 int result = deflate(&stream_, Z_FINISH);
247 DCHECK_EQ(Z_STREAM_END, result);
248
249 result = deflateEnd(&stream_);
250 DCHECK_EQ(Z_OK, result);
251
252 output_buffer.resize(output_buffer.size() - stream_.avail_out);
253
254 int bytes_written =
255 base::AppendToFile(dump_path_,
256 reinterpret_cast<const char*>(output_buffer.data()),
257 output_buffer.size());
258
259 return bytes_written > 0;
260 }
261
262 const base::FilePath dump_path_;
263
264 z_stream stream_;
265 bool stream_initialized_;
266
267 base::ThreadChecker thread_checker_;
268
269 DISALLOW_COPY_AND_ASSIGN(FileThreadWorker);
270 };
271
272 WebRtcRtpDumpWriter::WebRtcRtpDumpWriter(
273 const base::FilePath& incoming_dump_path,
274 const base::FilePath& outgoing_dump_path,
275 size_t max_dump_size,
276 const base::Closure& max_dump_size_reached_callback)
277 : max_dump_size_(max_dump_size),
278 max_dump_size_reached_callback_(max_dump_size_reached_callback),
279 total_dump_size_on_disk_(0),
280 incoming_file_thread_worker_(new FileThreadWorker(incoming_dump_path)),
281 outgoing_file_thread_worker_(new FileThreadWorker(outgoing_dump_path)),
282 weak_ptr_factory_(this) {
283 }
284
285 WebRtcRtpDumpWriter::~WebRtcRtpDumpWriter() {
286 DCHECK(thread_checker_.CalledOnValidThread());
287 if (BrowserThread::DeleteSoon(
288 BrowserThread::FILE, FROM_HERE, incoming_file_thread_worker_.get())) {
289 ignore_result(incoming_file_thread_worker_.release());
290 } else {
291 incoming_file_thread_worker_.reset();
292 }
293
294 if (BrowserThread::DeleteSoon(
295 BrowserThread::FILE, FROM_HERE, outgoing_file_thread_worker_.get())) {
296 ignore_result(outgoing_file_thread_worker_.release());
297 } else {
298 outgoing_file_thread_worker_.reset();
299 }
300 }
301
302 void WebRtcRtpDumpWriter::WriteRtpPacket(const uint8* packet_header,
303 size_t header_length,
304 size_t packet_length,
305 bool incoming) {
306 DCHECK(thread_checker_.CalledOnValidThread());
307
308 static const size_t kMaxInMemoryBufferSize = 65536; // 64KB
309
310 std::vector<uint8>* dest_buffer =
311 incoming ? &incoming_buffer_ : &outgoing_buffer_;
312 bool succeeded = true;
313 if (!dest_buffer->capacity()) {
314 dest_buffer->reserve(std::min(kMaxInMemoryBufferSize, max_dump_size_));
315
316 start_time_ = base::TimeTicks::Now();
317
318 // Writes the dump file header.
319 succeeded = AppendToBuffer(RtpDumpFileHeader::kFirstLine,
320 arraysize(RtpDumpFileHeader::kFirstLine) - 1,
321 dest_buffer);
322 DCHECK(succeeded);
323
324 RtpDumpFileHeader header(start_time_);
325 header.WriteBigEndian(dest_buffer);
326 }
327
328 size_t packet_dump_length = sizeof(PacketDumpHeader) + header_length;
329
330 // Flushes the buffer to disk if the buffer is full.
331 if (dest_buffer->capacity() < dest_buffer->size() + packet_dump_length)
332 FlushBuffer(incoming, false, FlushDoneCallback());
333
334 // Writes the packet dump header.
335 PacketDumpHeader packet_dump_header(
336 start_time_, packet_dump_length, packet_length);
337 packet_dump_header.WriteBigEndian(dest_buffer);
338
339 // Writes the actual RTP packet header.
340 succeeded = AppendToBuffer(packet_header, header_length, dest_buffer);
341 DCHECK(succeeded);
342 }
343
344 void WebRtcRtpDumpWriter::EndDump(RtpDumpType type,
345 const EndDumpCallback& finished_callback) {
346 DCHECK(thread_checker_.CalledOnValidThread());
347
348 bool incoming = (type == RTP_DUMP_BOTH || type == RTP_DUMP_INCOMING);
349 EndDumpContext context(type, finished_callback);
350
351 FlushBuffer(incoming,
352 true,
353 base::Bind(&WebRtcRtpDumpWriter::OnDumpEnded,
354 weak_ptr_factory_.GetWeakPtr(),
355 context,
356 incoming));
357 }
358
359 WebRtcRtpDumpWriter::EndDumpContext::EndDumpContext(
360 RtpDumpType type,
361 const EndDumpCallback& callback)
362 : type(type),
363 incoming_succeeded(false),
364 outgoing_succeeded(false),
365 callback(callback) {
366 }
367
368 WebRtcRtpDumpWriter::EndDumpContext::~EndDumpContext() {
369 }
370
371 void WebRtcRtpDumpWriter::FlushBuffer(bool incoming,
372 bool end_stream,
373 const FlushDoneCallback& callback) {
374 DCHECK(thread_checker_.CalledOnValidThread());
375
376 scoped_ptr<std::vector<uint8> > new_buffer(new std::vector<uint8>());
377
378 if (incoming) {
379 new_buffer->reserve(incoming_buffer_.capacity());
380 new_buffer->swap(incoming_buffer_);
381 } else {
382 new_buffer->reserve(outgoing_buffer_.capacity());
383 new_buffer->swap(outgoing_buffer_);
384 }
385
386 scoped_ptr<FlushResult> result(new FlushResult(FLUSH_RESULT_FAILURE));
387
388 scoped_ptr<size_t> bytes_written(new size_t(0));
389
390 FileThreadWorker* worker = incoming ? incoming_file_thread_worker_.get()
391 : outgoing_file_thread_worker_.get();
392
393 // Using "Unretained(worker)" because |worker| is owner by this object and it
394 // guaranteed to be deleted on the FILE thread before this object goes away.
395 BrowserThread::PostTaskAndReply(
396 BrowserThread::FILE,
397 FROM_HERE,
398 base::Bind(&FileThreadWorker::CompressAndWriteToFileOnFileThread,
399 base::Unretained(worker),
400 Passed(&new_buffer),
401 end_stream,
402 result.get(),
403 bytes_written.get()),
404 // OnFlushDone is necessary to avoid running the callback after this
405 // object is gone.
406 base::Bind(&WebRtcRtpDumpWriter::OnFlushDone,
407 weak_ptr_factory_.GetWeakPtr(),
408 callback,
409 Passed(&result),
410 Passed(&bytes_written)));
411 }
412
413 void WebRtcRtpDumpWriter::OnFlushDone(const FlushDoneCallback& callback,
414 const scoped_ptr<FlushResult>& result,
415 const scoped_ptr<size_t>& bytes_written) {
416 DCHECK(thread_checker_.CalledOnValidThread());
417
418 total_dump_size_on_disk_ += *bytes_written;
419
420 if (total_dump_size_on_disk_ >= max_dump_size_ &&
421 !max_dump_size_reached_callback_.is_null()) {
422 max_dump_size_reached_callback_.Run();
423 }
424
425 // Returns success for FLUSH_RESULT_MAX_SIZE_REACHED since the dump is still
426 // valid.
427 if (!callback.is_null()) {
428 callback.Run(*result != FLUSH_RESULT_FAILURE &&
429 *result != FLUSH_RESULT_NO_DATA);
430 }
431 }
432
433 void WebRtcRtpDumpWriter::OnDumpEnded(EndDumpContext context,
434 bool incoming,
435 bool success) {
436 DCHECK(thread_checker_.CalledOnValidThread());
437
438 DVLOG(2) << "Dump ended, incoming = " << incoming
439 << ", succeeded = " << success;
440
441 if (incoming)
442 context.incoming_succeeded = success;
443 else
444 context.outgoing_succeeded = success;
445
446 // End the outgoing dump if needed.
447 if (incoming && context.type == RTP_DUMP_BOTH) {
448 FlushBuffer(false,
449 true,
450 base::Bind(&WebRtcRtpDumpWriter::OnDumpEnded,
451 weak_ptr_factory_.GetWeakPtr(),
452 context,
453 false));
454 return;
455 }
456
457 context.callback.Run(context.incoming_succeeded, context.outgoing_succeeded);
458 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698