local SCRIPT_TITLE = 'Loudness from audio file V2.0'

--[[

Synthesizer V Studio Pro Script
 
lua file name: LoudnessFromAudio.lua

Extract loudness audio wave form and apply the corresponding loudness parameters

Warnings! 
AudioFile must be a wav file format!
This version tested on Windows 11 only!

Json source code included:
https://gist.github.com/tylerneylon/59f4bcf316be525b30ab

2025 - JF AVILES
--]]

-- Generated by JFA TranslateScripts.lua
function getTranslations(langCode)
	return getArrayLanguageStrings()[langCode]
end

-- Generated by JFA TranslateScripts.lua
function getArrayLanguageStrings()
	return {
		["en-us"] = {
			{"File: ", "File: "},
			{"Group: ", "Group: "},
			{"Enter the full path audio filename", "Enter the full path audio filename"},
			{"Unsupported float format: only 32-bit float is supported", "Unsupported float format: only 32-bit float is supported"},
			{"tag is nil", "tag is nil"},
			{"Unsupported format tag: ", "Unsupported format tag: "},
			{"Unable to open file: ", "Unable to open file: "},
			{"Invalid file format: missing RIFF header", "Invalid file format: missing RIFF header"},
			{"Invalid file format: missing WAVE header", "Invalid file format: missing WAVE header"},
			{"Invalid file format: missing fmt chunk", "Invalid file format: missing fmt chunk"},
			{"Unsupported bit depth: ", "Unsupported bit depth: "},
			{" (supported: 8, 16, 24, 32)", " (supported: 8, 16, 24, 32)"},
			{"Unsupported format combination: ", "Unsupported format combination: "},
			{"-bit", "-bit"},
			{"Data chunk not found", "Data chunk not found"},
			{"WAV file analyzed:", "WAV file analyzed:"},
			{"  Format: %s %d-bit PCM", "  Format: %s %d-bit PCM"},
			{"  Channels: %d", "  Channels: %d"},
			{"  Sample rate: %d Hz", "  Sample rate: %d Hz"},
			{"  Duration: %.2f seconds", "  Duration: %.2f seconds"},
			{"  Analysis window: %d ms (%d samples)", "  Analysis window: %d ms (%d samples)"},
			{"  File size: %d Kb", "  File size: %d Kb"},
			{"not found!", "not found!"},
			{"WAV Volume Analysis", "WAV Volume Analysis"},
			{"Done!", "Done!"},
			{"Nothing to read!", "Nothing to read!"},
		},
	}
end

function getClientInfo()
	return {
		name = SV:T(SCRIPT_TITLE),
		category = "_JFA_Tools",
		author = "JFAVILES",
		versionNumber = 2,
		minEditorVersion = 65540
	}
end

-- Define a class  "NotesObject"
NotesObject = {
	project = nil,
	timeAxis = nil,
	currentGroupRef = nil,
	currentGroupNotes = nil,
	currentGroupName = "",
	pathAudioFile = "D:/Mes musiques/Autre/GoogleFemale1/", -- put your wave file path for testing only
	audioFile = "GoogleFemale1.wav", -- put your wave file for testing only
	askForWaveFile = true, -- fasle for testing only
	loudnessWeight = 10, -- multiply values (10) to increase loudness
	window_size_ms = 10, -- Default 10ms window
	file_size = 0,
	fmt_size = 0,
	audio_format = 0,
	num_channels = 0,
	sample_rate = 0,
	byte_rate = 0,
	block_align = 0,
	bits_per_sample = 0,
	total_samples = 0,
	sample_readers = {}	-- Sample reading functions based on format
}


-- Constructor method for the NotesObject class
function NotesObject:new()
    local notesObject = {}
    setmetatable(notesObject, self)
    self.__index = self
	
    self.project = SV:getProject()
    self.timeAxis = SV:getProject():getTimeAxis()
	self.currentGroupRef = SV:getMainEditor():getCurrentGroup()
	self.currentGroupNotes = self.currentGroupRef:getTarget()
	self.currentGroupName = self.currentGroupNotes:getName()
    return self
