R/audio.R

Defines functions parse_ffmpeg_out_fast parse_ffmpeg_out

Documented in parse_ffmpeg_out parse_ffmpeg_out_fast

#' parse_ffmpeg_out
#'
#' Interprets the log file generated by ffmpeg with the loudness detail
#'
#' @param filepath path to the file to be processed
#' @param nlines read blocks of so many lines
#' @param compact_fmt Compact format for output (Default TRUE)
#'
#' @return a data.frame with loudness data
#' @export
#'
#' @examples
#'
#' \dontrun{
#' parse_ffmpeg_out('ffmpeg.out', nlines = 1000)
#' }
parse_ffmpeg_out <- function(filepath, nlines = 1, compact_fmt = TRUE) {

  pattern <- "t:\\s*(\\d*\\.?\\d*)\\s*M:\\s*(-\\d*\\.?\\d*)\\s*S:\\s*(-\\d*\\.?\\d*)\\s*I:\\s*(-\\d*\\.?\\d*)\\s*LUFS\\s*LRA:\\s*(\\d*\\.?\\d*)\\s*LU"
  con = file(filepath, "r")
  dflist <-  list()
  e <- 1
  while ( TRUE ) {
    lines = readLines(con, nlines)
    if ( length(lines) == 0 ) {
      break
    } else {
      for (i in 1:length(lines)){
        capture <- gsub(pattern, "\\1,\\2,\\3,\\4,\\5", regmatches(lines[i], gregexpr(pattern,lines[i])))
        data <- strsplit(capture, ",")[[1]]
        if (length(data) == 5) {
          data <- as.numeric(data)
          dflist[[e]] <- data.frame(t=data[1], M=data[2], S=data[3], I=data[4], LRA=data[5])
          e <- e + 1
        }
      }
    }
  }
  close(con)
  do.call('rbind', dflist)
}

#' parse_ffmpeg_out_fast
#'
#' Interprets the log file generated by ffmpeg with the loudness detail
#'
#' @param filepath path to the file to be processed
#' @param nlines number of buffered lines
#' @param compact_fmt Compact format for output (Default TRUE)
#'
#' @return a data.frame with loudness data
#' @export
#'
#' @examples
#'
#' \dontrun{
#' parse_ffmpeg_out_fast('ffmpeg.out')
#'}
parse_ffmpeg_out_fast <- function(filepath, nlines = 1, compact_fmt = TRUE) {

  pattern <- "t:\\s*(\\d*\\.?\\d*)\\s*M:\\s*(-\\d*\\.?\\d*)\\s*S:\\s*(-\\d*\\.?\\d*)\\s*I:\\s*(-\\d*\\.?\\d*)\\s*LUFS\\s*LRA:\\s*(\\d*\\.?\\d*)\\s*LU"
  dflist <-  list()
  e <- 1

  lines = readlines(filepath)
  assert(length(lines) > 0 , paste("Error when read", filepath))
  for (i in 1:length(lines)){
    capture <- gsub(pattern, "\\1,\\2,\\3,\\4,\\5", regmatches(lines[i], gregexpr(pattern,lines[i])))
    data <- strsplit(capture, ",")[[1]]
    if (length(data) == 5) {
      data <- as.numeric(data)
      dflist[[e]] <- data.frame(t=data[1], M=data[2], S=data[3], I=data[4], LRA=data[5])
      e <- e + 1
    }
  }
  do.call('rbind', dflist)
}
pmoracho/loudness documentation built on July 16, 2021, 2:04 p.m.