function(quiet_message)
    if (NOT FFMPEG_FIND_QUIETLY)
        message(${ARGV})
    endif()
endfunction()

function(required_message)
    if (FFMPEG_FIND_REQUIRED OR COMPONENT_REQUIRED)
        message(${ARGV})
    else()
        quiet_message(${ARGV})
    endif()
endfunction()

function(required_error)
    if (FFMPEG_FIND_REQUIRED OR COMPONENT_REQUIRED)
        message(FATAL_ERROR "${ARGV}")
    else()
        quiet_message(STATUS "${ARGV}")
    endif()
endfunction()

quiet_message(STATUS "Looking for FFMPEG")
set(FFMPEG_FOUND TRUE)

function(consume_component comp)
    list(FIND FFMPEG_FIND_COMPONENTS ${comp} want_comp)
    set(COMPONENT_REQUIRED ${FFMPEG_FIND_REQUIRED_${comp}})
    if(${want_comp} GREATER_EQUAL 0)
        quiet_message(STATUS "Looking for component ${comp}")

        quiet_message(STATUS "Looking for ${comp} library")
        find_library(FFMPEG_${comp}_LIB NAMES ${comp} PATHS ENV FFMPEG_LIBRARY_PATH)
        if (FFMPEG_${comp}_LIB)
            quiet_message(STATUS "Looking for ${comp} library - found (${FFMPEG_${comp}_LIB})")
        else()
            required_message(STATUS "Looking for ${comp} library - not found")
        endif()

        quiet_message(STATUS "Looking for ${comp} header")
        # ffmpeg Nux builds for CentOS place FFMPEG headers under an additional ffmpeg directory
        find_path(FFMPEG_${comp}_H NAMES ${comp}.h
            PATHS ENV FFMPEG_INCLUDE_PATH PATH_SUFFIXES lib${comp}
                ffmpeg/lib${comp} # For CentOS
        )
        if (FFMPEG_${comp}_H)
            quiet_message(STATUS "Looking for ${comp} header - found (${FFMPEG_${comp}_H}/${comp}.h)")
        else()
            required_message(STATUS "Looking for ${comp} header - not found")
        endif()

        if (FFMPEG_${comp}_LIB AND FFMPEG_${comp}_H)
            add_library(FFMPEG_${comp} INTERFACE)
            target_link_libraries(FFMPEG_${comp} INTERFACE ${FFMPEG_${comp}_LIB})
            get_filename_component(FFMPEG_${comp}_H_DIR ${FFMPEG_${comp}_H} DIRECTORY)
            set(FFMPEG_${comp}_H ${FFMPEG_${comp}_H_DIR} CACHE PATH "" FORCE)
            target_include_directories(FFMPEG_${comp} INTERFACE ${FFMPEG_${comp}_H})
            quiet_message(STATUS "Looking for component ${comp} - found")
            list(REMOVE_AT FFMPEG_FIND_COMPONENTS ${want_comp})
            set(FFMPEG_FIND_COMPONENTS ${FFMPEG_FIND_COMPONENTS} PARENT_SCOPE)
        else()
            set(FFMPEG_FOUND FALSE)
            required_error("Looking for component ${comp} - not found")
        endif()
    endif()
endfunction()

foreach(comp avcodec avformat avutil swscale)
    consume_component(${comp})
endforeach()

list(LENGTH FFMPEG_FIND_COMPONENTS remaining_components)
if(${remaining_components} GREATER 0)
    message(FATAL_ERROR "Components [${FFMPEG_FIND_COMPONENTS}] are unknown to the FFMPEG find module")
endif()

quiet_message(STATUS "Looking for FFMPEG - found")