end

-- Show message dialog
function NotesObject:show(message)
	SV:showMessageBox(SV:T(SCRIPT_TITLE), message)
end

-- local functions
-- Function to read a little-endian integer of n bytes
local function read_little_endian(file, n)
    local result = 0
    for i = 0, n - 1 do
        local byte = file:read(1)
        if not byte then return nil end
        result = result + string.byte(byte) * (256 ^ i)
    end
    return result
end

-- Function to read a big-endian integer of n bytes
local function read_big_endian(file, n)
    local result = 0
    for i = 0, n - 1 do
        local byte = file:read(1)
        if not byte then return nil end
        result = result * 256 + string.byte(byte)
    end
    return result
end

-- Function to read IEEE 754 32-bit float (little-endian)
local function read_float32(file)
    local bytes = file:read(4)
    if not bytes or #bytes < 4 then return nil end
    
    local b1, b2, b3, b4 = string.byte(bytes, 1, 4)
    local bits = b4 * 16777216 + b3 * 65536 + b2 * 256 + b1
    
    local sign = (bits >= 2147483648) and -1 or 1
    local exponent = math.floor(bits / 8388608) % 256
    local mantissa = bits % 8388608
    
    if exponent == 0 then
        return sign * mantissa * (2 ^ -149)
    elseif exponent == 255 then
        return (mantissa == 0) and (sign * math.huge) or 0/0 -- inf or nan
    else
        return sign * (1 + mantissa / 8388608) * (2 ^ (exponent - 127))
    end
end

-- Function to read a signed 8-bit integer
local function read_int8(file)
    local value = file:read(1)
    if not value then return nil end
    local byte = string.byte(value)
    return (byte >= 128) and (byte - 256) or byte
end

-- Function to read an unsigned 8-bit integer
local function read_uint8(file)
    local value = file:read(1)
    if not value then return nil end
    return string.byte(value) - 128 -- Convert to signed range for consistency
end

-- Function to read a signed 16-bit integer
local function read_int16(file)
    local value = read_little_endian(file, 2)
    if not value then return nil end
    return (value >= 32768) and (value - 65536) or value
end

-- Function to read a signed 24-bit integer
local function read_int24(file)
    local value = read_little_endian(file, 3)
    if not value then return nil end
    return (value >= 8388608) and (value - 16777216) or value
end

-- Function to read a signed 32-bit integer
local function read_int32(file)
    local value = read_little_endian(file, 4)
    if not value then return nil end
    return (value >= 2147483648) and (value - 4294967296) or value
end

