├── .gitignore ├── .travis.yml ├── LICENSE.md ├── README.md ├── demuxer.cpp ├── demuxer.h ├── display.cpp ├── display.h ├── ffmpeg.cpp ├── ffmpeg.h ├── format_converter.cpp ├── format_converter.h ├── main.cpp ├── makefile ├── player.cpp ├── player.h ├── queue.h ├── timer.cpp ├── timer.h ├── video_decoder.cpp └── video_decoder.h /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files 2 | *.slo 3 | *.lo 4 | *.o 5 | 6 | # Compiled Dynamic libraries 7 | *.so 8 | *.dylib 9 | 10 | # Compiled Static libraries 11 | *.lai 12 | *.la 13 | *.a 14 | 15 | # Executable 16 | player 17 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: cpp 2 | compiler: gcc 3 | before_install: 4 | # GCC 4.9 needed for more complete c++11 support 5 | - sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y 6 | - sudo add-apt-repository ppa:zoogie/sdl2-snapshots -y 7 | - sudo apt-get update -qq 8 | install: 9 | # GCC 10 | - sudo apt-get install -y g++-4.9 11 | - sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.9 50 12 | # SDL 13 | - sudo apt-get install -y libsdl2 libsdl2-dev 14 | # FFmpeg 15 | - sudo apt-get install -y yasm 16 | - mkdir tmp && pushd tmp 17 | - wget http://ffmpeg.org/releases/ffmpeg-snapshot.tar.bz2 18 | - tar xvf ffmpeg-snapshot.tar.bz2 19 | - cd ffmpeg 20 | - ./configure --prefix=/usr --enable-shared --disable-static 21 | --disable-programs --disable-doc --disable-avdevice --disable-postproc 22 | --disable-avfilter 23 | - make 24 | - sudo make install 25 | - make distclean 26 | - popd && rm -rf tmp 27 | script: make 28 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | player 2 | ====== 3 | 4 | Video player written in C++14 using FFmpeg libraries and SDL2 5 | 6 | Usage 7 | ----- 8 | 9 | ./player video.mp4 10 | 11 | Controls 12 | -------- 13 | 14 | * Space: Toggle play/pause 15 | * Escape: Quit 16 | 17 | Build 18 | ----- 19 | 20 | sudo pacman -S ffmpeg sdl2 21 | make 22 | -------------------------------------------------------------------------------- /demuxer.cpp: -------------------------------------------------------------------------------- 1 | #include "demuxer.h" 2 | #include "ffmpeg.h" 3 | 4 | Demuxer::Demuxer(const std::string &file_name) { 5 | ffmpeg::check(avformat_open_input( 6 | &format_context_, file_name.c_str(), nullptr, nullptr)); 7 | ffmpeg::check(avformat_find_stream_info( 8 | format_context_, nullptr)); 9 | video_stream_index_ = ffmpeg::check(av_find_best_stream( 10 | format_context_, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0)); 11 | } 12 | 13 | Demuxer::~Demuxer() { 14 | avformat_close_input(&format_context_); 15 | } 16 | 17 | AVCodecParameters* Demuxer::video_codec_parameters() { 18 | return format_context_->streams[video_stream_index_]->codecpar; 19 | } 20 | 21 | int Demuxer::video_stream_index() const { 22 | return video_stream_index_; 23 | } 24 | 25 | AVRational Demuxer::time_base() const { 26 | return format_context_->streams[video_stream_index_]->time_base; 27 | } 28 | 29 | bool Demuxer::operator()(AVPacket &packet) { 30 | return av_read_frame(format_context_, &packet) >= 0; 31 | } 32 | -------------------------------------------------------------------------------- /demuxer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | extern "C" { 4 | #include "libavformat/avformat.h" 5 | } 6 | 7 | class Demuxer { 8 | public: 9 | Demuxer(const std::string &file_name); 10 | ~Demuxer(); 11 | AVCodecParameters* video_codec_parameters(); 12 | int video_stream_index() const; 13 | AVRational time_base() const; 14 | bool operator()(AVPacket &packet); 15 | 16 | private: 17 | AVFormatContext* format_context_{}; 18 | int video_stream_index_{}; 19 | }; 20 | -------------------------------------------------------------------------------- /display.cpp: -------------------------------------------------------------------------------- 1 | #include "display.h" 2 | #include 3 | 4 | template 5 | inline T check_SDL(T value, const std::string &message) { 6 | if (!value) { 7 | throw std::runtime_error{"SDL " + message}; 8 | } else { 9 | return value; 10 | } 11 | } 12 | 13 | SDL::SDL() { 14 | check_SDL(!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER), "init"); 15 | } 16 | 17 | SDL::~SDL() { 18 | SDL_Quit(); 19 | } 20 | 21 | Display::Display(const unsigned width, const unsigned height) : 22 | window_{check_SDL(SDL_CreateWindow( 23 | "player", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 24 | width, height, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE), 25 | "window"), SDL_DestroyWindow}, 26 | renderer_{check_SDL(SDL_CreateRenderer( 27 | window_.get(), -1, 28 | SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC), 29 | "renderer"), SDL_DestroyRenderer}, 30 | texture_{check_SDL(SDL_CreateTexture( 31 | renderer_.get(), SDL_PIXELFORMAT_YV12, SDL_TEXTUREACCESS_STREAMING, 32 | width, height), "renderer"), SDL_DestroyTexture} { 33 | 34 | SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear"); 35 | SDL_RenderSetLogicalSize(renderer_.get(), width, height); 36 | 37 | SDL_SetRenderDrawColor(renderer_.get(), 0, 0, 0, 255); 38 | SDL_RenderClear(renderer_.get()); 39 | SDL_RenderPresent(renderer_.get()); 40 | } 41 | 42 | void Display::refresh( 43 | std::array planes, std::array pitches) { 44 | check_SDL(!SDL_UpdateYUVTexture( 45 | texture_.get(), nullptr, 46 | planes[0], pitches[0], 47 | planes[1], pitches[1], 48 | planes[2], pitches[2]), "texture update"); 49 | SDL_RenderClear(renderer_.get()); 50 | SDL_RenderCopy(renderer_.get(), texture_.get(), nullptr, nullptr); 51 | SDL_RenderPresent(renderer_.get()); 52 | } 53 | 54 | void Display::input() { 55 | if (SDL_PollEvent(&event_)) { 56 | switch (event_.type) { 57 | case SDL_KEYUP: 58 | switch (event_.key.keysym.sym) { 59 | case SDLK_ESCAPE: 60 | quit_ = true; 61 | break; 62 | case SDLK_SPACE: 63 | play_ = !play_; 64 | break; 65 | default: 66 | break; 67 | } 68 | break; 69 | case SDL_QUIT: 70 | quit_ = true; 71 | break; 72 | default: 73 | break; 74 | } 75 | } 76 | } 77 | 78 | bool Display::get_quit() { 79 | return quit_; 80 | } 81 | 82 | bool Display::get_play() { 83 | return play_; 84 | } 85 | -------------------------------------------------------------------------------- /display.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "SDL2/SDL.h" 3 | #include 4 | #include 5 | 6 | struct SDL { 7 | SDL(); 8 | ~SDL(); 9 | }; 10 | 11 | class Display { 12 | private: 13 | bool quit_{false}; 14 | bool play_{true}; 15 | 16 | SDL sdl_; 17 | std::unique_ptr window_; 18 | std::unique_ptr renderer_; 19 | std::unique_ptr texture_; 20 | SDL_Event event_; 21 | 22 | public: 23 | Display(const unsigned width, const unsigned height); 24 | 25 | // Copy frame to display 26 | void refresh( 27 | std::array planes, std::array pitches); 28 | 29 | // Handle events 30 | void input(); 31 | 32 | bool get_quit(); 33 | bool get_play(); 34 | }; 35 | -------------------------------------------------------------------------------- /ffmpeg.cpp: -------------------------------------------------------------------------------- 1 | #include "ffmpeg.h" 2 | 3 | namespace ffmpeg { 4 | std::string error_string(const int error_code) { 5 | constexpr size_t size{64}; 6 | std::array buffer; 7 | av_make_error_string(buffer.data(), size, error_code); 8 | return "FFmpeg: " + std::string(buffer.data()); 9 | } 10 | 11 | Error::Error(const std::string &message) : 12 | std::runtime_error{"FFmpeg: " + message} { 13 | } 14 | 15 | Error::Error(const int status) : 16 | std::runtime_error{error_string(status)} { 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /ffmpeg.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | extern "C" { 5 | #include "libavutil/avutil.h" 6 | } 7 | 8 | namespace ffmpeg { 9 | class Error : std::runtime_error { 10 | public: 11 | Error(const std::string &message); 12 | Error(int status); 13 | }; 14 | 15 | std::string error_string(const int error_code); 16 | 17 | inline int check(const int status) { 18 | if (status < 0) { 19 | throw ffmpeg::Error{status}; 20 | } 21 | return status; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /format_converter.cpp: -------------------------------------------------------------------------------- 1 | #include "format_converter.h" 2 | 3 | FormatConverter::FormatConverter( 4 | size_t width, size_t height, 5 | AVPixelFormat input_pixel_format, AVPixelFormat output_pixel_format) : 6 | width_{width}, height_{height}, conversion_context_{sws_getContext( 7 | // Source 8 | width, height, input_pixel_format, 9 | // Destination 10 | width, height, output_pixel_format, 11 | // Filters 12 | SWS_BICUBIC, nullptr, nullptr, nullptr)} { 13 | } 14 | 15 | void FormatConverter::operator()(AVFrame* src, AVFrame* dst) { 16 | sws_scale(conversion_context_, 17 | // Source 18 | src->data, src->linesize, 0, height_, 19 | // Destination 20 | dst->data, dst->linesize); 21 | } 22 | -------------------------------------------------------------------------------- /format_converter.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | extern "C" { 3 | #include "libavformat/avformat.h" 4 | #include "libswscale/swscale.h" 5 | } 6 | 7 | class FormatConverter { 8 | public: 9 | FormatConverter( 10 | size_t width, size_t height, 11 | AVPixelFormat input_pixel_format, AVPixelFormat output_pixel_format); 12 | void operator()(AVFrame* src, AVFrame* dst); 13 | private: 14 | size_t width_; 15 | size_t height_; 16 | SwsContext* conversion_context_{}; 17 | }; 18 | -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | #include "player.h" 2 | #include 3 | #include 4 | #include 5 | 6 | int main(int argc, char** argv) { 7 | try { 8 | if (argc != 2) { 9 | throw std::logic_error{"Not enough arguments"}; 10 | } 11 | 12 | Player play{argv[1]}; 13 | play(); 14 | } 15 | 16 | catch (const std::exception &e) { 17 | std::cerr << "Error: " << e.what() << std::endl; 18 | return -1; 19 | } 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /makefile: -------------------------------------------------------------------------------- 1 | CXX = g++ 2 | CXXFLAGS = -g3 -std=c++14 -D__STDC_CONSTANT_MACROS \ 3 | -Wall -Wextra -Wextra -pedantic \ 4 | -Wdisabled-optimization -Wctor-dtor-privacy -Wmissing-declarations \ 5 | -Woverloaded-virtual -Wshadow -Wno-unused -Winline 6 | LDLIBS = -lavformat -lavcodec -lavutil -lswscale -lSDL2 -pthread 7 | 8 | src = $(wildcard *.cpp) 9 | obj = $(src:.cpp=.o) 10 | dep = $(obj:.o=.d) 11 | target = player 12 | 13 | all: $(target) 14 | 15 | $(target): $(obj) 16 | $(CXX) -o $@ $^ $(LDLIBS) 17 | 18 | -include $(dep) 19 | 20 | %.d: %.cpp 21 | @$(CXX) $(CXXFLAGS) $< -MM -MT $(@:.d=.o) >$@ 22 | 23 | test: $(target) 24 | ./$(target) test.mkv 25 | 26 | .PHONY: clean 27 | clean: 28 | $(RM) $(obj) $(target) $(dep) 29 | -------------------------------------------------------------------------------- /player.cpp: -------------------------------------------------------------------------------- 1 | #include "player.h" 2 | #include 3 | #include 4 | #include 5 | #include 6 | extern "C" { 7 | #include 8 | #include 9 | #include 10 | } 11 | 12 | const size_t Player::queue_size_{5}; 13 | 14 | Player::Player(const std::string &file_name) : 15 | demuxer_{std::make_unique(file_name)}, 16 | video_decoder_{std::make_unique( 17 | demuxer_->video_codec_parameters())}, 18 | format_converter_{std::make_unique( 19 | video_decoder_->width(), video_decoder_->height(), 20 | video_decoder_->pixel_format(), AV_PIX_FMT_YUV420P)}, 21 | display_{std::make_unique( 22 | video_decoder_->width(), video_decoder_->height())}, 23 | timer_{std::make_unique()}, 24 | packet_queue_{std::make_unique(queue_size_)}, 25 | frame_queue_{std::make_unique(queue_size_)} { 26 | } 27 | 28 | void Player::operator()() { 29 | stages_.emplace_back(&Player::demultiplex, this); 30 | stages_.emplace_back(&Player::decode_video, this); 31 | video(); 32 | 33 | for (auto &stage : stages_) { 34 | stage.join(); 35 | } 36 | 37 | if (exception_) { 38 | std::rethrow_exception(exception_); 39 | } 40 | } 41 | 42 | void Player::demultiplex() { 43 | try { 44 | for (;;) { 45 | // Create AVPacket 46 | std::unique_ptr> packet{ 47 | av_packet_alloc(), 48 | [](AVPacket* p){ av_packet_free(&p); }}; 49 | packet->data = nullptr; 50 | 51 | // Read frame into AVPacket 52 | if (!(*demuxer_)(*packet)) { 53 | packet_queue_->finished(); 54 | break; 55 | } 56 | 57 | // Move into queue if first video stream 58 | if (packet->stream_index == demuxer_->video_stream_index()) { 59 | if (!packet_queue_->push(std::move(packet))) { 60 | break; 61 | } 62 | } 63 | } 64 | } catch (...) { 65 | exception_ = std::current_exception(); 66 | frame_queue_->quit(); 67 | packet_queue_->quit(); 68 | } 69 | } 70 | 71 | void Player::decode_video() { 72 | try { 73 | const AVRational microseconds = {1, 1000000}; 74 | 75 | for (;;) { 76 | // Create AVFrame and AVQueue 77 | std::unique_ptr> 78 | frame_decoded{ 79 | av_frame_alloc(), [](AVFrame* f){ av_frame_free(&f); }}; 80 | std::unique_ptr> packet{ 81 | nullptr, [](AVPacket* p){ av_packet_unref(p); delete p; }}; 82 | 83 | // Read packet from queue 84 | if (!packet_queue_->pop(packet)) { 85 | frame_queue_->finished(); 86 | break; 87 | } 88 | 89 | // If the packet didn't send, receive more frames and try again 90 | bool sent = false; 91 | while (!sent) { 92 | sent = video_decoder_->send(packet.get()); 93 | 94 | // If a whole frame has been decoded, 95 | // adjust time stamps and add to queue 96 | while (video_decoder_->receive(frame_decoded.get())) { 97 | frame_decoded->pts = av_rescale_q( 98 | frame_decoded->pkt_dts, 99 | demuxer_->time_base(), 100 | microseconds); 101 | 102 | std::unique_ptr> 103 | frame_converted{ 104 | av_frame_alloc(), 105 | [](AVFrame* f){ av_free(f->data[0]); }}; 106 | if (av_frame_copy_props(frame_converted.get(), 107 | frame_decoded.get()) < 0) { 108 | throw std::runtime_error("Copying frame properties"); 109 | } 110 | if (av_image_alloc( 111 | frame_converted->data, frame_converted->linesize, 112 | video_decoder_->width(), video_decoder_->height(), 113 | video_decoder_->pixel_format(), 1) < 0) { 114 | throw std::runtime_error("Allocating picture"); 115 | } 116 | (*format_converter_)( 117 | frame_decoded.get(), frame_converted.get()); 118 | 119 | if (!frame_queue_->push(std::move(frame_converted))) { 120 | break; 121 | } 122 | } 123 | } 124 | } 125 | } catch (...) { 126 | exception_ = std::current_exception(); 127 | frame_queue_->quit(); 128 | packet_queue_->quit(); 129 | } 130 | } 131 | 132 | void Player::video() { 133 | try { 134 | int64_t last_pts = 0; 135 | 136 | for (uint64_t frame_number = 0;; ++frame_number) { 137 | 138 | display_->input(); 139 | 140 | if (display_->get_quit()) { 141 | break; 142 | 143 | } else if (display_->get_play()) { 144 | std::unique_ptr> frame{ 145 | nullptr, [](AVFrame* f){ av_frame_free(&f); }}; 146 | if (!frame_queue_->pop(frame)) { 147 | break; 148 | } 149 | 150 | if (frame_number) { 151 | const int64_t frame_delay = frame->pts - last_pts; 152 | last_pts = frame->pts; 153 | timer_->wait(frame_delay); 154 | 155 | } else { 156 | last_pts = frame->pts; 157 | timer_->update(); 158 | } 159 | 160 | display_->refresh( 161 | {frame->data[0], frame->data[1], frame->data[2]}, 162 | {static_cast(frame->linesize[0]), 163 | static_cast(frame->linesize[1]), 164 | static_cast(frame->linesize[2])}); 165 | 166 | } else { 167 | std::chrono::milliseconds sleep(10); 168 | std::this_thread::sleep_for(sleep); 169 | timer_->update(); 170 | } 171 | } 172 | 173 | } catch (...) { 174 | exception_ = std::current_exception(); 175 | } 176 | 177 | frame_queue_->quit(); 178 | packet_queue_->quit(); 179 | } 180 | -------------------------------------------------------------------------------- /player.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "demuxer.h" 3 | #include "display.h" 4 | #include "format_converter.h" 5 | #include "queue.h" 6 | #include "timer.h" 7 | #include "video_decoder.h" 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | class Player { 14 | public: 15 | Player(const std::string &file_name); 16 | void operator()(); 17 | private: 18 | void demultiplex(); 19 | void decode_video(); 20 | void video(); 21 | private: 22 | std::unique_ptr demuxer_; 23 | std::unique_ptr video_decoder_; 24 | std::unique_ptr format_converter_; 25 | std::unique_ptr display_; 26 | std::unique_ptr timer_; 27 | std::unique_ptr packet_queue_; 28 | std::unique_ptr frame_queue_; 29 | std::vector stages_; 30 | static const size_t queue_size_; 31 | std::exception_ptr exception_{}; 32 | }; 33 | -------------------------------------------------------------------------------- /queue.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | struct AVPacket; 10 | struct AVFrame; 11 | 12 | template 13 | class Queue { 14 | protected: 15 | // Data 16 | std::queue queue_; 17 | typename std::queue::size_type size_max_; 18 | 19 | // Thread gubbins 20 | std::mutex mutex_; 21 | std::condition_variable full_; 22 | std::condition_variable empty_; 23 | 24 | // Exit 25 | std::atomic_bool quit_{false}; 26 | std::atomic_bool finished_{false}; 27 | 28 | public: 29 | Queue(const size_t size_max); 30 | 31 | bool push(T &&data); 32 | bool pop(T &data); 33 | 34 | // The queue has finished accepting input 35 | void finished(); 36 | // The queue will cannot be pushed or popped 37 | void quit(); 38 | 39 | }; 40 | 41 | using PacketQueue = 42 | Queue>>; 43 | using FrameQueue = 44 | Queue>>; 45 | 46 | template 47 | Queue::Queue(size_t size_max) : 48 | size_max_{size_max} { 49 | } 50 | 51 | template 52 | bool Queue::push(T &&data) { 53 | std::unique_lock lock(mutex_); 54 | 55 | while (!quit_ && !finished_) { 56 | 57 | if (queue_.size() < size_max_) { 58 | queue_.push(std::move(data)); 59 | 60 | empty_.notify_all(); 61 | return true; 62 | } else { 63 | full_.wait(lock); 64 | } 65 | } 66 | 67 | return false; 68 | } 69 | 70 | template 71 | bool Queue::pop(T &data) { 72 | std::unique_lock lock(mutex_); 73 | 74 | while (!quit_) { 75 | 76 | if (!queue_.empty()) { 77 | data = std::move(queue_.front()); 78 | queue_.pop(); 79 | 80 | full_.notify_all(); 81 | return true; 82 | } else if (queue_.empty() && finished_) { 83 | return false; 84 | } else { 85 | empty_.wait(lock); 86 | } 87 | } 88 | 89 | return false; 90 | } 91 | 92 | template 93 | void Queue::finished() { 94 | finished_ = true; 95 | empty_.notify_all(); 96 | } 97 | 98 | template 99 | void Queue::quit() { 100 | quit_ = true; 101 | empty_.notify_all(); 102 | full_.notify_all(); 103 | } 104 | -------------------------------------------------------------------------------- /timer.cpp: -------------------------------------------------------------------------------- 1 | #include "timer.h" 2 | #include 3 | #include 4 | 5 | Timer::Timer() : 6 | target_time_{std::chrono::high_resolution_clock::now()} { 7 | } 8 | 9 | void Timer::wait(const int64_t period) { 10 | target_time_ += std::chrono::microseconds{period}; 11 | 12 | const auto lag = 13 | std::chrono::duration_cast( 14 | target_time_ - std::chrono::high_resolution_clock::now()) + 15 | std::chrono::microseconds{adjust()}; 16 | 17 | std::this_thread::sleep_for(lag); 18 | 19 | const int64_t error = 20 | std::chrono::duration_cast( 21 | std::chrono::high_resolution_clock::now() - target_time_).count(); 22 | derivative_ = error - proportional_; 23 | integral_ += error; 24 | proportional_ = error; 25 | 26 | } 27 | 28 | void Timer::update() { 29 | target_time_ = std::chrono::high_resolution_clock::now(); 30 | } 31 | 32 | int64_t Timer::adjust() const { 33 | return P_ * proportional_ + I_ * integral_ + D_ * derivative_; 34 | } 35 | -------------------------------------------------------------------------------- /timer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | class Timer { 6 | private: 7 | std::chrono::time_point target_time_; 8 | 9 | int64_t proportional_{}; 10 | int64_t integral_{}; 11 | int64_t derivative_{}; 12 | 13 | constexpr static double P_{0.0}; 14 | constexpr static double I_{-1.0}; 15 | constexpr static double D_{0.0}; 16 | 17 | public: 18 | Timer(); 19 | void wait(int64_t period); 20 | void update(); 21 | 22 | private: 23 | int64_t adjust() const; 24 | }; 25 | -------------------------------------------------------------------------------- /video_decoder.cpp: -------------------------------------------------------------------------------- 1 | #include "video_decoder.h" 2 | #include "ffmpeg.h" 3 | 4 | VideoDecoder::VideoDecoder(AVCodecParameters* codec_parameters) { 5 | const auto codec = avcodec_find_decoder(codec_parameters->codec_id); 6 | if (!codec) { 7 | throw ffmpeg::Error{"Unsupported video codec"}; 8 | } 9 | codec_context_ = avcodec_alloc_context3(codec); 10 | if (!codec_context_) { 11 | throw ffmpeg::Error{"Couldn't allocate video codec context"}; 12 | } 13 | ffmpeg::check(avcodec_parameters_to_context( 14 | codec_context_, codec_parameters)); 15 | ffmpeg::check(avcodec_open2(codec_context_, codec, nullptr)); 16 | } 17 | 18 | VideoDecoder::~VideoDecoder() { 19 | avcodec_free_context(&codec_context_); 20 | } 21 | 22 | bool VideoDecoder::send(AVPacket* packet) { 23 | auto ret = avcodec_send_packet(codec_context_, packet); 24 | if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { 25 | return false; 26 | } else { 27 | ffmpeg::check(ret); 28 | return true; 29 | } 30 | } 31 | 32 | bool VideoDecoder::receive(AVFrame* frame) { 33 | auto ret = avcodec_receive_frame(codec_context_, frame); 34 | if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { 35 | return false; 36 | } else { 37 | ffmpeg::check(ret); 38 | return true; 39 | } 40 | } 41 | 42 | unsigned VideoDecoder::width() const { 43 | return codec_context_->width; 44 | } 45 | 46 | unsigned VideoDecoder::height() const { 47 | return codec_context_->height; 48 | } 49 | 50 | AVPixelFormat VideoDecoder::pixel_format() const { 51 | return codec_context_->pix_fmt; 52 | } 53 | 54 | AVRational VideoDecoder::time_base() const { 55 | return codec_context_->time_base; 56 | } 57 | -------------------------------------------------------------------------------- /video_decoder.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | extern "C" { 3 | #include "libavcodec/avcodec.h" 4 | } 5 | 6 | class VideoDecoder { 7 | public: 8 | VideoDecoder(AVCodecParameters* codec_parameters); 9 | ~VideoDecoder(); 10 | bool send(AVPacket* packet); 11 | bool receive(AVFrame* frame); 12 | unsigned width() const; 13 | unsigned height() const; 14 | AVPixelFormat pixel_format() const; 15 | AVRational time_base() const; 16 | private: 17 | AVCodecContext* codec_context_{}; 18 | }; 19 | --------------------------------------------------------------------------------