Debian Codegraph @

src/packets.rs

raw symbols SCIP
1 use crate::Page;
2 use crate::error::{PageError, Result};
3 use crate::header::PageHeader;
4 use crate::paginate::paginate;
5
6 use std::fmt::{Debug, Formatter};
7 use std::io::{Read, Seek, Write};
8 use std::ops::Range;
9
10 /// A container for packets in an OGG file
11 pub struct Packets {
12 content: Vec<u8>,
13 packet_sizes: Vec<u64>,
14 }
15
16 impl Packets {
17 /// Read as many packets as possible from a reader
18 ///
19 /// # Errors
20 ///
21 /// A page has a bad length
22 ///
23 /// # Examples
24 ///
25 /// ```rust
26 /// use ogg_pager::Packets;
27 ///
28 /// # fn main() -> Result<(), ogg_pager::PageError> {
29 /// # let path = "../lofty/tests/files/assets/minimal/full_test.ogg";
30 /// let mut file = std::fs::File::open(path)?;
31 ///
32 /// let packets = Packets::read(&mut file)?;
33 /// # Ok(()) }
34 /// ```
35 pub fn read<R>(data: &mut R) -> Result<Self>
36 where
37 R: Read + Seek,
38 {
39 Self::read_count(data, -1)
40 }
41
42 /// Read a specific number of packets from a reader
43 ///
44 /// A special value of `-1` will read as many packets as possible,
45 /// in which case [`Packets::read`] should be used.
46 ///
47 /// NOTE: Any value 0 or below will return an empty [`Packets`]
48 ///
49 /// # Errors
50 ///
51 /// * Unable to read the specified number of packets
52 /// * A page has a bad length
53 ///
54 /// # Examples
55 ///
56 /// ```rust
57 /// use ogg_pager::Packets;
58 ///
59 /// # fn main() -> Result<(), ogg_pager::PageError> {
60 /// # let path = "../lofty/tests/files/assets/minimal/full_test.ogg";
61 /// let mut file = std::fs::File::open(path)?;
62 ///
63 /// // We know that the file has at least 2 packets in it
64 /// let packets = Packets::read_count(&mut file, 2)?;
65 /// # Ok(()) }
66 /// ```
67 #[allow(clippy::read_zero_byte_vec)]
68 pub fn read_count<R>(data: &mut R, count: isize) -> Result<Self>
69 where
70 R: Read + Seek,
71 {
72 let mut content = Vec::new();
73 let mut packet_sizes = Vec::new();
74
75 if count == 0 || count < -1 {
76 return Ok(Self {
77 content,
78 packet_sizes,
79 });
80 }
81
82 let mut packets_read = 0;
83
84 let mut packet_size = 0_u64;
85 let mut packet_bytes_already_read = None;
86 let mut current_packet_content;
87 'outer: while let Ok(header) = PageHeader::read(data) {
88 for i in header.segments {
89 packet_size += u64::from(i);
90
91 if i < 255 {
92 if count != -1 {
93 packets_read += 1;
94 }
95
96 let byte_count_to_read =
97 Self::get_byte_count_to_read(packet_size, &mut packet_bytes_already_read);
98
99 current_packet_content = vec![0; byte_count_to_read as usize];
100 data.read_exact(&mut current_packet_content)?;
101
102 packet_sizes.push(packet_size);
103 packet_size = 0;
104 packet_bytes_already_read = None;
105
106 content.append(&mut current_packet_content);
107
108 if packets_read == count {
109 break 'outer;
110 }
111 }
112 }
113
114 // The packet continues on the next page, write what we can so far
115 if packet_size != 0 {
116 let byte_count_to_read =
117 Self::get_byte_count_to_read(packet_size, &mut packet_bytes_already_read);
118
119 current_packet_content = vec![0; byte_count_to_read as usize];
120 data.read_exact(&mut current_packet_content)?;
121 content.append(&mut current_packet_content);
122 }
123
124 continue;
125 }
126
127 if count != -1 && packet_sizes.len() != count as usize {
128 return Err(PageError::NotEnoughData);
129 }
130
131 Ok(Self {
132 content,
133 packet_sizes,
134 })
135 }
136
137 fn get_byte_count_to_read(
138 packet_size: u64,
139 packet_bytes_already_read: &mut Option<u64>,
140 ) -> u64 {
141 let byte_count_to_read;
142 match packet_bytes_already_read {
143 Some(already_read_bytes_count) => {
144 byte_count_to_read = packet_size - *already_read_bytes_count;
145 *packet_bytes_already_read = Some(*already_read_bytes_count + byte_count_to_read);
146 },
147 None => {
148 byte_count_to_read = packet_size;
149 *packet_bytes_already_read = Some(packet_size);
150 },
151 }
152
153 byte_count_to_read
154 }
155
156 /// Returns the number of packets
157 ///
158 /// # Examples
159 ///
160 /// ```rust
161 /// use ogg_pager::Packets;
162 ///
163 /// # fn main() -> Result<(), ogg_pager::PageError> {
164 /// # let path = "../lofty/tests/files/assets/minimal/full_test.ogg";
165 /// let mut file = std::fs::File::open(path)?;
166 ///
167 /// // I want to read 2 packets
168 /// let packets = Packets::read_count(&mut file, 2)?;
169 ///
170 /// // And that's what I received!
171 /// assert_eq!(packets.len(), 2);
172 /// # Ok(()) }
173 /// ```
174 pub fn len(&self) -> usize {
175 self.packet_sizes.len()
176 }
177
178 /// Returns true if there are no packets
179 ///
180 /// # Examples
181 ///
182 /// ```rust
183 /// use ogg_pager::Packets;
184 ///
185 /// # fn main() -> Result<(), ogg_pager::PageError> {
186 /// # let path = "../lofty/tests/files/assets/minimal/full_test.ogg";
187 /// let mut file = std::fs::File::open(path)?;
188 ///
189 /// let packets = Packets::read(&mut file)?;
190 ///
191 /// // My file contains packets!
192 /// assert!(!packets.is_empty());
193 /// # Ok(()) }
194 /// ```
195 pub fn is_empty(&self) -> bool {
196 self.packet_sizes.is_empty()
197 }
198
199 fn packet_span(&self, idx: usize) -> Option<Range<usize>> {
200 if idx >= self.packet_sizes.len() {
201 return None;
202 }
203
204 let start_pos = match idx {
205 // Packet 0 starts at pos 0
206 0 => 0,
207 other => self.packet_sizes[..other].iter().sum::<u64>() as usize,
208 };
209
210 if let Some(packet_size) = self.packet_sizes.get(idx) {
211 return Some(start_pos..start_pos + *packet_size as usize);
212 }
213
214 None
215 }
216
217 /// Gets the packet at a specified index, returning its contents
218 ///
219 /// NOTES:
220 ///
221 /// * This is zero-indexed
222 /// * If the index is out of bounds, it will return [`None`]
223 ///
224 /// # Examples
225 ///
226 /// ```rust
227 /// use ogg_pager::Packets;
228 ///
229 /// # fn main() -> Result<(), ogg_pager::PageError> {
230 /// # let path = "../lofty/tests/files/assets/minimal/full_test.ogg";
231 /// let mut file = std::fs::File::open(path)?;
232 ///
233 /// let packets = Packets::read(&mut file)?;
234 ///
235 /// let first_packet = packets.get(0);
236 /// assert!(first_packet.is_some());
237 ///
238 /// let out_of_bounds = packets.get(1000000);
239 /// assert!(out_of_bounds.is_none());
240 /// # Ok(()) }
241 /// ```
242 pub fn get(&self, idx: usize) -> Option<&[u8]> {
243 self.packet_span(idx).map(|range| &self.content[range])
244 }
245
246 /// Sets the packet content, if it exists
247 ///
248 /// NOTES:
249 ///
250 /// * This is zero-indexed
251 /// * If the index is out of bounds, it will return `false`
252 ///
253 /// # Examples
254 ///
255 /// ```rust
256 /// use ogg_pager::Packets;
257 ///
258 /// # fn main() -> Result<(), ogg_pager::PageError> {
259 /// # let path = "../lofty/tests/files/assets/minimal/full_test.ogg";
260 /// let mut file = std::fs::File::open(path)?;
261 ///
262 /// let mut packets = Packets::read(&mut file)?;
263 ///
264 /// let new_content = [0; 100];
265 ///
266 /// assert_ne!(packets.get(0), Some(new_content.as_slice()));
267 ///
268 /// // Set our new content
269 /// assert!(packets.set(0, new_content));
270 ///
271 /// // Now our packet contains the new content
272 /// assert_eq!(packets.get(0), Some(new_content.as_slice()));
273 ///
274 /// // We cannot index out of bounds
275 /// assert!(!packets.set(1000000, new_content));
276 /// # Ok(()) }
277 /// ```
278 pub fn set(&mut self, idx: usize, content: impl Into<Vec<u8>>) -> bool {
279 let Some(range) = self.packet_span(idx) else {
280 return false;
281 };
282
283 let content = content.into();
284 let content_size = content.len();
285
286 self.content.splice(range, content);
287 self.packet_sizes[idx] = content_size as u64;
288
289 true
290 }
291
292 /// Returns an iterator over the packets
293 ///
294 /// # Examples
295 ///
296 /// ```rust
297 /// use ogg_pager::Packets;
298 ///
299 /// # fn main() -> Result<(), ogg_pager::PageError> {
300 /// # let path = "../lofty/tests/files/assets/minimal/full_test.ogg";
301 /// let mut file = std::fs::File::open(path)?;
302 ///
303 /// let packets = Packets::read(&mut file)?;
304 ///
305 /// for packet in packets.iter() {
306 /// println!("Packet size: {}", packet.len());
307 /// }
308 /// # Ok(()) }
309 pub fn iter(&self) -> PacketsIter<'_> {
310 <&Self as IntoIterator>::into_iter(self)
311 }
312
313 /// Convert the packets into a stream of pages
314 ///
315 /// See [paginate()] for more information.
316 ///
317 /// # Errors
318 ///
319 /// See [`paginate()`]
320 ///
321 /// # Examples
322 ///
323 /// ```rust
324 /// use ogg_pager::{CONTAINS_FIRST_PAGE_OF_BITSTREAM, CONTAINS_LAST_PAGE_OF_BITSTREAM, Packets};
325 ///
326 /// # fn main() -> Result<(), ogg_pager::PageError> {
327 /// # let path = "../lofty/tests/files/assets/minimal/full_test.ogg";
328 /// let mut file = std::fs::File::open(path)?;
329 ///
330 /// let mut packets = Packets::read(&mut file)?;
331 ///
332 /// let stream_serial_number = 1234;
333 /// let absolute_granule_position = 0;
334 /// let flags = CONTAINS_FIRST_PAGE_OF_BITSTREAM | CONTAINS_LAST_PAGE_OF_BITSTREAM;
335 ///
336 /// let pages = packets.paginate(stream_serial_number, absolute_granule_position, flags)?;
337 ///
338 /// println!("We created {} pages!", pages.len());
339 /// # Ok(()) }
340 /// ```
341 pub fn paginate(&self, stream_serial: u32, abgp: u64, flags: u8) -> Result<Vec<Page>> {
342 let mut packets = Vec::new();
343
344 let mut pos = 0;
345 for packet_size in self.packet_sizes.iter().copied() {
346 packets.push(&self.content[pos..pos + packet_size as usize]);
347 pos += packet_size as usize;
348 }
349
350 paginate(packets, stream_serial, abgp, flags)
351 }
352
353 /// Write packets to a writer
354 ///
355 /// This will paginate and write all of the packets to a writer.
356 ///
357 /// # Errors
358 ///
359 /// * Unable to write, see [`std::io::Error`]
360 ///
361 /// # Examples
362 ///
363 /// ```rust,no_run
364 /// use ogg_pager::{CONTAINS_FIRST_PAGE_OF_BITSTREAM, CONTAINS_LAST_PAGE_OF_BITSTREAM, Packets};
365 /// use std::fs::OpenOptions;
366 ///
367 /// # fn main() -> Result<(), ogg_pager::PageError> {
368 /// let mut file = std::fs::File::open("foo.ogg")?;
369 ///
370 /// let mut packets = Packets::read(&mut file)?;
371 ///
372 /// let stream_serial_number = 1234;
373 /// let absolute_granule_position = 0;
374 /// let flags = CONTAINS_FIRST_PAGE_OF_BITSTREAM | CONTAINS_LAST_PAGE_OF_BITSTREAM;
375 ///
376 /// let mut new_file = OpenOptions::new().write(true).open("bar.ogg")?;
377 /// let pages_written = packets.write_to(
378 /// &mut new_file,
379 /// stream_serial_number,
380 /// absolute_granule_position,
381 /// flags,
382 /// )?;
383 ///
384 /// println!("We wrote {} pages!", pages_written);
385 /// # Ok(()) }
386 /// ```
387 pub fn write_to<W>(
388 &self,
389 writer: &mut W,
390 stream_serial: u32,
391 abgp: u64,
392 flags: u8,
393 ) -> Result<usize>
394 where
395 W: Write,
396 {
397 let paginated = self.paginate(stream_serial, abgp, flags)?;
398 let num_pages = paginated.len();
399
400 for mut page in paginated {
401 page.gen_crc();
402 writer.write_all(&page.as_bytes())?;
403 }
404
405 Ok(num_pages)
406 }
407 }
408
409 /// An iterator over packets
410 ///
411 /// This is created by calling `into_iter` on [`Packets`]
412 #[derive(Clone, PartialEq, Eq, Debug)]
413 pub struct PacketsIter<'a> {
414 content: &'a [u8],
415 packet_sizes: &'a [u64],
416 cap: usize,
417 }
418
419 impl<'a> Iterator for PacketsIter<'a> {
420 type Item = &'a [u8];
421
422 fn next(&mut self) -> Option<Self::Item> {
423 if self.cap == 0 {
424 return None;
425 }
426
427 let packet_size = self.packet_sizes[0];
428
429 self.cap -= 1;
430 self.packet_sizes = &self.packet_sizes[1..];
431
432 let (ret, remaining) = self.content.split_at(packet_size as usize);
433 self.content = remaining;
434
435 Some(ret)
436 }
437 }
438
439 impl<'a> IntoIterator for &'a Packets {
440 type Item = &'a [u8];
441 type IntoIter = PacketsIter<'a>;
442
443 fn into_iter(self) -> Self::IntoIter {
444 PacketsIter {
445 content: &self.content,
446 packet_sizes: &self.packet_sizes,
447 cap: self.packet_sizes.len(),
448 }
449 }
450 }
451
452 impl Debug for Packets {
453 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
454 f.debug_struct("Packets")
455 .field("total_bytes", &self.content.len())
456 .field("count", &self.packet_sizes.len())
457 .finish()
458 }
459 }