-- Function to calculate RMS (Root Mean Square) of samples
local function calculate_rms(samples)
    if #samples == 0 then return 0 end
    local sum = 0
    for _, sample in ipairs(samples) do
        sum = sum + sample * sample
    end
    return math.sqrt(sum / #samples)
end

-- Function to convert RMS to dB
local function rms_to_db(rms, max_value)
    if rms == 0 then
        return -math.huge -- -∞ dB for silence
    end
    return 20 * math.log(rms / max_value)
end

-- Read file content
function NotesObject:readAll(file)
    local f = assert(io.open(file, "rb"))
    local content = f:read("*all")
    f:close()
    return content
end

-- Check if file exists
function NotesObject:isFileExists(fileName)
	local result = false
	local file = io.open(fileName, "r")
	if file ~= nil then
		io.close(file)
		result = true
	end
	return result
end

function NotesObject:quotedFile(file)
	local quote = '"'
	return quote .. file .. quote
end

-- Get host os
function NotesObject:getHostOs()
	local hostinfo = SV:getHostInfo()
	local osType = hostinfo.osType  -- "macOS", "Linux", "Unknown", "Windows"
	return osType
end

-- Get clean filename
function NotesObject:getCleanFilename(file)
	local filename = file
	if #filename > 0 then
		if string.find(filename, '"') ~= nil then
			filename = filename:gsub('"', '')
		end
	end
	return filename
end

-- Get wave file path
function NotesObject:getWaveFile()
	local filename = SV:showInputBox(SV:T(SCRIPT_TITLE), SV:T("Enter the full path audio filename"), "")
	return filename
end

-- Get object properties
local function getObjectProperties(obj)
	local result = ""
	for k, v in pairs(obj) do
		if obj[k] ~= nil then
			result = result .. "{" .. k .. " : " 
			if type(v) == "table" then
				result = result .. getObjectProperties(v)  .. ","
			else
				result = result .. tostring(v) .. "}"
			end
		end
	end
	return result
end

-- Function to detect sample format from format tag and bits per sample
function NotesObject:get_sample_format(format_tag, bits_per_sample)
	local sampleFormat = ""
	local error = false
	
    if format_tag == 1 then -- PCM
        sampleFormat = "signed"
    elseif format_tag == 3 then -- IEEE Float
        if bits_per_sample == 32 then
            sampleFormat = "float"
        else
            sampleFormat = SV:T("Unsupported float format: only 32-bit float is supported")
			error = true
        end
    elseif format_tag == 65534 then -- EXTENSIBLE
        sampleFormat = "signed" -- Assume signed PCM for EXTENSIBLE
    else
		if format_tag == nil then
			format_tag = SV:T("tag is nil")
		end
		sampleFormat = SV:T("Unsupported format tag: ") .. format_tag
		error = true
    end
	return sampleFormat, error
end

-- Main function to analyze a WAV file
function NotesObject:analyze_wav_file(filename)
    local result = ""
    local infos = ""
	local error = false
    local volume_data = {}
	local sample_reader = nil
	local fileOpened = false
	local max_value = 0
	local sample_format = ""
	local error_Format = ""
	
    local file = io.open(filename, "rb")
    if not file then
		result = SV:T("Unable to open file: ") .. filename
		error = true
    end
    
	if not error then
		fileOpened = true
		-- Read WAV header
		local riff_header = file:read(4)
		if riff_header ~= "RIFF" then
			result = SV:T("Invalid file format: missing RIFF header")
			error = true
		end
	end

	if not error then
		self.file_size = math.floor((tonumber(read_little_endian(file, 4))/1024))
		local wave_header = file:read(4)
		if wave_header ~= "WAVE" then
			result = SV:T("Invalid file format: missing WAVE header")
			error = true
		end
	end

	if not error then
		-- Read empty data chunk
		local data_empty = file:read(4)
		while data_empty and data_empty ~= "fmt " do
			-- Skip unknown chunk
			local chunk_size = read_little_endian(file, 4)
			if chunk_size and chunk_size > 0 then
				file:read(chunk_size)
			end
			data_empty = file:read(4)
		end
		
		if data_empty ~= "fmt " then
			result = SV:T("Invalid file format: missing fmt chunk")
			error = true
		end
	end
	
   	if not error then
 
		self.fmt_size = read_little_endian(file, 4)
		self.audio_format = read_little_endian(file, 2)
		self.num_channels = read_little_endian(file, 2)
		self.sample_rate = read_little_endian(file, 4)
		self.byte_rate = read_little_endian(file, 4)
		self.block_align = read_little_endian(file, 2)
		self.bits_per_sample = read_little_endian(file, 2)
		
		-- Skip any extra fmt data
		if self.fmt_size > 16 then
			file:read(self.fmt_size - 16)
		end
		
		-- Validate supported formats
		local supported_bits = {8, 16, 24, 32}
		local bits_supported = false
		for _, bits in ipairs(supported_bits) do
			if self.bits_per_sample == bits then
				bits_supported = true
				break
			end
		end
		
		if not bits_supported then
			result = SV:T("Unsupported bit depth: ") .. self.bits_per_sample .. SV:T(" (supported: 8, 16, 24, 32)")
			error = true
		end
	end
	
	if not error then
		-- Get sample format and reader		
		sample_format, error_Format = self:get_sample_format(self.audio_format, self.bits_per_sample)
		if error_Format then
			result = sample_format
			error = true
		end
		
		if not error then
			local reader_info = self.sample_readers[self.bits_per_sample] -- [8] or [16] or [24] or [32]
			sample_reader = reader_info[sample_format] -- [16].signed or [24].signed etc. => read_int16(file) or read_int24(file) ...
			max_value = (sample_format == "float") and reader_info.float_max or reader_info.max_value
			
			if not sample_reader then
				result = SV:T("Unsupported format combination: ") .. sample_format .. " " .. self.bits_per_sample .. SV:T("-bit")
				error = true
			end
		end
    end
    
    if not error then
		-- Read data chunk
		local data_header = file:read(4)
		while data_header and data_header ~= "data" do
			-- Skip unknown chunk
			local chunk_size = read_little_endian(file, 4)
			if chunk_size and chunk_size > 0 then
				file:read(chunk_size)
			end
			data_header = file:read(4)
		end
		
		if not data_header or data_header ~= "data" then
			result = SV:T("Data chunk not found")
			error = true
		end
    end
	
	if not error then

		local data_size = read_little_endian(file, 4)
		
		-- Calculate analysis parameters
		local samples_per_window = math.floor((self.sample_rate * self.window_size_ms) / 1000)
		local bytes_per_sample = (self.bits_per_sample / 8) * self.num_channels
		self.total_samples = data_size / bytes_per_sample
		
		infos = SV:T("WAV file analyzed:") .. "\r"
			.. string.format(SV:T("  Format: %s %d-bit PCM"), sample_format, self.bits_per_sample) .. "\r"
			.. string.format(SV:T("  Channels: %d"), self.num_channels) .. "\r"
			.. string.format(SV:T("  Sample rate: %d Hz"), self.sample_rate) .. "\r"
			.. string.format(SV:T("  Duration: %.2f seconds"), self.total_samples / self.sample_rate) .. "\r"
			.. string.format(SV:T("  Analysis window: %d ms (%d samples)"), self.window_size_ms, samples_per_window) .. "\r"
			.. string.format(SV:T("  File size: %d Kb"), self.file_size) .. "\r"
		
		-- Extract volume data
		local current_time = 0
		local finish_analysis = false
		while true do
			local sample_data = {}
			
			-- Read a window of samples
			for i = 1, samples_per_window do
				local sample_sum = 0
				local valid_sample = true
				
				-- Read all channels for this sample
				for channel = 1, self.num_channels do
					local sample = sample_reader(file)
					if not sample then
						valid_sample = false
						finish_analysis = true
						break
					end
					
					-- Normalize float samples
					if sample_format == "float" then
						sample = sample * max_value
					end
					
					sample_sum = sample_sum + math.abs(sample)
				end
				
				if finish_analysis then
					break
				end
				
				if valid_sample then
					-- Average across channels
					table.insert(sample_data, sample_sum / self.num_channels)
				end
			end
			
			if not finish_analysis then
				-- Calculate volume for this window
				if #sample_data > 0 then
					local rms = calculate_rms(sample_data)
					local volume_db = rms_to_db(rms, max_value)
					local volume_normalized = math.max(0, math.min(1, (volume_db + 60) / 60)) -- Normalize -60dB to 0dB -> 0 to 1
					
					table.insert(volume_data, {
						time = current_time,
						volume = volume_normalized,
						volume_db = volume_db,
						rms = rms
					})
					
					current_time = current_time + (self.window_size_ms / 1000)
				end
			else
				break
			end
		end
	end
	
	if fileOpened then 
		file:close()
	end
	
    return error, result, infos, volume_data
end

-- Start project notes processing
function NotesObject:start()
	local result = false
	local filename = ""
	
	self.sample_readers = {
		[8] = {
			signed = read_int8,
			unsigned = read_uint8,
			max_value = 127
		},
		[16] = {
			signed = read_int16,
			unsigned = read_int16, -- 16-bit is typically signed
			max_value = 32767
		},
		[24] = {
			signed = read_int24,
			unsigned = read_int24, -- 24-bit is typically signed
			max_value = 8388607
		},
		[32] = {
			signed = read_int32,
			unsigned = read_int32, -- 32-bit is typically signed
			max_value = 2147483647,
			float = read_float32,
			float_max = 1.0
		}
	}	-- Sample reading functions based on format
	
	if self.askForWaveFile then
		filename = self:getWaveFile()
		if #filename == 0 then
			return result
		end
		
		filename = self:getCleanFilename(filename)
		if not self:isFileExists(filename) then
			self:show(filename .. " " .. SV:T("not found!"))
			return result
		end
		self.audioFile = filename
	else
		self.audioFile = self.pathAudioFile .. self.audioFile
	end
	
	-- Analyze audio wav file
	local error, result, infos, volume_data = self:analyze_wav_file(self.audioFile)
	
	if not error then
		local json_data = {
			metadata = {
				format = SV:T("WAV Volume Analysis"),
				timestamp = os.date("%Y-%m-%d %H:%M:%S"),
				total_data = #volume_data
			},
			volume_data = {}
		}
		
	    -- Simplify data for JSON (just time and normalized volume)
		for _, data in ipairs(volume_data) do
			table.insert(json_data.volume_data, {
				time = math.floor(data.time * 1000) / 1000, -- Round to 3 decimals
				volume = math.floor(data.volume * 1000) / 1000 -- Round to 3 decimals
			})
		end
		json = load_json()	
		local json_string = json.stringify(json_data)

		-- Process is ok
		local groupNotes = self.currentGroupNotes
		local firstNote = groupNotes:getNote(1)
		local lastNote = groupNotes:getNote(groupNotes:getNumNotes())
		local loudness = groupNotes:getParameter("loudness")
		loudness:removeAll()
			
		if json_string ~= nil then
			if #json_string > 0 then
				local js = json.parse(json_string)
				-- {
				  -- "metadata": {
					-- "format": "WAV Volume Analysis",
					-- "timestamp": "2025-06-28 10:30:00",
					-- "total_samples": 1250
				  -- },
				  -- "volume_data": [
					-- {"time": 0.0, "volume": 0.245},
					-- {"time": 0.1, "volume": 0.387},
					-- {"time": 0.2, "volume": 0.512}
				  -- ]
				-- }

				local length = #volume_data -- js.length
				local data = js.volume_data
				
				local firstPos = self.timeAxis:getSecondsFromBlick( firstNote:getOnset() - SV.QUARTER)
				local lastPos = self.timeAxis:getSecondsFromBlick(lastNote:getEnd())

				-- Add first note pos volume = 0
				local timeFist = self.timeAxis:getBlickFromSeconds(firstPos)
				loudness:add(timeFist, 0)
				-- Add last note pos volume = 0
				local timeLast = self.timeAxis:getBlickFromSeconds(lastPos)
				loudness:add(timeLast, 0)
				
				for iPos = 1, #data do
					local timeInfo = self.timeAxis:getBlickFromSeconds(data[iPos].time)
					if data[iPos].volume > 0 then
						loudness:add(timeInfo, data[iPos].volume * self.loudnessWeight) -- Add loudness
					end
				end
				loudness:simplify(groupNotes:getNote(1):getOnset(), lastNote:getOnset(), 0.01)
				
				result = true
				self:show(SV:T("Group: ") .. self.currentGroupName .. "\r"
				.. SV:T("File: ") .. self.audioFile .. "\r"
				.. infos .. "\r" .. SV:T("Done!"))
			else
				self:show(SV:T("Nothing to read!"))
			end
		else
			self:show(SV:T("Nothing to read!"))
		end
	else
		self:show(result) -- error
	end
	return result
end

-- Main process
function main()
	local notesObject = NotesObject:new()
	notesObject:start()
	
	-- End of script
	SV:finish()
end

--https://gist.github.com/tylerneylon/59f4bcf316be525b30ab
--[[ json.lua

A compact pure-Lua JSON library.
The main functions are: json.stringify, json.parse.

## json.stringify:

This expects the following to be true of any tables being encoded:
 * They only have string or number keys. Number keys must be represented as
   strings in json; this is part of the json spec.
 * They are not recursive. Such a structure cannot be specified in json.

A Lua table is considered to be an array if and only if its set of keys is a
consecutive sequence of positive integers starting at 1. Arrays are encoded like
so: `[2, 3, false, "hi"]`. Any other type of Lua table is encoded as a json
object, encoded like so: `{"key1": 2, "key2": false}`.

Because the Lua nil value cannot be a key, and as a table value is considerd
equivalent to a missing key, there is no way to express the json "null" value in
a Lua table. The only way this will output "null" is if your entire input obj is
nil itself.

An empty Lua table, {}, could be considered either a json object or array -
it's an ambiguous edge case. We choose to treat this as an object as it is the
more general type.

To be clear, none of the above considerations is a limitation of this code.
Rather, it is what we get when we completely observe the json specification for
as arbitrary a Lua object as json is capable of expressing.

## json.parse:

This function parses json, with the exception that it does not pay attention to
\u-escaped unicode code points in strings.

It is difficult for Lua to return null as a value. In order to prevent the loss
of keys with a null value in a json string, this function uses the one-off
table value json.null (which is just an empty table) to indicate null values.
This way you can check if a value is null with the conditional
`val == json.null`.

If you have control over the data and are using Lua, I would recommend just
avoiding null values in your data to begin with.

--]]

function load_json()
	json = {}


	-- Internal functions.

	local function kind_of(obj)
	  if type(obj) ~= 'table' then return type(obj) end
	  local i = 1
	  for _ in pairs(obj) do
		if obj[i] ~= nil then i = i + 1 else return 'table' end
	  end
	  if i == 1 then return 'table' else return 'array' end
	end

	local function escape_str(s)
	  local in_char  = {'\\', '"', '/', '\b', '\f', '\n', '\r', '\t'}
	  local out_char = {'\\', '"', '/',  'b',  'f',  'n',  'r',  't'}
	  for i, c in ipairs(in_char) do
		s = s:gsub(c, '\\' .. out_char[i])
	  end
	  return s
	end

	-- Returns pos, did_find; there are two cases:
	-- 1. Delimiter found: pos = pos after leading space + delim; did_find = true.
	-- 2. Delimiter not found: pos = pos after leading space;     did_find = false.
	-- This throws an error if err_if_missing is true and the delim is not found.
	local function skip_delim(str, pos, delim, err_if_missing)
	  pos = pos + #str:match('^%s*', pos)
	  if str:sub(pos, pos) ~= delim then
		if err_if_missing then
		  error('Expected ' .. delim .. ' near position ' .. pos)
		end
		return pos, false
	  end
	  return pos + 1, true
	end

	-- Expects the given pos to be the first character after the opening quote.
	-- Returns val, pos; the returned pos is after the closing quote character.
	local function parse_str_val(str, pos, val)
	  val = val or ''
	  local early_end_error = 'End of input found while parsing string.'
	  if pos > #str then error(early_end_error) end
	  local c = str:sub(pos, pos)
	  if c == '"'  then return val, pos + 1 end
	  if c ~= '\\' then return parse_str_val(str, pos + 1, val .. c) end
	  -- We must have a \ character.
	  local esc_map = {b = '\b', f = '\f', n = '\n', r = '\r', t = '\t'}
	  local nextc = str:sub(pos + 1, pos + 1)
	  if not nextc then error(early_end_error) end
	  return parse_str_val(str, pos + 2, val .. (esc_map[nextc] or nextc))
	end

	-- Returns val, pos; the returned pos is after the number's final character.
	local function parse_num_val(str, pos)
	  local num_str = str:match('^-?%d+%.?%d*[eE]?[+-]?%d*', pos)
	  local val = tonumber(num_str)
	  if not val then error('Error parsing number at position ' .. pos .. '.') end
	  return val, pos + #num_str
	end


	-- Public values and functions.

	function json.stringify(obj, as_key)
	  local s = {}  -- We'll build the string as an array of strings to be concatenated.
	  local kind = kind_of(obj)  -- This is 'array' if it's an array or type(obj) otherwise.
	  if kind == 'array' then
		if as_key then error('Can\'t encode array as key.') end
		s[#s + 1] = '['
		for i, val in ipairs(obj) do
		  if i > 1 then s[#s + 1] = ', ' end
		  s[#s + 1] = json.stringify(val)
		end
		s[#s + 1] = ']'
	  elseif kind == 'table' then
		if as_key then error('Can\'t encode table as key.') end
		s[#s + 1] = '{'
		for k, v in pairs(obj) do
		  if #s > 1 then s[#s + 1] = ', ' end
		  s[#s + 1] = json.stringify(k, true)
		  s[#s + 1] = ':'
		  s[#s + 1] = json.stringify(v)
		end
		s[#s + 1] = '}'
	  elseif kind == 'string' then
		return '"' .. escape_str(obj) .. '"'
	  elseif kind == 'number' then
		if as_key then return '"' .. tostring(obj) .. '"' end
		return tostring(obj)
	  elseif kind == 'boolean' then
		return tostring(obj)
	  elseif kind == 'nil' then
		return 'null'
	  else
		error('Unjsonifiable type: ' .. kind .. '.')
	  end
	  return table.concat(s)
	end

	json.null = {}  -- This is a one-off table to represent the null value.

	function json.parse(str, pos, end_delim)
	  pos = pos or 1
	  if str == nil or pos > #str then error('Reached unexpected end of input, pos: ' .. pos) end
	  local pos = pos + #str:match('^%s*', pos)  -- Skip whitespace.
	  local first = str:sub(pos, pos)
	  if first == '{' then  -- Parse an object.
		local obj, key, delim_found = {}, true, true
		pos = pos + 1
		while true do
		  key, pos = json.parse(str, pos, '}')
		  if key == nil then return obj, pos end
		  if not delim_found then error('Comma missing between object items.') end
		  pos = skip_delim(str, pos, ':', true)  -- true -> error if missing.
		  obj[key], pos = json.parse(str, pos)
		  pos, delim_found = skip_delim(str, pos, ',')
		end
	  elseif first == '[' then  -- Parse an array.
		local arr, val, delim_found = {}, true, true
		pos = pos + 1
		while true do
		  val, pos = json.parse(str, pos, ']')
		  if val == nil then return arr, pos end
		  if not delim_found then error('Comma missing between array items.') end
		  arr[#arr + 1] = val
		  pos, delim_found = skip_delim(str, pos, ',')
		end
	  elseif first == '"' then  -- Parse a string.
		return parse_str_val(str, pos + 1)
	  elseif first == '-' or first:match('%d') then  -- Parse a number.
		return parse_num_val(str, pos)
	  elseif first == end_delim then  -- End of an object or array.
		return nil, pos + 1
	  else  -- Parse true, false, or null.
		local literals = {['true'] = true, ['false'] = false, ['null'] = json.null}
		for lit_str, lit_val in pairs(literals) do
		  local lit_end = pos + #lit_str - 1
		  if str:sub(pos, lit_end) == lit_str then return lit_val, lit_end + 1 end
		end
		local pos_info_str = 'position ' .. pos .. ': ' .. str:sub(pos, pos + 10)
		error('Invalid json syntax starting at ' .. pos_info_str)
	  end
	end

	return json
end
